<?php

/**
 *
 * INDEXU
 * Copyright(C), Nicecoder, 2000-2006, All Rights Reserved.
 *
 * INDEXU(tm) is protected by Indonesia and International copyright laws.
 * Unauthorized use or distribution of INDEXU(tm) is strictly prohibited,
 * violators will be prosecuted. To obtain a license for using INDEXU(tm),
 * please register at Nicecoder home page at http://www.nicecoder.com
 *
 * Author:
 *    Dody Rachmat Wicaksono (dody@nicecoder.com)
 *    M. Zuber (zubby@nicecoder.com)
 *
 */

  /*===================================================
    ShowSearchResult()
  ===================================================*/

  function ShowSearchResult() {

    // vars global configuration
    global $dbConn, $theme_path, $category_separator,
             $search_max_rows, $max_rows, $number_of_links_format, $bold_keyword,
             $bold_format, $theme_name;

    // vars url & form
    global $pg_which, $cat;

    // vars messages
    global $msg;

    // vars template
    global $keyword, $category, $link, $pagination, $error_msg, $num_categories, $num_links, $favorites, $opt;

    $tpl     = new Template();
    $keyword = chop($keyword);

    // $opt = 0 ---> search in entire directory
    //        1 ---> search within category
    //        2 ---> search on the web using google api

    if ($opt == 2) {
      GoogleSearch();
      RunPostFilter(__FILE__);
    }

    if (empty($keyword) || strlen($keyword) < 3) {
      $error_msg = $msg["10024"];
      DisplayTemplate($theme_path . "search_error.html", "\$error_msg,\$keyword");
      RunPostFilter(__FILE__);
    }

    $keyword_org   = $keyword;
    $keywords      = explode(" ", $keyword);
    $keywords_org  = $keywords;
    $count_keyword = @count($keywords);

    $category_obj = new clsCategory;
    $category_obj->table_name             = "idx_category";
    $category_obj->link_table_name        = "idx_link";
    $category_obj->separator              = $category_separator;
    $category_obj->header                 = $msg["10021"];
    $category_obj->bold_format            = $bold_format;
    $category_obj->bold                   = $bold_keyword;
    $category_obj->keywords               = $keywords;
    $category_obj->number_of_columns      = 1;
    $category_obj->number_of_links_format = $number_of_links_format;
    $category_obj->show_subcat            = false;
    $category_obj->type_of_list           = "SEARCH_RESULT";

    // query category //

    if (empty($pg_which))
      $record_log = true;

    // build query

    $query = "select * from idx_category where 0=0";

    $i = 0;
    while ($i < $count_keyword) {
      if (substr($keywords[$i], 0, 1) == "+") {
        $keywords[$i] = substr($keywords[$i], 1);
        $query .= " and (name like '%$keywords[$i]%')";
        $eval = 1;
      }

      if (substr($keywords[$i], 0, 1) == "-") {
        $keywords[$i] = substr($keywords[$i], 1);
        $query .= " and (name not like '%$keywords[$i]%')";
        $eval = 1;
      }

      if (substr($keywords[$i], 0, 1) == "|") {
        $keywords[$i] = substr($keywords[$i], 1);

        if ($i == 0) {
          $query .= " and (name like '%$keywords[$i]%')";
        }
        else {
          $query .= " or (name like '%$keywords[$i]%')";
        }

        $eval = 1;
      }
      else {
        if ($eval != 1) {
          $query .= " and (name like '%$keywords[$i]%')";
        }
      }

      $i++;
    }

    $query .= " and visible = 1 ";

    //search within category
    
    $cats = array ();

    if ($opt == 1) {
      $cats = $category_obj->GetChildren($cat);
      $query .= " and (0 != 0";
      while (list(, $v) = @each($cats)) {
        $query .= " or category_id = $v";
      }
      $query .= " ) ";
    }

    $result = $dbConn->Execute($query);
    $num_categories = $result->RecordCount();

    if (empty($pg_which) || $pg_which == 1) {
      $category_obj->query = $query;
      $category            = $category_obj->Display();
    }

    // query links 

    $keywords  = $keywords_org;

    $users_obj             = new clsUsers;
    $users_obj->table_name = "idx_users";
    $c                     = $category_obj->GetHiddenCategories();
    $c2                    = $category_obj->GetMemberOnlyCategories();
    
    $links_obj                      = new clsLink;
    $links_obj->table_name          = "idx_link";
    $links_obj->category_table_name = "idx_category";
    $fields                         = $links_obj->GetFields();
    $num_fields                     = count($fields);

    $query = "
      select idx_link.*, 
             if (isnull(premium) || expire < now() || paid != 1, 0, premium) premium,
             if (isnull(sponsored) || expire < now() || paid != 1, 0, sponsored) sponsored
      from idx_link
           left join idx_paid_listing on (idx_link.link_id = idx_paid_listing.link_id)
           left join idx_pagerank on (idx_link.link_id = idx_pagerank.link_id)
		  where 0=0";

    $i = 0;
    while ($i < $count_keyword) {
      if (substr($keywords[$i], 0, 1) == "+") {
        $keywords[$i] = substr($keywords[$i], 1);
        $query .= " and (title like '%$keywords[$i]%' or description like '%$keywords[$i]%' or keywords like '%$keywords[$i]%'";
        for ($j = $links_obj->custom_field_offset; $j <= $num_fields; $j++) {
          if (!$links_obj->fields_searchable[$j] || $links_obj->fields_type[$j] == 'IMAGE' || $links_obj->fields_type[$j] == 'FILE') {
            continue;
          }
          $query .= " or {$links_obj->fields_name[$j]} like '%$keywords[$i]%'";
        }
        $query .= ")";
        $eval = 1;
      }

      if (substr($keywords[$i], 0, 1) == "-") {
        $keywords[$i] = substr($keywords[$i], 1);
        $query .= " and (title not like '%$keywords[$i]%' and description not like '%$keywords[$i]%' and keywords not like '%$keywords[$i]%'";
        for ($j = $links_obj->custom_field_offset; $j <= $num_fields; $j++) {
          if (!$links_obj->fields_searchable[$j] || $links_obj->fields_type[$j] == 'IMAGE' || $links_obj->fields_type[$j] == 'FILE') {
            continue;
          }
          $query .= " and {$links_obj->fields_name[$j]} not like '%$keywords[$i]%'";
        }
        $query .= ")";
        $eval = 1;
      }

      if (substr($keywords[$i], 0, 1) == "|") {
        $keywords[$i] = substr($keywords[$i], 1);

        if ($i == 0) {
          $query .= " and (title like '%$keywords[$i]%' or description like '%$keywords[$i]%' or keywords like '%$keywords[$i]%'";
          for ($j = $links_obj->custom_field_offset; $j <= $num_fields; $j++) {
            if (!$links_obj->fields_searchable[$j] || $links_obj->fields_type[$j] == 'IMAGE' || $links_obj->fields_type[$j] == 'FILE') {
              continue;
            }
            $query .= " or {$links_obj->fields_name[$j]} like '%$keywords[$i]%'";
          }
          $query .= ")";
        }
        else {
          $query .= " or (title like '%$keywords[$i]%' or description like '%$keywords[$i]%' or keywords like '%$keywords[$i]%'";
          for ($j = $links_obj->custom_field_offset; $j <= $num_fields; $j++) {
            if (!$links_obj->fields_searchable[$j] || $links_obj->fields_type[$j] == 'IMAGE' || $links_obj->fields_type[$j] == 'FILE') {
              continue;
            }
            $query .= " or {$links_obj->fields_name[$j]} like '%$keywords[$i]%'";
          }
          $query .= ")";
        }

        $eval = 1;
      }
      else {
        if ($eval != 1) {
          $query .= " and (title like '%$keywords[$i]%' or description like '%$keywords[$i]%' or keywords like '%$keywords[$i]%'";
          for ($j = $links_obj->custom_field_offset; $j <= $num_fields; $j++) {
            if (!$links_obj->fields_searchable[$j] || $links_obj->fields_type[$j] == 'IMAGE' || $links_obj->fields_type[$j] == 'FILE') {
              continue;
            }
            $query .= " or {$links_obj->fields_name[$j]} like '%$keywords[$i]%'";
          }
          $query .= ")";
        }
      }

      $i++;
    }

    // filter suspended
    $query .= " and suspended = 0 ";

    // filter unhide
    while (list(, $v) = @each($c)) {
      $query .= " and category_id != $v";
    }

    // filter member only
    if (!$users_obj->GetUserAuthentication() == 0) {
      while (list(, $v) = @each($c2)) {
        $query .= " and category_id != $v";
      }
    }

    //search within category
    $cats = array ();

    if ($opt == 1) {
      $cats = $category_obj->GetChildren($cat);
      $query .= " and ((0 != 0";
      while (list($k, $v) = @each($cats)) {
        $query .= " or category_id = $v";
      }
      $query .= " ) or (0 != 0";

      // for multiple categories
      $cats = $category_obj->GetChildren($cat);
      while (list($k, $v) = @each($cats)) {
        $query .= " or cat1 = $v";
      }
      $query .= " ) or (0 != 0";

      $cats = $category_obj->GetChildren($cat);
      while (list($k, $v) = @each($cats)) {
        $query .= " or cat2 = $v";
      }
      $query .= " )) ";
    }

    if ($_COOKIE['COOKIE_SORT_BY']) {
      $query .= "	order by sponsored desc, premium desc, $_COOKIE[COOKIE_SORT_BY] $_COOKIE[COOKIE_SORT_ORDER]";
    }
    else {
      $query .= " order by sponsored desc, premium desc, bid desc";
    }


    $result = $dbConn->PageExecute($query, $pg_which, ($search_max_rows) ? $search_max_rows : $max_rows);
    $num_links = $result->RecordCount();

    $keyword = stripslashes($keyword_org);

    if ($num_categories == 0 && $num_links == 0) {
      $error_msg = $msg["10025"];
      $error_msg = str_replace('<%$keyword%>', $keyword, $error_msg);
      $keyword   = $keyword_org;

      if ($record_log) {
        $date   = date("Y-m-d H:i:s");
        $ip     = $_SERVER["REMOTE_ADDR"];
        $query  = "insert into idx_searchlog (keyword,time,ip,result) values ('$keyword','$date','$ip','0')";
        $result = $dbConn->Execute($query);
      }

      DisplayTemplate($theme_path . "search_error.html", "\$error_msg,\$keyword");
      RunPostFilter(__FILE__);
    }
    
    $links_obj->query               = $query;
    $links_obj->template_file       = $theme_path . "rows.html";
    $links_obj->date_format         = $msg["10023"];
    $links_obj->header              = $msg["10022"];
    $links_obj->paging              = true;
    $links_obj->pg_size             = ($search_max_rows) ? $search_max_rows : $max_rows;
    $links_obj->href                = "search.php";

    if ($opt == 1)
      $links_obj->more_param = "&keyword=$keyword&opt=1&cat=$cat";
    else
      $links_obj->more_param = "&keyword=$keyword";

    $links_obj->bold_format           = $bold_format;
    $links_obj->bold                  = $bold_keyword;
    $links_obj->keywords              = $keywords;
    $links_obj->rating_image_path     = "themes/" . $theme_name . "/images/rating/";
    $links_obj->rev_rating_image_path = "themes/" . $theme_name . "/images/review/";
    $link                             = $links_obj->Display();
    $pagination                       = $links_obj->pagination;

    // insert keyword to searchlog table

    if ($record_log) {
      $date   = date("Y-m-d H:i:s");
      $ip     = $_SERVER["REMOTE_ADDR"];
      $query  = "insert into idx_searchlog (keyword,time,ip,result) values ('$keyword','$date','$ip','$num_links')";
      $result = $dbConn->Execute($query);
    }

    DisplayTemplate($theme_path . "search.html",
                    "\$opt,\$keyword,\$category,\$link,\$num_links,\$num_categories,\$pagination,\$favorites");
  }

  function GoogleSearch() {
    global $keyword, $pg_which, $bold_keyword, $bold_format, $google_key, $num_links;
    global $theme_path, $url, $description, $title, $link, $pagination, $opt;

    $keyword     = stripslashes($keyword);
    $keyword_org = $keyword = chop($keyword);

    if (empty($pg_which)) {
      $pg_which = 1;
    }
    
    $p          = $pg_which - 1;
    $start_num  = $p * 10;

    $nusoapclient = new nusoapclient("http://api.google.com/search/beta2");

    $params = array (
      'key'        => $google_key, // Googlelicense key
      'q'          => $keyword,    // searchterm
      'start'      => $start_num,  // startfrom result n
      'maxResults' => 10,          // show atotal of nresults
      'filter'     => true,        // removesimilar results
      'restrict'   => '',          // restrictby topic
      'safeSearch' => false,       // removeadult links
      'lr'         => '',          // restrictby language
      'ie'         => '',          // inputencoding
      'oe'         => ''           // outputencoding
    );

    $result = $nusoapclient->call("doGoogleSearch", $params, "urn:GoogleSearch", "urn:GoogleSearch");

    if ($result['faultstring']) { }
    else {
      if (is_array($result['resultElements'])) {
        foreach ($result['resultElements'] as $r) {
          $url         = $r['URL'];
          $description = $r['snippet'];
          $title       = $r['title'];

          if (empty($title))
            $title = $url;

          $link .= EvalTemplate($theme_path . "web_search_rows.html", "\$url,\$description,\$title");
        }
      }
    }

    $nav             = new navigator;
    $nav->pg_size    = 10;
    $nav->href       = "search.php";
    $kw              = urlencode($keyword);
    $nav->more_param = "&keyword=$kw&opt=2";
    $nav->pg_which   = $pg_which;
    $nav->rec_count  = $result['estimatedTotalResultsCount'];
    $nav->init();

    $pagination = $nav->print_all();
    $num_links  = $result['estimatedTotalResultsCount'];
    $keyword    = htmlspecialchars($keyword_org);

    DisplayTemplate($theme_path . "web_search.html", "\$opt,\$keyword,\$link,\$pagination,\$num_links");
  }


  /*===================================================
    main
  ===================================================*/

  include "application.php";
  include "lib/nusoap/nusoap.php";

  RunPreFilter(__FILE__);

  if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    RemoveFilter("page_cache");
    setcookie("COOKIE_SORT_BY", $_POST['sort_by'], 0, "/",  "", 0);
    setcookie("COOKIE_SORT_ORDER", $_POST['sort_order'], 0, "/",  "", 0);
    Redirect($_SERVER['REQUEST_URI']);
  }

  ShowSearchResult();

  RunPostFilter(__FILE__);

?>