system/classes/search.class.php
author Sami Barakat
Sun, 18 Oct 2009 02:05:53 +0100
branchHEAD
changeset 7387 39932e68c099
parent 7342 187ee0efcee2
child 7391 0bee991937cc
permissions -rw-r--r--
Looks like the Search API function setComment() is not required after all (cf. bug #0000902)
     1 <?php
     2 
     3 /* Reminder: always indent with 4 spaces (no tabs). */
     4 // +---------------------------------------------------------------------------+
     5 // | Geeklog 1.6                                                               |
     6 // +---------------------------------------------------------------------------+
     7 // | search.class.php                                                          |
     8 // |                                                                           |
     9 // | Geeklog search class.                                                     |
    10 // +---------------------------------------------------------------------------+
    11 // | Copyright (C) 2000-2009 by the following authors:                         |
    12 // |                                                                           |
    13 // | Authors: Tony Bibbs       - tony AT geeklog DOT net                       |
    14 // |          Dirk Haun        - dirk AT haun-online DOT de                    |
    15 // |          Sami Barakat     - s.m.barakat AT gmail DOT com                  |
    16 // +---------------------------------------------------------------------------+
    17 // |                                                                           |
    18 // | This program is free software; you can redistribute it and/or             |
    19 // | modify it under the terms of the GNU General Public License               |
    20 // | as published by the Free Software Foundation; either version 2            |
    21 // | of the License, or (at your option) any later version.                    |
    22 // |                                                                           |
    23 // | This program is distributed in the hope that it will be useful,           |
    24 // | but WITHOUT ANY WARRANTY; without even the implied warranty of            |
    25 // | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             |
    26 // | GNU General Public License for more details.                              |
    27 // |                                                                           |
    28 // | You should have received a copy of the GNU General Public License         |
    29 // | along with this program; if not, write to the Free Software Foundation,   |
    30 // | Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.           |
    31 // |                                                                           |
    32 // +---------------------------------------------------------------------------+
    33 
    34 if (strpos(strtolower($_SERVER['PHP_SELF']), 'search.class.php') !== false) {
    35     die('This file can not be used on its own.');
    36 }
    37 
    38 require_once $_CONF['path_system'] . 'classes/plugin.class.php';
    39 require_once $_CONF['path_system'] . 'classes/searchcriteria.class.php';
    40 require_once $_CONF['path_system'] . 'classes/listfactory.class.php';
    41 
    42 /**
    43 * Geeklog Search Class
    44 *
    45 * @author Tony Bibbs, tony AT geeklog DOT net
    46 * @package net.geeklog.search
    47 *
    48 */
    49 class Search {
    50 
    51     // PRIVATE VARIABLES
    52     var $_query = '';
    53     var $_topic = '';
    54     var $_dateStart = null;
    55     var $_dateEnd = null;
    56     var $_author = '';
    57     var $_type = '';
    58     var $_keyType = '';
    59     var $_names = array();
    60     var $_url_rewrite = array();
    61     var $_append_query = array();
    62     var $_searchURL = '';
    63     var $_wordlength;
    64     var $_verbose = false; // verbose logging
    65 
    66     /**
    67     * Constructor
    68     *
    69     * Sets up private search variables
    70     *
    71     * @author Tony Bibbs, tony AT geeklog DOT net
    72     * @access public
    73     *
    74     */
    75     function Search()
    76     {
    77         global $_CONF, $_TABLES;
    78 
    79         // Set search criteria
    80         if (isset ($_GET['query'])) {
    81             $this->_query = strip_tags (COM_stripslashes ($_GET['query']));
    82         }
    83         if (isset ($_GET['topic'])) {
    84             $this->_topic = COM_applyFilter ($_GET['topic']);
    85         }
    86         if (isset ($_GET['datestart'])) {
    87             $this->_dateStart = COM_applyFilter ($_GET['datestart']);
    88         }
    89         if (isset ($_GET['dateend'])) {
    90             $this->_dateEnd = COM_applyFilter ($_GET['dateend']);
    91         }
    92         if (isset ($_GET['author'])) {
    93             $this->_author = COM_applyFilter($_GET['author']);
    94 
    95             // In case we got a username instead of uid, convert it.  This should
    96             // make custom themes for search page easier.
    97             if (!is_numeric($this->_author) && !preg_match('/^([0-9]+)$/', $this->_author) && $this->_author != '') {
    98                 $this->_author = DB_getItem($_TABLES['users'], 'uid', "username='" . addslashes ($this->_author) . "'");
    99             }
   100 
   101             if ($this->_author < 1) {
   102                 $this->_author = '';
   103             }
   104         }
   105         $this->_type = isset($_GET['type']) ? COM_applyFilter($_GET['type']) : 'all';
   106         $this->_keyType = isset($_GET['keyType']) ? COM_applyFilter($_GET['keyType']) : $_CONF['search_def_keytype'];
   107     }
   108 
   109     /**
   110     * Shows an error message to anonymous users
   111     *
   112     * This is called when anonymous users attempt to access search
   113     * functionality that has been locked down by the Geeklog admin.
   114     *
   115     * @author Tony Bibbs, tony AT geeklog DOT net
   116     * @access private
   117     * @return string HTML output for error message
   118     *
   119     */
   120     function _getAccessDeniedMessage()
   121     {
   122         global $_CONF, $LANG_LOGIN;
   123 
   124         $retval .= COM_startBlock ($LANG_LOGIN[1], '',
   125                         COM_getBlockTemplate ('_msg_block', 'header'));
   126         $login = new Template($_CONF['path_layout'] . 'submit');
   127         $login->set_file (array ('login'=>'submitloginrequired.thtml'));
   128         $login->set_var ( 'xhtml', XHTML );
   129         $login->set_var ('login_message', $LANG_LOGIN[2]);
   130         $login->set_var ('site_url', $_CONF['site_url']);
   131         $login->set_var ('site_admin_url', $_CONF['site_admin_url']);
   132         $login->set_var ('layout_url', $_CONF['layout_url']);
   133         $login->set_var ('lang_login', $LANG_LOGIN[3]);
   134         $login->set_var ('lang_newuser', $LANG_LOGIN[4]);
   135         $login->parse ('output', 'login');
   136         $retval .= $login->finish ($login->get_var('output'));
   137         $retval .= COM_endBlock (COM_getBlockTemplate ('_msg_block', 'footer'));
   138 
   139         return $retval;
   140     }
   141 
   142     /**
   143     * Determines if user is allowed to perform a search
   144     *
   145     * Geeklog has a number of settings that may prevent
   146     * the access anonymous users have to the search engine.
   147     * This performs those checks
   148     *
   149     * @author Tony Bibbs, tony AT geeklog DOT net
   150     * @access private
   151     * @return boolean True if search is allowed, otherwise false
   152     *
   153     */
   154     function _isSearchAllowed()
   155     {
   156         global $_USER, $_CONF;
   157 
   158         if (empty($_USER['username'])) {
   159             //check if an anonymous user is attempting to illegally access privilege search capabilities
   160             if (($this->_type != 'all') OR !empty($this->_dateStart) OR !empty($this->_dateEnd) OR ($this->_author > 0) OR !empty($topic)) {
   161                 if (($_CONF['loginrequired'] == 1) OR ($_CONF['searchloginrequired'] >= 1)) {
   162                     return false;
   163                 }
   164             } else {
   165                 if (($_CONF['loginrequired'] == 1) OR ($_CONF['searchloginrequired'] == 2)) {
   166                     return false;
   167                 }
   168             }
   169         }
   170 
   171         return true;
   172     }
   173 
   174     /**
   175     * Determines if user is allowed to use the search form
   176     *
   177     * Geeklog has a number of settings that may prevent
   178     * the access anonymous users have to the search engine.
   179     * This performs those checks
   180     *
   181     * @author Dirk Haun, dirk AT haun-online DOT de
   182     * @access private
   183     * @return boolean True if form usage is allowed, otherwise false
   184     *
   185     */
   186     function _isFormAllowed ()
   187     {
   188         global $_CONF, $_USER;
   189 
   190         if (empty($_USER['username']) AND (($_CONF['loginrequired'] == 1) OR ($_CONF['searchloginrequired'] >= 1))) {
   191             return false;
   192         }
   193 
   194         return true;
   195     }
   196 
   197     /**
   198     * Shows search form
   199     *
   200     * Shows advanced search page
   201     *
   202     * @author Tony Bibbs, tony AT geeklog DOT net
   203     * @access public
   204     * @return string HTML output for form
   205     *
   206     */
   207     function showForm ()
   208     {
   209         global $_CONF, $_TABLES, $LANG09;
   210 
   211         $retval = '';
   212 
   213         // Verify current user my use the search form
   214         if (!$this->_isFormAllowed()) {
   215             return $this->_getAccessDeniedMessage();
   216         }
   217 
   218         $retval .= COM_startBlock($LANG09[1],'advancedsearch.html');
   219         $searchform = new Template($_CONF['path_layout'].'search');
   220         $searchform->set_file (array ('searchform' => 'searchform.thtml',
   221                                       'authors'    => 'searchauthors.thtml'));
   222         $searchform->set_var( 'xhtml', XHTML );
   223         $searchform->set_var('search_intro', $LANG09[19]);
   224         $searchform->set_var('site_url', $_CONF['site_url']);
   225         $searchform->set_var('site_admin_url', $_CONF['site_admin_url']);
   226         $searchform->set_var('layout_url', $_CONF['layout_url']);
   227         $searchform->set_var('lang_keywords', $LANG09[2]);
   228         $searchform->set_var('lang_date', $LANG09[20]);
   229         $searchform->set_var('lang_to', $LANG09[21]);
   230         $searchform->set_var('date_format', $LANG09[22]);
   231         $searchform->set_var('lang_topic', $LANG09[3]);
   232         $searchform->set_var('lang_all', $LANG09[4]);
   233         $searchform->set_var('topic_option_list',
   234                             COM_topicList ('tid,topic', $this->_topic));
   235         $searchform->set_var('lang_type', $LANG09[5]);
   236         $searchform->set_var('lang_results', $LANG09[59]);
   237         $searchform->set_var('lang_per_page', $LANG09[60]);
   238 
   239         $searchform->set_var('lang_exact_phrase', $LANG09[43]);
   240         $searchform->set_var('lang_all_words', $LANG09[44]);
   241         $searchform->set_var('lang_any_word', $LANG09[45]);
   242         $searchform->set_var('lang_titles', $LANG09[69]);
   243 
   244         $escquery = htmlspecialchars($this->_query);
   245         $escquery = str_replace(array('{', '}'), array('&#123;', '&#125;'),
   246                                 $escquery);
   247         $searchform->set_var ('query', $escquery);
   248         $searchform->set_var ('datestart', $this->_dateStart);
   249         $searchform->set_var ('dateend', $this->_dateEnd);
   250 
   251         $phrase_selected = '';
   252         $all_selected = '';
   253         $any_selected = '';
   254         if ($this->_keyType == 'phrase') {
   255             $phrase_selected = 'selected="selected"';
   256         } else if ($this->_keyType == 'all') {
   257             $all_selected = 'selected="selected"';
   258         } else if ($this->_keyType == 'any') {
   259             $any_selected = 'selected="selected"';
   260         }
   261         $searchform->set_var ('key_phrase_selected', $phrase_selected);
   262         $searchform->set_var ('key_all_selected', $all_selected);
   263         $searchform->set_var ('key_any_selected', $any_selected);
   264 
   265         $options = '';
   266         $plugintypes = array('all' => $LANG09[4], 'stories' => $LANG09[6], 'comments' => $LANG09[7]);
   267         $plugintypes = array_merge($plugintypes, PLG_getSearchTypes());
   268         // Generally I don't like to hardcode HTML but this seems easiest
   269         foreach ($plugintypes as $key => $val) {
   270             $options .= "<option value=\"$key\"";
   271             if ($this->_type == $key)
   272                 $options .= ' selected="selected"';
   273             $options .= ">$val</option>".LB;
   274         }
   275         $searchform->set_var('plugin_types', $options);
   276 
   277         if ($_CONF['contributedbyline'] == 1) {
   278             $searchform->set_var('lang_authors', $LANG09[8]);
   279             $searchusers = array();
   280             $result = DB_query("SELECT DISTINCT uid FROM {$_TABLES['comments']}");
   281             while ($A = DB_fetchArray($result)) {
   282                 $searchusers[$A['uid']] = $A['uid'];
   283             }
   284             $result = DB_query("SELECT DISTINCT uid FROM {$_TABLES['stories']} WHERE (date <= NOW()) AND (draft_flag = 0)");
   285             while ($A = DB_fetchArray($result)) {
   286                 $searchusers[$A['uid']] = $A['uid'];
   287             }
   288 
   289             $inlist = implode(',', $searchusers);
   290 
   291             if (!empty ($inlist)) {
   292                 $sql = "SELECT uid,username,fullname FROM {$_TABLES['users']} WHERE uid IN ($inlist)";
   293                 if (isset ($_CONF['show_fullname']) && ($_CONF['show_fullname'] == 1)) {
   294                     /* Caveat: This will group all users with an emtpy fullname
   295                      *         together, so it's not exactly sorted by their
   296                      *         full name ...
   297                      */
   298                     $sql .= ' ORDER BY fullname,username';
   299                 } else {
   300                     $sql .= ' ORDER BY username';
   301                 }
   302                 $result = DB_query ($sql);
   303                 $options = '';
   304                 while ($A = DB_fetchArray($result)) {
   305                     $options .= '<option value="' . $A['uid'] . '"';
   306                     if ($A['uid'] == $this->_author) {
   307                         $options .= ' selected="selected"';
   308                     }
   309                     $options .= '>' . htmlspecialchars(COM_getDisplayName('', $A['username'], $A['fullname'])) . '</option>';
   310                 }
   311                 $searchform->set_var('author_option_list', $options);
   312                 $searchform->parse('author_form_element', 'authors', true);
   313             } else {
   314                 $searchform->set_var('author_form_element', '<input type="hidden" name="author" value="0"' . XHTML . '>');
   315             }
   316         } else {
   317             $searchform->set_var ('author_form_element',
   318                     '<input type="hidden" name="author" value="0"' . XHTML . '>');
   319         }
   320 
   321         // Results per page
   322         $options = '';
   323         $limits = explode(',', $_CONF['search_limits']);
   324         foreach ($limits as $limit) {
   325             $options .= "<option value=\"$limit\"";
   326             if ($_CONF['num_search_results'] == $limit) {
   327                 $options .= ' selected="selected"';
   328             }
   329             $options .= ">$limit</option>" . LB;
   330         }
   331         $searchform->set_var('search_limits', $options);
   332 
   333         $searchform->set_var('lang_search', $LANG09[10]);
   334         $searchform->parse('output', 'searchform');
   335 
   336         $retval .= $searchform->finish($searchform->get_var('output'));
   337         $retval .= COM_endBlock();
   338 
   339         return $retval;
   340     }
   341 
   342     /**
   343     * Performs search on all stories
   344     *
   345     * @author Tony Bibbs, tony AT geeklog DOT net
   346     * @author Sami Barakat, s.m.barakat AT gmail DOT com
   347     * @access private
   348     * @return object plugin object
   349     *
   350     */
   351     function _searchStories()
   352     {
   353         global $_TABLES, $_DB_dbms, $LANG09;
   354 
   355         // Make sure the query is SQL safe
   356         $query = trim(addslashes($this->_query));
   357 
   358         $sql = "SELECT s.sid AS id, s.title AS title, s.introtext AS description, ";
   359         $sql .= "UNIX_TIMESTAMP(s.date) AS date, s.uid AS uid, s.hits AS hits, ";
   360         $sql .= "CONCAT('/article.php?story=',s.sid) AS url ";
   361         $sql .= "FROM {$_TABLES['stories']} AS s, {$_TABLES['users']} AS u ";
   362         $sql .= "WHERE (draft_flag = 0) AND (date <= NOW()) AND (u.uid = s.uid) ";
   363         $sql .= COM_getPermSQL('AND') . COM_getTopicSQL('AND') . COM_getLangSQL('sid', 'AND') . ' ';
   364 
   365         if (!empty($this->_topic)) {
   366             $sql .= "AND (s.tid = '$this->_topic') ";
   367         }
   368         if (!empty($this->_author)) {
   369             $sql .= "AND (s.uid = '$this->_author') ";
   370         }
   371 
   372         $search_s = new SearchCriteria('stories', $LANG09[65]);
   373 
   374         $columns = array('title' => 'title', 'introtext', 'bodytext');
   375         $sql .= $search_s->getDateRangeSQL('AND', 'date', $this->_dateStart, $this->_dateEnd);
   376         list($sql, $ftsql) = $search_s->buildSearchSQL($this->_keyType, $query, $columns, $sql);
   377 
   378         $search_s->setSQL($sql);
   379         $search_s->setFTSQL($ftsql);
   380         $search_s->setRank(5);
   381         $search_s->setURLRewrite(true);
   382 
   383         // Search Story Comments
   384         $sql = "SELECT c.cid AS id, c.title AS title, c.comment AS description, ";
   385         $sql .= "UNIX_TIMESTAMP(c.date) AS date, c.uid AS uid, ";
   386 
   387         // MSSQL has a problem when concatenating numeric values
   388         if ($_DB_dbms == 'mssql') {
   389             $sql .= "'/comment.php?mode=view&amp;cid=' + CAST(c.cid AS varchar(10)) AS url ";
   390         } else {
   391             $sql .= "CONCAT('/comment.php?mode=view&amp;cid=',c.cid) AS url ";
   392         }
   393 
   394         $sql .= "FROM {$_TABLES['users']} AS u, {$_TABLES['comments']} AS c ";
   395         $sql .= "LEFT JOIN {$_TABLES['stories']} AS s ON ((s.sid = c.sid) ";
   396         $sql .= COM_getPermSQL('AND',0,2,'s') . COM_getTopicSQL('AND',0,'s') . COM_getLangSQL('sid','AND','s') . ") ";
   397         $sql .= "WHERE (u.uid = c.uid) AND (s.draft_flag = 0) AND (s.commentcode >= 0) AND (s.date <= NOW()) ";
   398 
   399         if (!empty($this->_topic)) {
   400             $sql .= "AND (s.tid = '$this->_topic') ";
   401         }
   402         if (!empty($this->_author)) {
   403             $sql .= "AND (c.uid = '$this->_author') ";
   404         }
   405 
   406         $search_c = new SearchCriteria('comments', array($LANG09[65],$LANG09[66]));
   407 
   408         $columns = array('title' => 'c.title', 'comment');
   409         $sql .= $search_c->getDateRangeSQL('AND', 'c.date', $this->_dateStart, $this->_dateEnd);
   410         list($sql, $ftsql) = $search_c->buildSearchSQL($this->_keyType, $query, $columns, $sql);
   411 
   412         $search_c->setSQL($sql);
   413         $search_c->setFTSQL($ftsql);
   414         $search_c->setRank(2);
   415 
   416         return array($search_s, $search_c);
   417     }
   418 
   419     /**
   420     * Kicks off the appropriate search(es)
   421     *
   422     * Initiates the search engine and returns HTML formatted
   423     * results. It also provides support to plugins using a
   424     * search API. Backwards compatibility has been incorporated
   425     * in this function to allow legacy support to plugins using
   426     * the old API calls defined versions prior to Geeklog 1.5.1
   427     *
   428     * @author Sami Barakat, s.m.barakat AT gmail DOT com
   429     * @access public
   430     * @return string HTML output for search results
   431     *
   432     */
   433     function doSearch()
   434     {
   435         global $_CONF, $LANG01, $LANG09, $LANG31;
   436 
   437         // Verify current user can perform requested search
   438         if (!$this->_isSearchAllowed())
   439         {
   440             return $this->_getAccessDeniedMessage();
   441         }
   442 
   443         // Make sure there is a query string
   444         // Full text searches have a minimum word length of 3 by default
   445         if ((empty($this->_query) && empty($this->_author) && empty($this->_topic)) || ($_CONF['search_use_fulltext'] && strlen($this->_query) < 3))
   446         {
   447             $retval = '<p>' . $LANG09[41] . '</p>' . LB;
   448             $retval .= $this->showForm();
   449 
   450             return $retval;
   451         }
   452 
   453         // Build the URL strings
   454         $this->_searchURL = $_CONF['site_url'] . '/search.php?query=' . urlencode($this->_query) .
   455             ((!empty($this->_keyType))    ? '&amp;keyType=' . $this->_keyType : '' ) .
   456             ((!empty($this->_dateStart))  ? '&amp;datestart=' . $this->_dateStart : '' ) .
   457             ((!empty($this->_dateEnd))    ? '&amp;dateend=' . $this->_dateEnd : '' ) .
   458             ((!empty($this->_topic))      ? '&amp;topic=' . $this->_topic : '' ) .
   459             ((!empty($this->_author))     ? '&amp;author=' . $this->_author : '' );
   460 
   461         $url = "{$this->_searchURL}&amp;type={$this->_type}&amp;mode=";
   462         $obj = new ListFactory($url.'search', $_CONF['search_limits'], $_CONF['num_search_results']);
   463         $obj->setRowFunction(array($this, 'searchFormatCallBack'));
   464         $obj->setField('ID', 'id', false);
   465         $obj->setField('URL', 'url', false);
   466 
   467         $show_num  = $_CONF['search_show_num'];
   468         $show_type = $_CONF['search_show_type'];
   469         $show_user = $_CONF['contributedbyline'];
   470         $show_hits = !$_CONF['hideviewscount'];
   471         $style = isset($_CONF['search_style']) ? $_CONF['search_style'] : 'google';
   472 
   473         if ($style == 'table')
   474         {
   475             $obj->setStyle('table');
   476             //             Title        Name           Display     Sort   Format
   477             $obj->setField($LANG09[62], ROW_NUMBER,    $show_num,  false, '<b>%d.</b>');
   478             $obj->setField($LANG09[5],  SQL_TITLE,     $show_type, true,  '<b>%s</b>');
   479             $obj->setField($LANG09[16], 'title',       true,       true);
   480             $obj->setField($LANG09[63], 'description', true,       false);
   481             $obj->setField($LANG09[17], 'date',        true,       true);
   482             $obj->setField($LANG09[18], 'uid',         $show_user, true);
   483             $obj->setField($LANG09[50], 'hits',        $show_hits, true);
   484             $this->_wordlength = 7;
   485         }
   486         else if ($style == 'google')
   487         {
   488             $obj->setStyle('inline');
   489             $obj->setField('',          ROW_NUMBER,    $show_num,  false, '<b>%d.</b>');
   490             $obj->setField($LANG09[16], 'title',       true,       true,  '%s<br>');
   491             $obj->setField('',          'description', true,       false, '%s<br>');
   492             $obj->setField('',          '_html',       true,       false, '<span style="color:green;">');
   493             $obj->setField($LANG09[18], 'uid',         $show_user, true,  $LANG01[104].' %s ');
   494             $obj->setField($LANG09[17], 'date',        true,       true,  $LANG01[36].' %s');
   495             $obj->setField($LANG09[5],  SQL_TITLE,     $show_type, true,  ' - %s');
   496             $obj->setField($LANG09[50], 'hits',        $show_hits, true,  ' - %s '.$LANG09[50]);
   497             $obj->setField('',          '_html',       true,       false, '</span>');
   498             $this->_wordlength = 50;
   499         }
   500         $obj->setDefaultSort('hits');
   501 
   502         // Start search timer
   503         $searchtimer = new timerobject();
   504         $searchtimer->setPrecision(4);
   505         $searchtimer->startTimer();
   506 
   507         // Have plugins do their searches
   508         $page = isset($_GET['page']) ? COM_applyFilter($_GET['page'], true) : 1;
   509         $result_plugins = PLG_doSearch($this->_query, $this->_dateStart, $this->_dateEnd, $this->_topic, $this->_type, $this->_author, $this->_keyType, $page, 5);
   510 
   511         // Add core searches
   512         $result_plugins = array_merge($result_plugins, $this->_searchStories());
   513 
   514         // Loop through all plugins separating the new API from the old
   515         $new_api = 0;
   516         $old_api = 0;
   517         $num_results = 0;
   518 
   519         foreach ($result_plugins as $result)
   520         {
   521             if (is_a($result, 'SearchCriteria'))
   522             {
   523                 if ($this->_type != 'all' && $this->_type != $result->getName())
   524                 {
   525                     if ($this->_verbose) {
   526                         COM_errorLog($result->getName() . " using APIv2. Skipped as type is not " . $this->_type);
   527                     }
   528                     continue;
   529                 }
   530 
   531                 $debug_info = $result->getName() . " using APIv2 with ";
   532 
   533                 if ($_CONF['search_use_fulltext'] == true && $result->getFTSQL() != '')
   534                 {
   535                     $debug_info .= "FULLTEXT. ";
   536                     $sql = $result->getFTSQL();
   537                 }
   538                 else
   539                 {
   540                     $debug_info .= "LIKE. ";
   541                     $sql = $result->getSQL();
   542                 }
   543 
   544                 $sql = $this->_convertsql($sql);
   545 
   546                 $debug_info .= "SQL = " . print_r($sql,1);
   547                 if ($this->_verbose) {
   548                     COM_errorLog($debug_info);
   549                 }
   550 
   551                 $api_results = $result->getResults();
   552                 if (!empty($api_results)) {
   553                     $obj->addResultArray($api_results);
   554                 }
   555 
   556                 $obj->setQuery($result->getLabel(), $result->getName(), $sql, $result->getRank());
   557                 $this->_url_rewrite[ $result->getName() ] = $result->UrlRewriteEnable();
   558                 $this->_append_query[ $result->getName() ] = $result->AppendQueryEnable();
   559                 $new_api++;
   560             }
   561             else if (is_a($result, 'Plugin') && $result->num_searchresults != 0)
   562             {
   563                 // Some backwards compatibility
   564                 $debug_info = $result->plugin_name . " using APIv1 with backwards compatibility.";
   565                 $debug_info .= " Count: " . $result->num_searchresults;
   566                 $debug_info .= " Headings: " . implode(",", $result->searchheading);
   567                 if ($this->_verbose) {
   568                     COM_errorLog($debug_info);
   569                 }
   570 
   571                 // Find the column heading names that closely match what we are looking for
   572                 // There may be issues here on different languages, but this _should_ capture most of the data
   573                 $col_title = $this->_findColumn($result->searchheading, array($LANG09[16],$LANG31[4],'Question', 'Site Page'));//Title,Subject
   574                 $col_desc = $this->_findColumn($result->searchheading, array($LANG09[63],'Answer'));
   575                 $col_date = $this->_findColumn($result->searchheading, array($LANG09[17]));//'Date','Date Added','Last Updated','Date & Time'
   576                 $col_user = $this->_findColumn($result->searchheading, array($LANG09[18],'Submited by'));
   577                 $col_hits = $this->_findColumn($result->searchheading, array($LANG09[50],$LANG09[23],'Downloads','Clicks'));//'Hits','Views'
   578 
   579                 $label = str_replace($LANG09[59], '', $result->searchlabel);
   580                 $num_results += $result->num_itemssearched;
   581 
   582                 // Extract the results
   583                 for ($i = 0; $i < 5; $i++)
   584                 {
   585                     // If the plugin does not repect the $perpage perameter force it here.
   586                     $j = ($i + ($page * 5)) - 5;
   587                     if ($j >= count($result->searchresults))
   588                         break;
   589 
   590                     $old_row = $result->searchresults[$j];
   591                     if ($col_date != -1)
   592                     {
   593                         // Convert the date back to a timestamp
   594                         $date = $old_row[ $col_date ];
   595                         $date = substr($date, 0, strpos($date, '@'));
   596                         if ($date == '')
   597                         {
   598                             $date = $old_row[$col_date];
   599                         }
   600                         else
   601                         {
   602                             $date = strtotime($date);
   603                         }
   604                     }
   605 
   606                     $api_results = array(
   607                                 SQL_NAME =>       $result->plugin_name,
   608                                 SQL_TITLE =>      $label,
   609                                 'title' =>        $col_title == -1 ? '<i>' . $LANG09[70] . '</i>' : $old_row[$col_title],
   610                                 'description' =>  $col_desc == -1 ? '<i>' . $LANG09[70] . '</i>' : $old_row[$col_desc],
   611                                 'date' =>         $col_date == -1 ? 'LF_NULL' : $date,
   612                                 'uid' =>          $col_user == -1 ? 'LF_NULL' : $old_row[$col_user],
   613                                 'hits' =>         $col_hits == -1 ? 'LF_NULL' : str_replace(',', '', $old_row[$col_hits])
   614                             );
   615                     preg_match('/href="([^"]+)"/i', $api_results['title'], $links);
   616                     $api_results['url'] = empty($links) ? '#' : $links[1];
   617 
   618                     $obj->addResult($api_results);
   619                 }
   620                 $old_api++;
   621             }
   622         }
   623 
   624         // Find out how many plugins are on the old/new system
   625         if ($this->_verbose) {
   626             COM_errorLog("Search Plugins using APIv1: $old_api APIv2: $new_api");
   627         }
   628 
   629         // Execute the queries
   630         $results = $obj->ExecuteQueries();
   631 
   632         // Searches are done, stop timer
   633         $searchtime = $searchtimer->stopTimer();
   634 
   635         $escquery = htmlspecialchars($this->_query);
   636         $escquery = str_replace(array('{', '}'), array('&#123;', '&#125;'),
   637                                 $escquery);
   638         if ($this->_keyType == 'any')
   639         {
   640             $searchQuery = str_replace(' ', "</b>' " . $LANG09[57] . " '<b>", $escquery);
   641             $searchQuery = "'<b>$searchQuery</b>'";
   642         }
   643         else if ($this->_keyType == 'all')
   644         {
   645             $searchQuery = str_replace(' ', "</b>' " . $LANG09[56] . " '<b>", $escquery);
   646             $searchQuery = "'<b>$searchQuery</b>'";
   647         }
   648         else
   649         {
   650             $searchQuery = $LANG09[55] . " '<b>$escquery</b>'";
   651         }
   652 
   653         // Clean the query string so that sprintf works as expected
   654         $searchQuery = str_replace("%", "%%", $searchQuery);
   655 
   656         $retval = "{$LANG09[25]} $searchQuery. ";
   657         if (count($results) == 0)
   658         {
   659             $retval .= sprintf($LANG09[24], 0);
   660             $retval = '<p>' . $retval . '</p>' . LB;
   661             $retval .= '<p>' . $LANG09[13] . '</p>' . LB;
   662             $retval .= $this->showForm();
   663         }
   664         else
   665         {
   666             $retval .= $LANG09[64] . " ($searchtime {$LANG09[27]}). ";
   667             $retval .= str_replace("%", "%%", COM_createLink($LANG09[61], $url.'refine'));
   668             $retval = '<p>' . $retval . '</p>' . LB;
   669             $retval = $obj->getFormattedOutput($results, $LANG09[11], $retval, '', $_CONF['search_show_sort'], $_CONF['search_show_limit']);
   670         }
   671 
   672         return $retval;
   673     }
   674 
   675     /**
   676     * CallBack function for the ListFactory class
   677     *
   678     * This function gets called by the ListFactory class and formats
   679     * each row accordingly for example pulling usernames from the
   680     * users table and displaying a link to their profile.
   681     *
   682     * @author Sami Barakat, s.m.barakat AT gmail DOT com
   683     * @access public
   684     * @param array $row An array of plain data to format
   685     * @return array A reformatted version of the input array
   686     *
   687     */
   688     function searchFormatCallBack( $preSort, $row )
   689     {
   690         global $_CONF, $LANG09;
   691 
   692         if ($preSort)
   693         {
   694             $row[SQL_TITLE] = is_array($row[SQL_TITLE]) ? implode($_CONF['search_separator'],$row[SQL_TITLE]) : $row[SQL_TITLE];
   695 
   696             if (is_numeric($row['uid']))
   697             {
   698                 if (empty($this->_names[ $row['uid'] ]))
   699                 {
   700                     $this->_names[ $row['uid'] ] = htmlspecialchars(COM_getDisplayName( $row['uid'] ));
   701                     if ($row['uid'] != 1)
   702                     {
   703                         $this->_names[$row['uid']] = COM_createLink($this->_names[ $row['uid'] ],
   704                                     $_CONF['site_url'] . '/users.php?mode=profile&amp;uid=' . $row['uid']);
   705                     }
   706                 }
   707                 $row['uid'] = $this->_names[ $row['uid'] ];
   708             }
   709         }
   710         else
   711         {
   712             $row[SQL_TITLE] = COM_createLink($row[SQL_TITLE], $this->_searchURL.'&amp;type='.$row[SQL_NAME].'&amp;mode=search');
   713 
   714             if ($row['url'] != '#')
   715             {
   716                 $row['url'] = ($row['url'][0] == '/' ? $_CONF['site_url'] : '') . $row['url'];
   717                 if (isset($this->_url_rewrite[$row[SQL_NAME]]) &&
   718                         $this->_url_rewrite[$row[SQL_NAME]]) {
   719                     $row['url'] = COM_buildUrl($row['url']);
   720                 }
   721                 if (isset($this->_append_query[$row[SQL_NAME]]) &&
   722                         $this->_append_query[$row[SQL_NAME]]) {
   723                     $row['url'] .= (strpos($row['url'],'?') ? '&amp;' : '?') . 'query=' . urlencode($this->_query);
   724                 }
   725             }
   726 
   727             $row['title'] = $this->_shortenText($this->_query, $row['title'], 8);
   728             $row['title'] = stripslashes(str_replace('$', '&#36;', $row['title']));
   729             $row['title'] = COM_createLink($row['title'], $row['url']);
   730 
   731             if ($row['description'] == 'LF_NULL') {
   732                 $row['description'] = '<i>' . $LANG09[70] . '</i>';
   733             } elseif ($row['description'] != '<i>' . $LANG09[70] . '</i>') {
   734                 $row['description'] = stripslashes($this->_shortenText($this->_query, PLG_replaceTags($row['description']), $this->_wordlength));
   735             }
   736 
   737             if ($row['date'] != 'LF_NULL') {
   738                 $dt = COM_getUserDateTimeFormat(intval($row['date']));
   739                 $row['date'] = $dt[0];
   740             }
   741 
   742             if ($row['hits'] != 'LF_NULL') {
   743                 $row['hits'] = COM_NumberFormat($row['hits']) . ' '; // simple solution to a silly problem!
   744             }
   745         }
   746 
   747         return $row;
   748     }
   749 
   750     /**
   751     * Shortens a long text string to only a few words
   752     *
   753     * Returns a shorter version of the in putted text centred
   754     * around the keyword. The keyword is highlighted in bold.
   755     * Adds '...' to the beginning or the end of the shortened
   756     * version depending where the text was cut. Works on a
   757     * word basis, so long words wont get cut.
   758     *
   759     * @author Sami Barakat, s.m.barakat AT gmail DOT com
   760     * @access private
   761     * @param string $keyword The word to centre around
   762     * @param string $text The complete text string
   763     * @param int $num_words The number of words to display, best to use an odd number
   764     * @return string A short version of the text
   765     *
   766     */
   767     function _shortenText($keyword, $text, $num_words = 7)
   768     {
   769         $text = COM_getTextContent($text);
   770         $words = explode(' ', $text);
   771         $word_count = count($words);
   772         if ($word_count <= $num_words) {
   773             return COM_highlightQuery($text, $keyword, 'b');
   774         }
   775 
   776         $rt = '';
   777         $pos = $this->_stripos($text, $keyword);
   778         if ($pos !== false)
   779         {
   780             $pos_space = strpos($text, ' ', $pos);
   781             if (empty($pos_space))
   782             {
   783                 // Keyword at the end of text
   784                 $key = $word_count - 1;
   785                 $start = 0 - $num_words;
   786                 $end = 0;
   787                 $rt = '<b>...</b> ';
   788             }
   789             else
   790             {
   791                 $str = substr($text, $pos, $pos_space - $pos);
   792                 $m = (int) (($num_words - 1) / 2);
   793                 $key = $this->_arraySearch($keyword, $words);
   794                 if ($key === false) {
   795                     // Keyword(s) not found - show start of text
   796                     $key = 0;
   797                     $start = 0;
   798                     $end = $num_words - 1;
   799                 } elseif ($key <= $m) {
   800                     // Keyword at the start of text
   801                     $start = 0 - $key;
   802                     $end = $num_words - 1;
   803                     $end = ($key + $m <= $word_count - 1)
   804                          ? $key : $word_count - $m - 1;
   805                     $abs_length = abs($start) + abs($end) + 1;
   806                     if ($abs_length < $num_words) {
   807                         $end += ($num_words - $abs_length);
   808                     }
   809                 } else {
   810                     // Keyword in the middle of text
   811                     $start = 0 - $m;
   812                     $end = ($key + $m <= $word_count - 1)
   813                          ? $m : $word_count - $key - 1;
   814                     $abs_length = abs($start) + abs($end) + 1;
   815                     if ($abs_length < $num_words) {
   816                         $start -= ($num_words - $abs_length);
   817                     }
   818                     $rt = '<b>...</b> ';
   819                 }
   820             }
   821         }
   822         else
   823         {
   824             $key = 0;
   825             $start = 0;
   826             $end = $num_words - 1;
   827         }
   828 
   829         for ($i = $start; $i <= $end; $i++) {
   830             $rt .= $words[$key + $i] . ' ';
   831         }
   832         if ($key + $i != $word_count) {
   833             $rt .= ' <b>...</b>';
   834         }
   835 
   836         return COM_highlightQuery($rt, $keyword, 'b');
   837     }
   838 
   839     /**
   840     * Search array of words for keyword(s)
   841     *
   842     * @param   string  $needle    keyword(s), separated by spaces
   843     * @param   array   $haystack  array of words to search through
   844     * @return  mixed              index in $haystack or false when not found
   845     * @access  private
   846     *
   847     */
   848     function _arraySearch($needle, $haystack)
   849     {
   850         $keywords = explode(' ', $needle);
   851         $num_keywords = count($keywords);
   852 
   853         foreach ($haystack as $key => $value) {
   854             if ($this->_stripos($value, $keywords[0]) !== false) {
   855                 if ($num_keywords == 1) {
   856                     return $key;
   857                 } else {
   858                     $matched_all = true;
   859                     for ($i = 1; $i < $num_keywords; $i++) {
   860                         if ($this->_stripos($haystack[$key + $i], $keywords[$i]) === false) {
   861                             $matched_all = false;
   862                             break;
   863                         }
   864                     }
   865                     if ($matched_all) {
   866                         return $key;
   867                     }
   868                 }
   869             }
   870         }
   871 
   872         return false;
   873     }
   874 
   875     /**
   876     * Finds the similarities between heading names
   877     *
   878     * Returns the index of a heading that matches a
   879     * number of similar heading names. Used for backwards
   880     * compatibility in the doSearch() function.
   881     *
   882     * @author Sami Barakat, s.m.barakat AT gmail DOT com
   883     * @access private
   884     * @param array $headings All the headings
   885     * @param array $find An array of alternative headings to find
   886     * @return int The index of the alternative heading
   887     *
   888     */
   889     function _findColumn( $headings, $find )
   890     {
   891         // We can't use normal for loops here as some of the
   892         // heading indexes start from 1, so foreach works better
   893         foreach ($find as $fh)
   894         {
   895             $j = 0;
   896             foreach ($headings as $h)
   897             {
   898                 if (preg_match("/$fh/i", $h) > 0) {
   899                     return $j;
   900                 }
   901                 $j++;
   902             }
   903         }
   904         return -1;
   905     }
   906 
   907     /**
   908     * Converts the MySQL CONCAT function to the MSSQL equivalent
   909     *
   910     * @author Sami Barakat, s.m.barakat AT gmail DOT com
   911     * @access private
   912     * @param string $sql The SQL to convert
   913     * @return string MSSQL friendly SQL
   914     *
   915     */
   916     function _convertsql( $sql )
   917     {
   918         global $_DB_dbms;
   919         if ($_DB_dbms == 'mssql')
   920         {
   921             if (is_string( $sql ))
   922             {
   923                 $sql = preg_replace("/CONCAT\(([^\)]+)\)/ie", "preg_replace('/,?(\'[^\']+\'|[^,]+),/i', '\\\\1 + ', '\\1')", $sql);
   924             }
   925             else if (is_array( $sql ))
   926             {
   927                 $sql['mssql'] = preg_replace("/CONCAT\(([^\)]+)\)/ie", "preg_replace('/,?(\'[^\']+\'|[^,]+),/i', '\\\\1 + ', '\\1')", $sql['mssql']);
   928             }
   929         }
   930         return $sql;
   931     }
   932 
   933     /**
   934     * Helper function: Simulate stripos on PHP 4
   935     *
   936     * @param   string  $haystack  string to search in
   937     * @param   string  $needle    string to search for
   938     * @return  mixed              first pos of $needle in $haystack, or false
   939     *
   940     */
   941     function _stripos($haystack, $needle)
   942     {
   943         if (function_exists('stripos')) {
   944             return stripos($haystack, $needle);
   945         } else {
   946             return strpos(strtolower($haystack), strtolower($needle));
   947         }
   948     }
   949 }
   950 
   951 ?>