Looks like the Search API function setComment() is not required after all (cf. bug #0000902)
3 /* Reminder: always indent with 4 spaces (no tabs). */
4 // +---------------------------------------------------------------------------+
6 // +---------------------------------------------------------------------------+
7 // | search.class.php |
9 // | Geeklog search class. |
10 // +---------------------------------------------------------------------------+
11 // | Copyright (C) 2000-2009 by the following authors: |
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 // +---------------------------------------------------------------------------+
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. |
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. |
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. |
32 // +---------------------------------------------------------------------------+
34 if (strpos(strtolower($_SERVER['PHP_SELF']), 'search.class.php') !== false) {
35 die('This file can not be used on its own.');
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';
43 * Geeklog Search Class
45 * @author Tony Bibbs, tony AT geeklog DOT net
46 * @package net.geeklog.search
54 var $_dateStart = null;
59 var $_names = array();
60 var $_url_rewrite = array();
61 var $_append_query = array();
64 var $_verbose = false; // verbose logging
69 * Sets up private search variables
71 * @author Tony Bibbs, tony AT geeklog DOT net
77 global $_CONF, $_TABLES;
79 // Set search criteria
80 if (isset ($_GET['query'])) {
81 $this->_query = strip_tags (COM_stripslashes ($_GET['query']));
83 if (isset ($_GET['topic'])) {
84 $this->_topic = COM_applyFilter ($_GET['topic']);
86 if (isset ($_GET['datestart'])) {
87 $this->_dateStart = COM_applyFilter ($_GET['datestart']);
89 if (isset ($_GET['dateend'])) {
90 $this->_dateEnd = COM_applyFilter ($_GET['dateend']);
92 if (isset ($_GET['author'])) {
93 $this->_author = COM_applyFilter($_GET['author']);
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) . "'");
101 if ($this->_author < 1) {
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'];
110 * Shows an error message to anonymous users
112 * This is called when anonymous users attempt to access search
113 * functionality that has been locked down by the Geeklog admin.
115 * @author Tony Bibbs, tony AT geeklog DOT net
117 * @return string HTML output for error message
120 function _getAccessDeniedMessage()
122 global $_CONF, $LANG_LOGIN;
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'));
143 * Determines if user is allowed to perform a search
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
149 * @author Tony Bibbs, tony AT geeklog DOT net
151 * @return boolean True if search is allowed, otherwise false
154 function _isSearchAllowed()
156 global $_USER, $_CONF;
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)) {
165 if (($_CONF['loginrequired'] == 1) OR ($_CONF['searchloginrequired'] == 2)) {
175 * Determines if user is allowed to use the search form
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
181 * @author Dirk Haun, dirk AT haun-online DOT de
183 * @return boolean True if form usage is allowed, otherwise false
186 function _isFormAllowed ()
188 global $_CONF, $_USER;
190 if (empty($_USER['username']) AND (($_CONF['loginrequired'] == 1) OR ($_CONF['searchloginrequired'] >= 1))) {
200 * Shows advanced search page
202 * @author Tony Bibbs, tony AT geeklog DOT net
204 * @return string HTML output for form
209 global $_CONF, $_TABLES, $LANG09;
213 // Verify current user my use the search form
214 if (!$this->_isFormAllowed()) {
215 return $this->_getAccessDeniedMessage();
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]);
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]);
244 $escquery = htmlspecialchars($this->_query);
245 $escquery = str_replace(array('{', '}'), array('{', '}'),
247 $searchform->set_var ('query', $escquery);
248 $searchform->set_var ('datestart', $this->_dateStart);
249 $searchform->set_var ('dateend', $this->_dateEnd);
251 $phrase_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"';
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);
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;
275 $searchform->set_var('plugin_types', $options);
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'];
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'];
289 $inlist = implode(',', $searchusers);
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
298 $sql .= ' ORDER BY fullname,username';
300 $sql .= ' ORDER BY username';
302 $result = DB_query ($sql);
304 while ($A = DB_fetchArray($result)) {
305 $options .= '<option value="' . $A['uid'] . '"';
306 if ($A['uid'] == $this->_author) {
307 $options .= ' selected="selected"';
309 $options .= '>' . htmlspecialchars(COM_getDisplayName('', $A['username'], $A['fullname'])) . '</option>';
311 $searchform->set_var('author_option_list', $options);
312 $searchform->parse('author_form_element', 'authors', true);
314 $searchform->set_var('author_form_element', '<input type="hidden" name="author" value="0"' . XHTML . '>');
317 $searchform->set_var ('author_form_element',
318 '<input type="hidden" name="author" value="0"' . XHTML . '>');
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"';
329 $options .= ">$limit</option>" . LB;
331 $searchform->set_var('search_limits', $options);
333 $searchform->set_var('lang_search', $LANG09[10]);
334 $searchform->parse('output', 'searchform');
336 $retval .= $searchform->finish($searchform->get_var('output'));
337 $retval .= COM_endBlock();
343 * Performs search on all stories
345 * @author Tony Bibbs, tony AT geeklog DOT net
346 * @author Sami Barakat, s.m.barakat AT gmail DOT com
348 * @return object plugin object
351 function _searchStories()
353 global $_TABLES, $_DB_dbms, $LANG09;
355 // Make sure the query is SQL safe
356 $query = trim(addslashes($this->_query));
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') . ' ';
365 if (!empty($this->_topic)) {
366 $sql .= "AND (s.tid = '$this->_topic') ";
368 if (!empty($this->_author)) {
369 $sql .= "AND (s.uid = '$this->_author') ";
372 $search_s = new SearchCriteria('stories', $LANG09[65]);
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);
378 $search_s->setSQL($sql);
379 $search_s->setFTSQL($ftsql);
380 $search_s->setRank(5);
381 $search_s->setURLRewrite(true);
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, ";
387 // MSSQL has a problem when concatenating numeric values
388 if ($_DB_dbms == 'mssql') {
389 $sql .= "'/comment.php?mode=view&cid=' + CAST(c.cid AS varchar(10)) AS url ";
391 $sql .= "CONCAT('/comment.php?mode=view&cid=',c.cid) AS url ";
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()) ";
399 if (!empty($this->_topic)) {
400 $sql .= "AND (s.tid = '$this->_topic') ";
402 if (!empty($this->_author)) {
403 $sql .= "AND (c.uid = '$this->_author') ";
406 $search_c = new SearchCriteria('comments', array($LANG09[65],$LANG09[66]));
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);
412 $search_c->setSQL($sql);
413 $search_c->setFTSQL($ftsql);
414 $search_c->setRank(2);
416 return array($search_s, $search_c);
420 * Kicks off the appropriate search(es)
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
428 * @author Sami Barakat, s.m.barakat AT gmail DOT com
430 * @return string HTML output for search results
435 global $_CONF, $LANG01, $LANG09, $LANG31;
437 // Verify current user can perform requested search
438 if (!$this->_isSearchAllowed())
440 return $this->_getAccessDeniedMessage();
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))
447 $retval = '<p>' . $LANG09[41] . '</p>' . LB;
448 $retval .= $this->showForm();
453 // Build the URL strings
454 $this->_searchURL = $_CONF['site_url'] . '/search.php?query=' . urlencode($this->_query) .
455 ((!empty($this->_keyType)) ? '&keyType=' . $this->_keyType : '' ) .
456 ((!empty($this->_dateStart)) ? '&datestart=' . $this->_dateStart : '' ) .
457 ((!empty($this->_dateEnd)) ? '&dateend=' . $this->_dateEnd : '' ) .
458 ((!empty($this->_topic)) ? '&topic=' . $this->_topic : '' ) .
459 ((!empty($this->_author)) ? '&author=' . $this->_author : '' );
461 $url = "{$this->_searchURL}&type={$this->_type}&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);
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';
473 if ($style == 'table')
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;
486 else if ($style == 'google')
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;
500 $obj->setDefaultSort('hits');
502 // Start search timer
503 $searchtimer = new timerobject();
504 $searchtimer->setPrecision(4);
505 $searchtimer->startTimer();
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);
512 $result_plugins = array_merge($result_plugins, $this->_searchStories());
514 // Loop through all plugins separating the new API from the old
519 foreach ($result_plugins as $result)
521 if (is_a($result, 'SearchCriteria'))
523 if ($this->_type != 'all' && $this->_type != $result->getName())
525 if ($this->_verbose) {
526 COM_errorLog($result->getName() . " using APIv2. Skipped as type is not " . $this->_type);
531 $debug_info = $result->getName() . " using APIv2 with ";
533 if ($_CONF['search_use_fulltext'] == true && $result->getFTSQL() != '')
535 $debug_info .= "FULLTEXT. ";
536 $sql = $result->getFTSQL();
540 $debug_info .= "LIKE. ";
541 $sql = $result->getSQL();
544 $sql = $this->_convertsql($sql);
546 $debug_info .= "SQL = " . print_r($sql,1);
547 if ($this->_verbose) {
548 COM_errorLog($debug_info);
551 $api_results = $result->getResults();
552 if (!empty($api_results)) {
553 $obj->addResultArray($api_results);
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();
561 else if (is_a($result, 'Plugin') && $result->num_searchresults != 0)
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);
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'
579 $label = str_replace($LANG09[59], '', $result->searchlabel);
580 $num_results += $result->num_itemssearched;
582 // Extract the results
583 for ($i = 0; $i < 5; $i++)
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))
590 $old_row = $result->searchresults[$j];
593 // Convert the date back to a timestamp
594 $date = $old_row[ $col_date ];
595 $date = substr($date, 0, strpos($date, '@'));
598 $date = $old_row[$col_date];
602 $date = strtotime($date);
606 $api_results = array(
607 SQL_NAME => $result->plugin_name,
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])
615 preg_match('/href="([^"]+)"/i', $api_results['title'], $links);
616 $api_results['url'] = empty($links) ? '#' : $links[1];
618 $obj->addResult($api_results);
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");
629 // Execute the queries
630 $results = $obj->ExecuteQueries();
632 // Searches are done, stop timer
633 $searchtime = $searchtimer->stopTimer();
635 $escquery = htmlspecialchars($this->_query);
636 $escquery = str_replace(array('{', '}'), array('{', '}'),
638 if ($this->_keyType == 'any')
640 $searchQuery = str_replace(' ', "</b>' " . $LANG09[57] . " '<b>", $escquery);
641 $searchQuery = "'<b>$searchQuery</b>'";
643 else if ($this->_keyType == 'all')
645 $searchQuery = str_replace(' ', "</b>' " . $LANG09[56] . " '<b>", $escquery);
646 $searchQuery = "'<b>$searchQuery</b>'";
650 $searchQuery = $LANG09[55] . " '<b>$escquery</b>'";
653 // Clean the query string so that sprintf works as expected
654 $searchQuery = str_replace("%", "%%", $searchQuery);
656 $retval = "{$LANG09[25]} $searchQuery. ";
657 if (count($results) == 0)
659 $retval .= sprintf($LANG09[24], 0);
660 $retval = '<p>' . $retval . '</p>' . LB;
661 $retval .= '<p>' . $LANG09[13] . '</p>' . LB;
662 $retval .= $this->showForm();
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']);
676 * CallBack function for the ListFactory class
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.
682 * @author Sami Barakat, s.m.barakat AT gmail DOT com
684 * @param array $row An array of plain data to format
685 * @return array A reformatted version of the input array
688 function searchFormatCallBack( $preSort, $row )
690 global $_CONF, $LANG09;
694 $row[SQL_TITLE] = is_array($row[SQL_TITLE]) ? implode($_CONF['search_separator'],$row[SQL_TITLE]) : $row[SQL_TITLE];
696 if (is_numeric($row['uid']))
698 if (empty($this->_names[ $row['uid'] ]))
700 $this->_names[ $row['uid'] ] = htmlspecialchars(COM_getDisplayName( $row['uid'] ));
701 if ($row['uid'] != 1)
703 $this->_names[$row['uid']] = COM_createLink($this->_names[ $row['uid'] ],
704 $_CONF['site_url'] . '/users.php?mode=profile&uid=' . $row['uid']);
707 $row['uid'] = $this->_names[ $row['uid'] ];
712 $row[SQL_TITLE] = COM_createLink($row[SQL_TITLE], $this->_searchURL.'&type='.$row[SQL_NAME].'&mode=search');
714 if ($row['url'] != '#')
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']);
721 if (isset($this->_append_query[$row[SQL_NAME]]) &&
722 $this->_append_query[$row[SQL_NAME]]) {
723 $row['url'] .= (strpos($row['url'],'?') ? '&' : '?') . 'query=' . urlencode($this->_query);
727 $row['title'] = $this->_shortenText($this->_query, $row['title'], 8);
728 $row['title'] = stripslashes(str_replace('$', '$', $row['title']));
729 $row['title'] = COM_createLink($row['title'], $row['url']);
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));
737 if ($row['date'] != 'LF_NULL') {
738 $dt = COM_getUserDateTimeFormat(intval($row['date']));
739 $row['date'] = $dt[0];
742 if ($row['hits'] != 'LF_NULL') {
743 $row['hits'] = COM_NumberFormat($row['hits']) . ' '; // simple solution to a silly problem!
751 * Shortens a long text string to only a few words
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.
759 * @author Sami Barakat, s.m.barakat AT gmail DOT com
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
767 function _shortenText($keyword, $text, $num_words = 7)
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');
777 $pos = $this->_stripos($text, $keyword);
780 $pos_space = strpos($text, ' ', $pos);
781 if (empty($pos_space))
783 // Keyword at the end of text
784 $key = $word_count - 1;
785 $start = 0 - $num_words;
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
798 $end = $num_words - 1;
799 } elseif ($key <= $m) {
800 // Keyword at the start of text
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);
810 // Keyword in the middle of text
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);
826 $end = $num_words - 1;
829 for ($i = $start; $i <= $end; $i++) {
830 $rt .= $words[$key + $i] . ' ';
832 if ($key + $i != $word_count) {
833 $rt .= ' <b>...</b>';
836 return COM_highlightQuery($rt, $keyword, 'b');
840 * Search array of words for keyword(s)
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
848 function _arraySearch($needle, $haystack)
850 $keywords = explode(' ', $needle);
851 $num_keywords = count($keywords);
853 foreach ($haystack as $key => $value) {
854 if ($this->_stripos($value, $keywords[0]) !== false) {
855 if ($num_keywords == 1) {
859 for ($i = 1; $i < $num_keywords; $i++) {
860 if ($this->_stripos($haystack[$key + $i], $keywords[$i]) === false) {
861 $matched_all = false;
876 * Finds the similarities between heading names
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.
882 * @author Sami Barakat, s.m.barakat AT gmail DOT com
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
889 function _findColumn( $headings, $find )
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)
896 foreach ($headings as $h)
898 if (preg_match("/$fh/i", $h) > 0) {
908 * Converts the MySQL CONCAT function to the MSSQL equivalent
910 * @author Sami Barakat, s.m.barakat AT gmail DOT com
912 * @param string $sql The SQL to convert
913 * @return string MSSQL friendly SQL
916 function _convertsql( $sql )
919 if ($_DB_dbms == 'mssql')
921 if (is_string( $sql ))
923 $sql = preg_replace("/CONCAT\(([^\)]+)\)/ie", "preg_replace('/,?(\'[^\']+\'|[^,]+),/i', '\\\\1 + ', '\\1')", $sql);
925 else if (is_array( $sql ))
927 $sql['mssql'] = preg_replace("/CONCAT\(([^\)]+)\)/ie", "preg_replace('/,?(\'[^\']+\'|[^,]+),/i', '\\\\1 + ', '\\1')", $sql['mssql']);
934 * Helper function: Simulate stripos on PHP 4
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
941 function _stripos($haystack, $needle)
943 if (function_exists('stripos')) {
944 return stripos($haystack, $needle);
946 return strpos(strtolower($haystack), strtolower($needle));