<?php
/**
* 搜索页面
* @author moufer<moufer@163.com>
* @package modoer
* @copyright Moufer Studio(www.modoer.com)
* @version $Id: search.php 4 2007-11-07 12:48 $
*/

define('SCRIPTNAV', 'search');
require_once './include/inc_common.php';

if($searchsubmit) {

    $searchid = intval($searchid);
    if($searchid) {

        $query = $db->query("SELECT searchstring, keyword, total, ids FROM {$dbpre}searchindex WHERE searchid='$searchid'");
        if(!$index = $db->fetch_array($query)) {
            redirect('您指定的搜索不存在或已过期，请返回。');
        }

        $offset = $_config['dpshopnumber'] ? intval($_config['dpshopnumber']) : 20;
        $limit = get_limit($page, $offset);

        $ordersort_arr = array('addtime'=>'addtime', 'review'=>'reviews', 'browse'=>'pageviews', 'grade'=>'sumreview');
        if($ordersort && array_key_exists($ordersort, $ordersort_arr)) {
            $orderby = $ordersort_arr[$ordersort].($ordertype=='desc' ? ' DESC' : ' ASC');
        } else {
            $orderby = 'addtime DESC';
        }

        $shops = array();
        $query = $db->query("SELECT * FROM {$dbpre}shops WHERE sid IN ($index[ids]) ORDER BY $orderby LIMIT $limit");
        if(!function_exists('itemToArray')) {
            require_once(MUDDER_ROOT.'./'.$_modules['shop']['directory'].'/include/fun_item.php');
        }
        while($row = $db->fetch_array($query)) {
            $shops[] = itemToArray($row);
            unset($shop);
        }
        $keyword = html_special_chars_ex($index['keyword']);
        $multipage = multi($index['total'], $offset, $page, "search.php?searchid=$searchid&ordersort=$ordersort&ordertype=$ordertype&searchsubmit=yes");

    } else {

        $filterword = array('%');
        $keyword = str_replace($filterword,'',$keyword);

        !$keyword && redirect('未填写搜索关键字，请返回填写。','search.php');

        if($searchsort == 'tag') {
            location("tag.php?tagname=".rawurlencode($keyword));
            exit;
        }
        
        $searchstring = $keyword.'|'.$searchsort."|".$searchtype."|".$panel."|".$area;
        $searchindex = array('id' => 0, 'dateline' => '0');

        $modoer_uid = $user->uid;
        $search_limit = &$_search['limit'];

        $query = $db->query("SELECT searchid, dateline,
            ('$search_limit'<>'0' AND ".(empty($modoer_uid) ? "useip='$onlineip'" : "uid='$modoer_uid'")." AND $timestamp-dateline<$search_limit) AS flood,
            (searchstring='$searchstring' AND expiration>'$timestamp') AS indexvalid
            FROM {$dbpre}searchindex
            WHERE ('$search_limit'<>'0' AND ".(empty($modoer_uid) ? "useip='$onlineip'" : "uid='$modoer_uid'")." AND $timestamp-dateline<$search_limit) OR (searchstring='$searchstring' AND expiration>'$timestamp')
            ORDER BY flood");

        while($index = $db->fetch_array($query)) {
            if($index['indexvalid'] && $index['dateline'] > $searchindex['dateline']) {
                $searchindex = array('id' => $index['searchid'], 'dateline' => $index['dateline']);
                break;
            } elseif($index['flood']) {
                redirect("对不起，您在 $search_limit 秒内只能进行一次搜索，请返回。",'search.php');
            }
        }

        if($searchindex['id']) {

            $searchid = $searchindex['id'];

        } else {

            $maxspm = &$_search['maxspm'];
            if($maxspm) {
                $total = $db->get_value("SELECT COUNT(*) FROM {$dbpre}searchindex WHERE dateline>'$timestamp'-60");
                $total >= $maxspm && redirect("对不起，每分钟系统最多响应搜索请求 $maxspm 次，请返回并稍后再试。", 'search.php');
            }

            $searchsort = 'shop';
            $where[] = 'status NOT IN(2,6)';

            if($panel != 'all' && strlen($panel) == 2) {
                $where[] = "LEFT(classcode,2)='$panel'";
            }
            if($area != 'all' && strlen($area) > 2) {
                if(strlen($area) == 4) {
                    $where[] = "LEFT(areacode,4)='$area'";
                } elseif(strlen($area) == 6) {
                    $where[] = "streetcode='$area'";
                }
            }

            if(preg_match("(AND|\+|&|\s)", $keyword) && !preg_match("(OR|\|)", $keyword)) {
                $andor = ' AND ';
                $sqltxtsrch = '1';
                $keyword = preg_replace("/( AND |&| )/is", "+", $keyword);
            } else {
                $andor = ' OR ';
                $sqltxtsrch = '0';
                $keyword = preg_replace("/( OR |\|)/is", "+", $keyword);
            }
            $keyword = str_replace('*', '%', addcslashes($keyword, '%_'));
            foreach(explode('+', $keyword) as $text) {
                $text = trim($text);
                if($text) {
                    $sqltxtsrch .= $andor;
                    if($searchtype == 'name') {
                        $sqltxtsrch .= "CONCAT(shopname,subname) LIKE '%$text%'";
                    } elseif($searchtype == 'tel') {
                        $sqltxtsrch .= "CONCAT(tel1,',',tel2) LIKE '%$text%'";        
                    } elseif($searchtype == 'address') {
                        $sqltxtsrch .= "address LIKE '%$text%'";
                    }
                }
            }

            $sql_where = implode(' AND ', $where) . " AND ($sqltxtsrch)";

            $total = $ids = '0';
            $_search['maxresults'] = $_search['maxresults'] ? intval($_search['maxresults']) : 500;
            $query = $db->query("SELECT sid FROM {$dbpre}shops WHERE $sql_where LIMIT {$_search['maxresults']}");
            while($row = $db->fetch_array($query)) {
                $ids .= ','.$row['sid'];
                $total++;
            }
            $db->free_result($query);

            $search['cachelife'] = $search['cachelife'] ? intval($search['cachelife']) : 3600;
            $expiration = $timestamp + $search['cachelife'];

            $db->query("INSERT INTO {$dbpre}searchindex (keyword, searchstring, useip, uid, dateline, expiration, total, ids) VALUES ('$keyword', '$searchstring', '$onlineip', '$modoer_uid', '$timestamp', '$expiration', '$total', '$ids')");
            $searchid = $db->insert_id();

        }

        location("search.php?searchid=$searchid&ordersort=$ordersort&ordertype=$ordertype&searchsubmit=yes");

    }

}

$subtitle = '搜索';
require_once MUDDER_ROOT.'header.php';
require_once template('shop_search');
footer();
?>
