<?php
/**
 * 
 * @file search.php
 * @copyright (c) 2005 - 2007 eifr.com
 * @license http://www.gnu.org/copyleft/gpl.html gnu/gpl
 * eifr is free software
 */

require_once(dirname(__FILE__) . '/includes/inc_general.php');
require_once(dirname(__FILE__) . '/libraries/pages.php');

/*
 * use space(" ") to split to mutil-key
 */
function getKeySql($field, $searchkey = '', $logic = '') {
    $where_sql = '';
    if($field === '') return $where_sql = '';
    if ($logic !='or') $logic = 'and';
    
    $where_sql .= " and (";
    $key_arr = getArrayWithoutEmpty($searchkey);
    $key_count = count($key_arr);
    for($i = 0;$i < $key_count;$i++) {
        if ($i == $key_count-1) $where_sql .= "$field like '%" . $key_arr[$i] . "%'";
        else $where_sql .= "$field like '%" . $key_arr[$i] . "%' $logic ";
    } 
    $where_sql .= ") ";
    return $where_sql;
} 

function getSearchResult() {
    global $db, $searchkey, $type, $searchwhere, $isdecode, $logic;

    $rtn = array();
    $rtn['list'] = array();
    $rtn['page'] = '';

    $where_sql = '';

    if ($isdecode) $searchkey = urldecode($searchkey);

    switch ($searchwhere) {
        case 'nickname':
            $uid = dbGetFieldValue(TB_USER, TF_USER_ID, TF_USER_NICK . "='$searchkey'");
            if ($uid != '') $where_sql = " and " . TFR_USER_ID . "='$uid'";
            break;
        case 'content':
            $where_sql = getKeySql('words', $searchkey, $logic);
            break;
        case 'title':
        default:
            $where_sql = getKeySql('title', $searchkey, $logic);
            break;
    } 

    $channel_sql = '';
    if ($type != '') {
        $channel_sql = " and " . TB_ARTICLE . ".channel_id like'" . $type . "%' ";
    } 

    $sql = "select id, title, title_style, issuetime, uid, price, sourcename, type, channel_id, user_channel_channelid from " . TB_ARTICLE . " where 1=1 " . $channel_sql . $where_sql . " order by issuetime desc, ordernum desc, id desc ";
    $searchkey = urlencode($searchkey);
    $rtn = dbGetRecordPages($sql, "type=$type&isdecode=$isdecode&logic=$logic&searchkey=$searchkey&searchwhere=$searchwhere");

    return $rtn;
} 

$search_select = createChannelsSelect();

$tpl_file = 'search';
if (isset($searchkey)) {
    if ($searchkey != '') $tpl_file = 'search_result';
} 

if ($tpl_file == '') $tpl_file = 'search';

require_once(getTemplatePath($tpl_file));

?>
