[ Index ]

PHP Cross Reference of phpBB-3.2.8-deutsch

title

Body

[close]

/phpbb/search/ -> fulltext_mysql.php (source)

   1  <?php
   2  /**
   3  *
   4  * This file is part of the phpBB Forum Software package.
   5  *
   6  * @copyright (c) phpBB Limited <https://www.phpbb.com>
   7  * @license GNU General Public License, version 2 (GPL-2.0)
   8  *
   9  * For full copyright and license information, please see
  10  * the docs/CREDITS.txt file.
  11  *
  12  */
  13  
  14  namespace phpbb\search;
  15  
  16  /**
  17  * Fulltext search for MySQL
  18  */
  19  class fulltext_mysql extends \phpbb\search\base
  20  {
  21      /**
  22       * Associative array holding index stats
  23       * @var array
  24       */
  25      protected $stats = array();
  26  
  27      /**
  28       * Holds the words entered by user, obtained by splitting the entered query on whitespace
  29       * @var array
  30       */
  31      protected $split_words = array();
  32  
  33      /**
  34       * Config object
  35       * @var \phpbb\config\config
  36       */
  37      protected $config;
  38  
  39      /**
  40       * Database connection
  41       * @var \phpbb\db\driver\driver_interface
  42       */
  43      protected $db;
  44  
  45      /**
  46       * phpBB event dispatcher object
  47       * @var \phpbb\event\dispatcher_interface
  48       */
  49      protected $phpbb_dispatcher;
  50  
  51      /**
  52       * User object
  53       * @var \phpbb\user
  54       */
  55      protected $user;
  56  
  57      /**
  58       * Associative array stores the min and max word length to be searched
  59       * @var array
  60       */
  61      protected $word_length = array();
  62  
  63      /**
  64       * Contains tidied search query.
  65       * Operators are prefixed in search query and common words excluded
  66       * @var string
  67       */
  68      protected $search_query;
  69  
  70      /**
  71       * Contains common words.
  72       * Common words are words with length less/more than min/max length
  73       * @var array
  74       */
  75      protected $common_words = array();
  76  
  77      /**
  78       * Constructor
  79       * Creates a new \phpbb\search\fulltext_mysql, which is used as a search backend
  80       *
  81       * @param string|bool $error Any error that occurs is passed on through this reference variable otherwise false
  82       * @param string $phpbb_root_path Relative path to phpBB root
  83       * @param string $phpEx PHP file extension
  84       * @param \phpbb\auth\auth $auth Auth object
  85       * @param \phpbb\config\config $config Config object
  86       * @param \phpbb\db\driver\driver_interface Database object
  87       * @param \phpbb\user $user User object
  88       * @param \phpbb\event\dispatcher_interface    $phpbb_dispatcher    Event dispatcher object
  89       */
  90  	public function __construct(&$error, $phpbb_root_path, $phpEx, $auth, $config, $db, $user, $phpbb_dispatcher)
  91      {
  92          $this->config = $config;
  93          $this->db = $db;
  94          $this->phpbb_dispatcher = $phpbb_dispatcher;
  95          $this->user = $user;
  96  
  97          $this->word_length = array('min' => $this->config['fulltext_mysql_min_word_len'], 'max' => $this->config['fulltext_mysql_max_word_len']);
  98  
  99          /**
 100           * Load the UTF tools
 101           */
 102          if (!function_exists('utf8_strlen'))
 103          {
 104              include($phpbb_root_path . 'includes/utf/utf_tools.' . $phpEx);
 105          }
 106  
 107          $error = false;
 108      }
 109  
 110      /**
 111      * Returns the name of this search backend to be displayed to administrators
 112      *
 113      * @return string Name
 114      */
 115  	public function get_name()
 116      {
 117          return 'MySQL Fulltext';
 118      }
 119  
 120      /**
 121       * Returns the search_query
 122       *
 123       * @return string search query
 124       */
 125  	public function get_search_query()
 126      {
 127          return $this->search_query;
 128      }
 129  
 130      /**
 131       * Returns the common_words array
 132       *
 133       * @return array common words that are ignored by search backend
 134       */
 135  	public function get_common_words()
 136      {
 137          return $this->common_words;
 138      }
 139  
 140      /**
 141       * Returns the word_length array
 142       *
 143       * @return array min and max word length for searching
 144       */
 145  	public function get_word_length()
 146      {
 147          return $this->word_length;
 148      }
 149  
 150      /**
 151      * Checks for correct MySQL version and stores min/max word length in the config
 152      *
 153      * @return string|bool Language key of the error/incompatiblity occurred
 154      */
 155  	public function init()
 156      {
 157          if ($this->db->get_sql_layer() != 'mysql4' && $this->db->get_sql_layer() != 'mysqli')
 158          {
 159              return $this->user->lang['FULLTEXT_MYSQL_INCOMPATIBLE_DATABASE'];
 160          }
 161  
 162          $result = $this->db->sql_query('SHOW TABLE STATUS LIKE \'' . POSTS_TABLE . '\'');
 163          $info = $this->db->sql_fetchrow($result);
 164          $this->db->sql_freeresult($result);
 165  
 166          $engine = '';
 167          if (isset($info['Engine']))
 168          {
 169              $engine = $info['Engine'];
 170          }
 171          else if (isset($info['Type']))
 172          {
 173              $engine = $info['Type'];
 174          }
 175  
 176          $fulltext_supported =
 177              $engine === 'MyISAM' ||
 178              // FULLTEXT is supported on InnoDB since MySQL 5.6.4 according to
 179              // http://dev.mysql.com/doc/refman/5.6/en/innodb-storage-engine.html
 180              // We also require https://bugs.mysql.com/bug.php?id=67004 to be
 181              // fixed for proper overall operation. Hence we require 5.6.8.
 182              $engine === 'InnoDB' &&
 183              phpbb_version_compare($this->db->sql_server_info(true), '5.6.8', '>=');
 184  
 185          if (!$fulltext_supported)
 186          {
 187              return $this->user->lang['FULLTEXT_MYSQL_NOT_SUPPORTED'];
 188          }
 189  
 190          $sql = 'SHOW VARIABLES
 191              LIKE \'%ft\_%\'';
 192          $result = $this->db->sql_query($sql);
 193  
 194          $mysql_info = array();
 195          while ($row = $this->db->sql_fetchrow($result))
 196          {
 197              $mysql_info[$row['Variable_name']] = $row['Value'];
 198          }
 199          $this->db->sql_freeresult($result);
 200  
 201          if ($engine === 'MyISAM')
 202          {
 203              $this->config->set('fulltext_mysql_max_word_len', $mysql_info['ft_max_word_len']);
 204              $this->config->set('fulltext_mysql_min_word_len', $mysql_info['ft_min_word_len']);
 205          }
 206          else if ($engine === 'InnoDB')
 207          {
 208              $this->config->set('fulltext_mysql_max_word_len', $mysql_info['innodb_ft_max_token_size']);
 209              $this->config->set('fulltext_mysql_min_word_len', $mysql_info['innodb_ft_min_token_size']);
 210          }
 211  
 212          return false;
 213      }
 214  
 215      /**
 216      * Splits keywords entered by a user into an array of words stored in $this->split_words
 217      * Stores the tidied search query in $this->search_query
 218      *
 219      * @param string &$keywords Contains the keyword as entered by the user
 220      * @param string $terms is either 'all' or 'any'
 221      * @return bool false if no valid keywords were found and otherwise true
 222      */
 223  	public function split_keywords(&$keywords, $terms)
 224      {
 225          if ($terms == 'all')
 226          {
 227              $match        = array('#\sand\s#iu', '#\sor\s#iu', '#\snot\s#iu', '#(^|\s)\+#', '#(^|\s)-#', '#(^|\s)\|#');
 228              $replace    = array(' +', ' |', ' -', ' +', ' -', ' |');
 229  
 230              $keywords = preg_replace($match, $replace, $keywords);
 231          }
 232  
 233          // Filter out as above
 234          $split_keywords = preg_replace("#[\n\r\t]+#", ' ', trim(htmlspecialchars_decode($keywords)));
 235  
 236          // Split words
 237          $split_keywords = preg_replace('#([^\p{L}\p{N}\'*"()])#u', '$1$1', str_replace('\'\'', '\' \'', trim($split_keywords)));
 238          $matches = array();
 239          preg_match_all('#(?:[^\p{L}\p{N}*"()]|^)([+\-|]?(?:[\p{L}\p{N}*"()]+\'?)*[\p{L}\p{N}*"()])(?:[^\p{L}\p{N}*"()]|$)#u', $split_keywords, $matches);
 240          $this->split_words = $matches[1];
 241  
 242          // We limit the number of allowed keywords to minimize load on the database
 243          if ($this->config['max_num_search_keywords'] && count($this->split_words) > $this->config['max_num_search_keywords'])
 244          {
 245              trigger_error($this->user->lang('MAX_NUM_SEARCH_KEYWORDS_REFINE', (int) $this->config['max_num_search_keywords'], count($this->split_words)));
 246          }
 247  
 248          // to allow phrase search, we need to concatenate quoted words
 249          $tmp_split_words = array();
 250          $phrase = '';
 251          foreach ($this->split_words as $word)
 252          {
 253              if ($phrase)
 254              {
 255                  $phrase .= ' ' . $word;
 256                  if (strpos($word, '"') !== false && substr_count($word, '"') % 2 == 1)
 257                  {
 258                      $tmp_split_words[] = $phrase;
 259                      $phrase = '';
 260                  }
 261              }
 262              else if (strpos($word, '"') !== false && substr_count($word, '"') % 2 == 1)
 263              {
 264                  $phrase = $word;
 265              }
 266              else
 267              {
 268                  $tmp_split_words[] = $word;
 269              }
 270          }
 271          if ($phrase)
 272          {
 273              $tmp_split_words[] = $phrase;
 274          }
 275  
 276          $this->split_words = $tmp_split_words;
 277  
 278          unset($tmp_split_words);
 279          unset($phrase);
 280  
 281          foreach ($this->split_words as $i => $word)
 282          {
 283              // Check for not allowed search queries for InnoDB.
 284              // We assume similar restrictions for MyISAM, which is usually even
 285              // slower but not as restrictive as InnoDB.
 286              // InnoDB full-text search does not support the use of a leading
 287              // plus sign with wildcard ('+*'), a plus and minus sign
 288              // combination ('+-'), or leading a plus and minus sign combination.
 289              // InnoDB full-text search only supports leading plus or minus signs.
 290              // For example, InnoDB supports '+apple' but does not support 'apple+'.
 291              // Specifying a trailing plus or minus sign causes InnoDB to report
 292              // a syntax error. InnoDB full-text search does not support the use
 293              // of multiple operators on a single search word, as in this example:
 294              // '++apple'. Use of multiple operators on a single search word
 295              // returns a syntax error to standard out.
 296              // Also, ensure that the wildcard character is only used at the
 297              // end of the line as it's intended by MySQL.
 298              if (preg_match('#^(\+[+-]|\+\*|.+[+-]$|.+\*(?!$))#', $word))
 299              {
 300                  unset($this->split_words[$i]);
 301                  continue;
 302              }
 303  
 304              $clean_word = preg_replace('#^[+\-|"]#', '', $word);
 305  
 306              // check word length
 307              $clean_len = utf8_strlen(str_replace('*', '', $clean_word));
 308              if (($clean_len < $this->config['fulltext_mysql_min_word_len']) || ($clean_len > $this->config['fulltext_mysql_max_word_len']))
 309              {
 310                  $this->common_words[] = $word;
 311                  unset($this->split_words[$i]);
 312              }
 313          }
 314  
 315          if ($terms == 'any')
 316          {
 317              $this->search_query = '';
 318              foreach ($this->split_words as $word)
 319              {
 320                  if ((strpos($word, '+') === 0) || (strpos($word, '-') === 0) || (strpos($word, '|') === 0))
 321                  {
 322                      $word = substr($word, 1);
 323                  }
 324                  $this->search_query .= $word . ' ';
 325              }
 326          }
 327          else
 328          {
 329              $this->search_query = '';
 330              foreach ($this->split_words as $word)
 331              {
 332                  if ((strpos($word, '+') === 0) || (strpos($word, '-') === 0))
 333                  {
 334                      $this->search_query .= $word . ' ';
 335                  }
 336                  else if (strpos($word, '|') === 0)
 337                  {
 338                      $this->search_query .= substr($word, 1) . ' ';
 339                  }
 340                  else
 341                  {
 342                      $this->search_query .= '+' . $word . ' ';
 343                  }
 344              }
 345          }
 346  
 347          $this->search_query = utf8_htmlspecialchars($this->search_query);
 348  
 349          if ($this->search_query)
 350          {
 351              $this->split_words = array_values($this->split_words);
 352              sort($this->split_words);
 353              return true;
 354          }
 355          return false;
 356      }
 357  
 358      /**
 359      * Turns text into an array of words
 360      * @param string $text contains post text/subject
 361      */
 362  	public function split_message($text)
 363      {
 364          // Split words
 365          $text = preg_replace('#([^\p{L}\p{N}\'*])#u', '$1$1', str_replace('\'\'', '\' \'', trim($text)));
 366          $matches = array();
 367          preg_match_all('#(?:[^\p{L}\p{N}*]|^)([+\-|]?(?:[\p{L}\p{N}*]+\'?)*[\p{L}\p{N}*])(?:[^\p{L}\p{N}*]|$)#u', $text, $matches);
 368          $text = $matches[1];
 369  
 370          // remove too short or too long words
 371          $text = array_values($text);
 372          for ($i = 0, $n = count($text); $i < $n; $i++)
 373          {
 374              $text[$i] = trim($text[$i]);
 375              if (utf8_strlen($text[$i]) < $this->config['fulltext_mysql_min_word_len'] || utf8_strlen($text[$i]) > $this->config['fulltext_mysql_max_word_len'])
 376              {
 377                  unset($text[$i]);
 378              }
 379          }
 380  
 381          return array_values($text);
 382      }
 383  
 384      /**
 385      * Performs a search on keywords depending on display specific params. You have to run split_keywords() first
 386      *
 387      * @param    string        $type                contains either posts or topics depending on what should be searched for
 388      * @param    string        $fields                contains either titleonly (topic titles should be searched), msgonly (only message bodies should be searched), firstpost (only subject and body of the first post should be searched) or all (all post bodies and subjects should be searched)
 389      * @param    string        $terms                is either 'all' (use query as entered, words without prefix should default to "have to be in field") or 'any' (ignore search query parts and just return all posts that contain any of the specified words)
 390      * @param    array        $sort_by_sql        contains SQL code for the ORDER BY part of a query
 391      * @param    string        $sort_key            is the key of $sort_by_sql for the selected sorting
 392      * @param    string        $sort_dir            is either a or d representing ASC and DESC
 393      * @param    string        $sort_days            specifies the maximum amount of days a post may be old
 394      * @param    array        $ex_fid_ary            specifies an array of forum ids which should not be searched
 395      * @param    string        $post_visibility    specifies which types of posts the user can view in which forums
 396      * @param    int            $topic_id            is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched
 397      * @param    array        $author_ary            an array of author ids if the author should be ignored during the search the array is empty
 398      * @param    string        $author_name        specifies the author match, when ANONYMOUS is also a search-match
 399      * @param    array        &$id_ary            passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered
 400      * @param    int            $start                indicates the first index of the page
 401      * @param    int            $per_page            number of ids each page is supposed to contain
 402      * @return    boolean|int                        total number of results
 403      */
 404  	public function keyword_search($type, $fields, $terms, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page)
 405      {
 406          // No keywords? No posts
 407          if (!$this->search_query)
 408          {
 409              return false;
 410          }
 411  
 412          // generate a search_key from all the options to identify the results
 413          $search_key_array = array(
 414              implode(', ', $this->split_words),
 415              $type,
 416              $fields,
 417              $terms,
 418              $sort_days,
 419              $sort_key,
 420              $topic_id,
 421              implode(',', $ex_fid_ary),
 422              $post_visibility,
 423              implode(',', $author_ary)
 424          );
 425  
 426          /**
 427          * Allow changing the search_key for cached results
 428          *
 429          * @event core.search_mysql_by_keyword_modify_search_key
 430          * @var    array    search_key_array    Array with search parameters to generate the search_key
 431          * @var    string    type                Searching type ('posts', 'topics')
 432          * @var    string    fields                Searching fields ('titleonly', 'msgonly', 'firstpost', 'all')
 433          * @var    string    terms                Searching terms ('all', 'any')
 434          * @var    int        sort_days            Time, in days, of the oldest possible post to list
 435          * @var    string    sort_key            The sort type used from the possible sort types
 436          * @var    int        topic_id            Limit the search to this topic_id only
 437          * @var    array    ex_fid_ary            Which forums not to search on
 438          * @var    string    post_visibility        Post visibility data
 439          * @var    array    author_ary            Array of user_id containing the users to filter the results to
 440          * @since 3.1.7-RC1
 441          */
 442          $vars = array(
 443              'search_key_array',
 444              'type',
 445              'fields',
 446              'terms',
 447              'sort_days',
 448              'sort_key',
 449              'topic_id',
 450              'ex_fid_ary',
 451              'post_visibility',
 452              'author_ary',
 453          );
 454          extract($this->phpbb_dispatcher->trigger_event('core.search_mysql_by_keyword_modify_search_key', compact($vars)));
 455  
 456          $search_key = md5(implode('#', $search_key_array));
 457  
 458          if ($start < 0)
 459          {
 460              $start = 0;
 461          }
 462  
 463          // try reading the results from cache
 464          $result_count = 0;
 465          if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE)
 466          {
 467              return $result_count;
 468          }
 469  
 470          $id_ary = array();
 471  
 472          $join_topic = ($type == 'posts') ? false : true;
 473  
 474          // Build sql strings for sorting
 475          $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');
 476          $sql_sort_table = $sql_sort_join = '';
 477  
 478          switch ($sql_sort[0])
 479          {
 480              case 'u':
 481                  $sql_sort_table    = USERS_TABLE . ' u, ';
 482                  $sql_sort_join    = ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster ';
 483              break;
 484  
 485              case 't':
 486                  $join_topic = true;
 487              break;
 488  
 489              case 'f':
 490                  $sql_sort_table    = FORUMS_TABLE . ' f, ';
 491                  $sql_sort_join    = ' AND f.forum_id = p.forum_id ';
 492              break;
 493          }
 494  
 495          // Build some display specific sql strings
 496          switch ($fields)
 497          {
 498              case 'titleonly':
 499                  $sql_match = 'p.post_subject';
 500                  $sql_match_where = ' AND p.post_id = t.topic_first_post_id';
 501                  $join_topic = true;
 502              break;
 503  
 504              case 'msgonly':
 505                  $sql_match = 'p.post_text';
 506                  $sql_match_where = '';
 507              break;
 508  
 509              case 'firstpost':
 510                  $sql_match = 'p.post_subject, p.post_text';
 511                  $sql_match_where = ' AND p.post_id = t.topic_first_post_id';
 512                  $join_topic = true;
 513              break;
 514  
 515              default:
 516                  $sql_match = 'p.post_subject, p.post_text';
 517                  $sql_match_where = '';
 518              break;
 519          }
 520  
 521          $search_query = $this->search_query;
 522  
 523          /**
 524          * Allow changing the query used to search for posts using fulltext_mysql
 525          *
 526          * @event core.search_mysql_keywords_main_query_before
 527          * @var    string    search_query        The parsed keywords used for this search
 528          * @var    int        result_count        The previous result count for the format of the query.
 529          *                                    Set to 0 to force a re-count
 530          * @var    bool    join_topic            Weather or not TOPICS_TABLE should be CROSS JOIN'ED
 531          * @var    array    author_ary            Array of user_id containing the users to filter the results to
 532          * @var    string    author_name            An extra username to search on (!empty(author_ary) must be true, to be relevant)
 533          * @var    array    ex_fid_ary            Which forums not to search on
 534          * @var    int        topic_id            Limit the search to this topic_id only
 535          * @var    string    sql_sort_table        Extra tables to include in the SQL query.
 536          *                                    Used in conjunction with sql_sort_join
 537          * @var    string    sql_sort_join        SQL conditions to join all the tables used together.
 538          *                                    Used in conjunction with sql_sort_table
 539          * @var    int        sort_days            Time, in days, of the oldest possible post to list
 540          * @var    string    sql_match            Which columns to do the search on.
 541          * @var    string    sql_match_where        Extra conditions to use to properly filter the matching process
 542          * @var    string    sort_by_sql            The possible predefined sort types
 543          * @var    string    sort_key            The sort type used from the possible sort types
 544          * @var    string    sort_dir            "a" for ASC or "d" dor DESC for the sort order used
 545          * @var    string    sql_sort            The result SQL when processing sort_by_sql + sort_key + sort_dir
 546          * @var    int        start                How many posts to skip in the search results (used for pagination)
 547          * @since 3.1.5-RC1
 548          */
 549          $vars = array(
 550              'search_query',
 551              'result_count',
 552              'join_topic',
 553              'author_ary',
 554              'author_name',
 555              'ex_fid_ary',
 556              'topic_id',
 557              'sql_sort_table',
 558              'sql_sort_join',
 559              'sort_days',
 560              'sql_match',
 561              'sql_match_where',
 562              'sort_by_sql',
 563              'sort_key',
 564              'sort_dir',
 565              'sql_sort',
 566              'start',
 567          );
 568          extract($this->phpbb_dispatcher->trigger_event('core.search_mysql_keywords_main_query_before', compact($vars)));
 569  
 570          $sql_select            = (!$result_count) ? 'SQL_CALC_FOUND_ROWS ' : '';
 571          $sql_select            = ($type == 'posts') ? $sql_select . 'p.post_id' : 'DISTINCT ' . $sql_select . 't.topic_id';
 572          $sql_from            = ($join_topic) ? TOPICS_TABLE . ' t, ' : '';
 573          $field                = ($type == 'posts') ? 'post_id' : 'topic_id';
 574          if (count($author_ary) && $author_name)
 575          {
 576              // first one matches post of registered users, second one guests and deleted users
 577              $sql_author = ' AND (' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')';
 578          }
 579          else if (count($author_ary))
 580          {
 581              $sql_author = ' AND ' . $this->db->sql_in_set('p.poster_id', $author_ary);
 582          }
 583          else
 584          {
 585              $sql_author = '';
 586          }
 587  
 588          $sql_where_options = $sql_sort_join;
 589          $sql_where_options .= ($topic_id) ? ' AND p.topic_id = ' . $topic_id : '';
 590          $sql_where_options .= ($join_topic) ? ' AND t.topic_id = p.topic_id' : '';
 591          $sql_where_options .= (count($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '';
 592          $sql_where_options .= ' AND ' . $post_visibility;
 593          $sql_where_options .= $sql_author;
 594          $sql_where_options .= ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : '';
 595          $sql_where_options .= $sql_match_where;
 596  
 597          $sql = "SELECT $sql_select
 598              FROM $sql_from$sql_sort_table" . POSTS_TABLE . " p
 599              WHERE MATCH ($sql_match) AGAINST ('" . $this->db->sql_escape(htmlspecialchars_decode($this->search_query)) . "' IN BOOLEAN MODE)
 600                  $sql_where_options
 601              ORDER BY $sql_sort";
 602          $this->db->sql_return_on_error(true);
 603          $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
 604  
 605          while ($row = $this->db->sql_fetchrow($result))
 606          {
 607              $id_ary[] = (int) $row[$field];
 608          }
 609          $this->db->sql_freeresult($result);
 610  
 611          $id_ary = array_unique($id_ary);
 612  
 613          // if the total result count is not cached yet, retrieve it from the db
 614          if (!$result_count && count($id_ary))
 615          {
 616              $sql_found_rows = 'SELECT FOUND_ROWS() as result_count';
 617              $result = $this->db->sql_query($sql_found_rows);
 618              $result_count = (int) $this->db->sql_fetchfield('result_count');
 619              $this->db->sql_freeresult($result);
 620  
 621              if (!$result_count)
 622              {
 623                  return false;
 624              }
 625          }
 626  
 627          if ($start >= $result_count)
 628          {
 629              $start = floor(($result_count - 1) / $per_page) * $per_page;
 630  
 631              $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
 632  
 633              while ($row = $this->db->sql_fetchrow($result))
 634              {
 635                  $id_ary[] = (int) $row[$field];
 636              }
 637              $this->db->sql_freeresult($result);
 638  
 639              $id_ary = array_unique($id_ary);
 640          }
 641  
 642          // store the ids, from start on then delete anything that isn't on the current page because we only need ids for one page
 643          $this->save_ids($search_key, implode(' ', $this->split_words), $author_ary, $result_count, $id_ary, $start, $sort_dir);
 644          $id_ary = array_slice($id_ary, 0, (int) $per_page);
 645  
 646          return $result_count;
 647      }
 648  
 649      /**
 650      * Performs a search on an author's posts without caring about message contents. Depends on display specific params
 651      *
 652      * @param    string        $type                contains either posts or topics depending on what should be searched for
 653      * @param    boolean        $firstpost_only        if true, only topic starting posts will be considered
 654      * @param    array        $sort_by_sql        contains SQL code for the ORDER BY part of a query
 655      * @param    string        $sort_key            is the key of $sort_by_sql for the selected sorting
 656      * @param    string        $sort_dir            is either a or d representing ASC and DESC
 657      * @param    string        $sort_days            specifies the maximum amount of days a post may be old
 658      * @param    array        $ex_fid_ary            specifies an array of forum ids which should not be searched
 659      * @param    string        $post_visibility    specifies which types of posts the user can view in which forums
 660      * @param    int            $topic_id            is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched
 661      * @param    array        $author_ary            an array of author ids
 662      * @param    string        $author_name        specifies the author match, when ANONYMOUS is also a search-match
 663      * @param    array        &$id_ary            passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered
 664      * @param    int            $start                indicates the first index of the page
 665      * @param    int            $per_page            number of ids each page is supposed to contain
 666      * @return    boolean|int                        total number of results
 667      */
 668  	public function author_search($type, $firstpost_only, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page)
 669      {
 670          // No author? No posts
 671          if (!count($author_ary))
 672          {
 673              return 0;
 674          }
 675  
 676          // generate a search_key from all the options to identify the results
 677          $search_key_array = array(
 678              '',
 679              $type,
 680              ($firstpost_only) ? 'firstpost' : '',
 681              '',
 682              '',
 683              $sort_days,
 684              $sort_key,
 685              $topic_id,
 686              implode(',', $ex_fid_ary),
 687              $post_visibility,
 688              implode(',', $author_ary),
 689              $author_name,
 690          );
 691  
 692          /**
 693          * Allow changing the search_key for cached results
 694          *
 695          * @event core.search_mysql_by_author_modify_search_key
 696          * @var    array    search_key_array    Array with search parameters to generate the search_key
 697          * @var    string    type                Searching type ('posts', 'topics')
 698          * @var    boolean    firstpost_only        Flag indicating if only topic starting posts are considered
 699          * @var    int        sort_days            Time, in days, of the oldest possible post to list
 700          * @var    string    sort_key            The sort type used from the possible sort types
 701          * @var    int        topic_id            Limit the search to this topic_id only
 702          * @var    array    ex_fid_ary            Which forums not to search on
 703          * @var    string    post_visibility        Post visibility data
 704          * @var    array    author_ary            Array of user_id containing the users to filter the results to
 705          * @var    string    author_name            The username to search on
 706          * @since 3.1.7-RC1
 707          */
 708          $vars = array(
 709              'search_key_array',
 710              'type',
 711              'firstpost_only',
 712              'sort_days',
 713              'sort_key',
 714              'topic_id',
 715              'ex_fid_ary',
 716              'post_visibility',
 717              'author_ary',
 718              'author_name',
 719          );
 720          extract($this->phpbb_dispatcher->trigger_event('core.search_mysql_by_author_modify_search_key', compact($vars)));
 721  
 722          $search_key = md5(implode('#', $search_key_array));
 723  
 724          if ($start < 0)
 725          {
 726              $start = 0;
 727          }
 728  
 729          // try reading the results from cache
 730          $result_count = 0;
 731          if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE)
 732          {
 733              return $result_count;
 734          }
 735  
 736          $id_ary = array();
 737  
 738          // Create some display specific sql strings
 739          if ($author_name)
 740          {
 741              // first one matches post of registered users, second one guests and deleted users
 742              $sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')';
 743          }
 744          else
 745          {
 746              $sql_author = $this->db->sql_in_set('p.poster_id', $author_ary);
 747          }
 748          $sql_fora        = (count($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '';
 749          $sql_topic_id    = ($topic_id) ? ' AND p.topic_id = ' . (int) $topic_id : '';
 750          $sql_time        = ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : '';
 751          $sql_firstpost = ($firstpost_only) ? ' AND p.post_id = t.topic_first_post_id' : '';
 752  
 753          // Build sql strings for sorting
 754          $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');
 755          $sql_sort_table = $sql_sort_join = '';
 756          switch ($sql_sort[0])
 757          {
 758              case 'u':
 759                  $sql_sort_table    = USERS_TABLE . ' u, ';
 760                  $sql_sort_join    = ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster ';
 761              break;
 762  
 763              case 't':
 764                  $sql_sort_table    = ($type == 'posts' && !$firstpost_only) ? TOPICS_TABLE . ' t, ' : '';
 765                  $sql_sort_join    = ($type == 'posts' && !$firstpost_only) ? ' AND t.topic_id = p.topic_id ' : '';
 766              break;
 767  
 768              case 'f':
 769                  $sql_sort_table    = FORUMS_TABLE . ' f, ';
 770                  $sql_sort_join    = ' AND f.forum_id = p.forum_id ';
 771              break;
 772          }
 773  
 774          $m_approve_fid_sql = ' AND ' . $post_visibility;
 775  
 776          /**
 777          * Allow changing the query used to search for posts by author in fulltext_mysql
 778          *
 779          * @event core.search_mysql_author_query_before
 780          * @var    int        result_count        The previous result count for the format of the query.
 781          *                                    Set to 0 to force a re-count
 782          * @var    string    sql_sort_table        CROSS JOIN'ed table to allow doing the sort chosen
 783          * @var    string    sql_sort_join        Condition to define how to join the CROSS JOIN'ed table specifyed in sql_sort_table
 784          * @var    string    type                Either "posts" or "topics" specifying the type of search being made
 785          * @var    array    author_ary            Array of user_id containing the users to filter the results to
 786          * @var    string    author_name            An extra username to search on
 787          * @var    string    sql_author            SQL WHERE condition for the post author ids
 788          * @var    int        topic_id            Limit the search to this topic_id only
 789          * @var    string    sql_topic_id        SQL of topic_id
 790          * @var    string    sort_by_sql            The possible predefined sort types
 791          * @var    string    sort_key            The sort type used from the possible sort types
 792          * @var    string    sort_dir            "a" for ASC or "d" dor DESC for the sort order used
 793          * @var    string    sql_sort            The result SQL when processing sort_by_sql + sort_key + sort_dir
 794          * @var    string    sort_days            Time, in days, that the oldest post showing can have
 795          * @var    string    sql_time            The SQL to search on the time specifyed by sort_days
 796          * @var    bool    firstpost_only        Wether or not to search only on the first post of the topics
 797          * @var    string    sql_firstpost        The SQL with the conditions to join the tables when using firstpost_only
 798          * @var    array    ex_fid_ary            Forum ids that must not be searched on
 799          * @var    array    sql_fora            SQL query for ex_fid_ary
 800          * @var    string    m_approve_fid_sql    WHERE clause condition on post_visibility restrictions
 801          * @var    int        start                How many posts to skip in the search results (used for pagination)
 802          * @since 3.1.5-RC1
 803          */
 804          $vars = array(
 805              'result_count',
 806              'sql_sort_table',
 807              'sql_sort_join',
 808              'type',
 809              'author_ary',
 810              'author_name',
 811              'sql_author',
 812              'topic_id',
 813              'sql_topic_id',
 814              'sort_by_sql',
 815              'sort_key',
 816              'sort_dir',
 817              'sql_sort',
 818              'sort_days',
 819              'sql_time',
 820              'firstpost_only',
 821              'sql_firstpost',
 822              'ex_fid_ary',
 823              'sql_fora',
 824              'm_approve_fid_sql',
 825              'start',
 826          );
 827          extract($this->phpbb_dispatcher->trigger_event('core.search_mysql_author_query_before', compact($vars)));
 828  
 829          // If the cache was completely empty count the results
 830          $calc_results = ($result_count) ? '' : 'SQL_CALC_FOUND_ROWS ';
 831  
 832          // Build the query for really selecting the post_ids
 833          if ($type == 'posts')
 834          {
 835              $sql = "SELECT {$calc_results}p.post_id
 836                  FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . "
 837                  WHERE $sql_author
 838                      $sql_topic_id
 839                      $sql_firstpost
 840                      $m_approve_fid_sql
 841                      $sql_fora
 842                      $sql_sort_join
 843                      $sql_time
 844                  ORDER BY $sql_sort";
 845              $field = 'post_id';
 846          }
 847          else
 848          {
 849              $sql = "SELECT {$calc_results}t.topic_id
 850                  FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
 851                  WHERE $sql_author
 852                      $sql_topic_id
 853                      $sql_firstpost
 854                      $m_approve_fid_sql
 855                      $sql_fora
 856                      AND t.topic_id = p.topic_id
 857                      $sql_sort_join
 858                      $sql_time
 859                  GROUP BY t.topic_id
 860                  ORDER BY $sql_sort";
 861              $field = 'topic_id';
 862          }
 863  
 864          // Only read one block of posts from the db and then cache it
 865          $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
 866  
 867          while ($row = $this->db->sql_fetchrow($result))
 868          {
 869              $id_ary[] = (int) $row[$field];
 870          }
 871          $this->db->sql_freeresult($result);
 872  
 873          // retrieve the total result count if needed
 874          if (!$result_count)
 875          {
 876              $sql_found_rows = 'SELECT FOUND_ROWS() as result_count';
 877              $result = $this->db->sql_query($sql_found_rows);
 878              $result_count = (int) $this->db->sql_fetchfield('result_count');
 879              $this->db->sql_freeresult($result);
 880  
 881              if (!$result_count)
 882              {
 883                  return false;
 884              }
 885          }
 886  
 887          if ($start >= $result_count)
 888          {
 889              $start = floor(($result_count - 1) / $per_page) * $per_page;
 890  
 891              $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
 892              while ($row = $this->db->sql_fetchrow($result))
 893              {
 894                  $id_ary[] = (int) $row[$field];
 895              }
 896              $this->db->sql_freeresult($result);
 897  
 898              $id_ary = array_unique($id_ary);
 899          }
 900  
 901          if (count($id_ary))
 902          {
 903              $this->save_ids($search_key, '', $author_ary, $result_count, $id_ary, $start, $sort_dir);
 904              $id_ary = array_slice($id_ary, 0, $per_page);
 905  
 906              return $result_count;
 907          }
 908          return false;
 909      }
 910  
 911      /**
 912      * Destroys cached search results, that contained one of the new words in a post so the results won't be outdated
 913      *
 914      * @param    string        $mode contains the post mode: edit, post, reply, quote ...
 915      * @param    int            $post_id    contains the post id of the post to index
 916      * @param    string        $message    contains the post text of the post
 917      * @param    string        $subject    contains the subject of the post to index
 918      * @param    int            $poster_id    contains the user id of the poster
 919      * @param    int            $forum_id    contains the forum id of parent forum of the post
 920      */
 921  	public function index($mode, $post_id, &$message, &$subject, $poster_id, $forum_id)
 922      {
 923          // Split old and new post/subject to obtain array of words
 924          $split_text = $this->split_message($message);
 925          $split_title = ($subject) ? $this->split_message($subject) : array();
 926  
 927          $words = array_unique(array_merge($split_text, $split_title));
 928  
 929          /**
 930          * Event to modify method arguments and words before the MySQL search index is updated
 931          *
 932          * @event core.search_mysql_index_before
 933          * @var string    mode                Contains the post mode: edit, post, reply, quote
 934          * @var int        post_id                The id of the post which is modified/created
 935          * @var string    message                New or updated post content
 936          * @var string    subject                New or updated post subject
 937          * @var int        poster_id            Post author's user id
 938          * @var int        forum_id            The id of the forum in which the post is located
 939          * @var array    words                List of words added to the index
 940          * @var array    split_text            Array of words from the message
 941          * @var array    split_title            Array of words from the title
 942          * @since 3.2.3-RC1
 943          */
 944          $vars = array(
 945              'mode',
 946              'post_id',
 947              'message',
 948              'subject',
 949              'poster_id',
 950              'forum_id',
 951              'words',
 952              'split_text',
 953              'split_title',
 954          );
 955          extract($this->phpbb_dispatcher->trigger_event('core.search_mysql_index_before', compact($vars)));
 956  
 957          unset($split_text);
 958          unset($split_title);
 959  
 960          // destroy cached search results containing any of the words removed or added
 961          $this->destroy_cache($words, array($poster_id));
 962  
 963          unset($words);
 964      }
 965  
 966      /**
 967      * Destroy cached results, that might be outdated after deleting a post
 968      */
 969  	public function index_remove($post_ids, $author_ids, $forum_ids)
 970      {
 971          $this->destroy_cache(array(), array_unique($author_ids));
 972      }
 973  
 974      /**
 975      * Destroy old cache entries
 976      */
 977  	public function tidy()
 978      {
 979          // destroy too old cached search results
 980          $this->destroy_cache(array());
 981  
 982          $this->config->set('search_last_gc', time(), false);
 983      }
 984  
 985      /**
 986      * Create fulltext index
 987      *
 988      * @return string|bool error string is returned incase of errors otherwise false
 989      */
 990  	public function create_index($acp_module, $u_action)
 991      {
 992          // Make sure we can actually use MySQL with fulltext indexes
 993          if ($error = $this->init())
 994          {
 995              return $error;
 996          }
 997  
 998          if (empty($this->stats))
 999          {
1000              $this->get_stats();
1001          }
1002  
1003          $alter_list = array();
1004  
1005          if (!isset($this->stats['post_subject']))
1006          {
1007              $alter_entry = array();
1008              if ($this->db->get_sql_layer() == 'mysqli' || version_compare($this->db->sql_server_info(true), '4.1.3', '>='))
1009              {
1010                  $alter_entry[] = 'MODIFY post_subject varchar(255) COLLATE utf8_unicode_ci DEFAULT \'\' NOT NULL';
1011              }
1012              else
1013              {
1014                  $alter_entry[] = 'MODIFY post_subject text NOT NULL';
1015              }
1016              $alter_entry[] = 'ADD FULLTEXT (post_subject)';
1017              $alter_list[] = $alter_entry;
1018          }
1019  
1020          if (!isset($this->stats['post_content']))
1021          {
1022              $alter_entry = array();
1023              if ($this->db->get_sql_layer() == 'mysqli' || version_compare($this->db->sql_server_info(true), '4.1.3', '>='))
1024              {
1025                  $alter_entry[] = 'MODIFY post_text mediumtext COLLATE utf8_unicode_ci NOT NULL';
1026              }
1027              else
1028              {
1029                  $alter_entry[] = 'MODIFY post_text mediumtext NOT NULL';
1030              }
1031  
1032              $alter_entry[] = 'ADD FULLTEXT post_content (post_text, post_subject)';
1033              $alter_list[] = $alter_entry;
1034          }
1035  
1036          $sql_queries = [];
1037  
1038          foreach ($alter_list as $alter)
1039          {
1040              $sql_queries[] = 'ALTER TABLE ' . POSTS_TABLE . ' ' . implode(', ', $alter);
1041          }
1042  
1043          if (!isset($this->stats['post_text']))
1044          {
1045              $sql_queries[] = 'ALTER TABLE ' . POSTS_TABLE . ' ADD FULLTEXT post_text (post_text)';
1046          }
1047  
1048          $stats = $this->stats;
1049  
1050          /**
1051          * Event to modify SQL queries before the MySQL search index is created
1052          *
1053          * @event core.search_mysql_create_index_before
1054          * @var array    sql_queries            Array with queries for creating the search index
1055          * @var array    stats                Array with statistics of the current index (read only)
1056          * @since 3.2.3-RC1
1057          */
1058          $vars = array(
1059              'sql_queries',
1060              'stats',
1061          );
1062          extract($this->phpbb_dispatcher->trigger_event('core.search_mysql_create_index_before', compact($vars)));
1063  
1064          foreach ($sql_queries as $sql_query)
1065          {
1066              $this->db->sql_query($sql_query);
1067          }
1068  
1069          $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE);
1070  
1071          return false;
1072      }
1073  
1074      /**
1075      * Drop fulltext index
1076      *
1077      * @return string|bool error string is returned incase of errors otherwise false
1078      */
1079  	public function delete_index($acp_module, $u_action)
1080      {
1081          // Make sure we can actually use MySQL with fulltext indexes
1082          if ($error = $this->init())
1083          {
1084              return $error;
1085          }
1086  
1087          if (empty($this->stats))
1088          {
1089              $this->get_stats();
1090          }
1091  
1092          $alter = array();
1093  
1094          if (isset($this->stats['post_subject']))
1095          {
1096              $alter[] = 'DROP INDEX post_subject';
1097          }
1098  
1099          if (isset($this->stats['post_content']))
1100          {
1101              $alter[] = 'DROP INDEX post_content';
1102          }
1103  
1104          if (isset($this->stats['post_text']))
1105          {
1106              $alter[] = 'DROP INDEX post_text';
1107          }
1108  
1109          $sql_queries = [];
1110  
1111          if (count($alter))
1112          {
1113              $sql_queries[] = 'ALTER TABLE ' . POSTS_TABLE . ' ' . implode(', ', $alter);
1114          }
1115  
1116          $stats = $this->stats;
1117  
1118          /**
1119          * Event to modify SQL queries before the MySQL search index is deleted
1120          *
1121          * @event core.search_mysql_delete_index_before
1122          * @var array    sql_queries            Array with queries for deleting the search index
1123          * @var array    stats                Array with statistics of the current index (read only)
1124          * @since 3.2.3-RC1
1125          */
1126          $vars = array(
1127              'sql_queries',
1128              'stats',
1129          );
1130          extract($this->phpbb_dispatcher->trigger_event('core.search_mysql_delete_index_before', compact($vars)));
1131  
1132          foreach ($sql_queries as $sql_query)
1133          {
1134              $this->db->sql_query($sql_query);
1135          }
1136  
1137          $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE);
1138  
1139          return false;
1140      }
1141  
1142      /**
1143      * Returns true if both FULLTEXT indexes exist
1144      */
1145  	public function index_created()
1146      {
1147          if (empty($this->stats))
1148          {
1149              $this->get_stats();
1150          }
1151  
1152          return isset($this->stats['post_subject']) && isset($this->stats['post_content']) && isset($this->stats['post_text']);
1153      }
1154  
1155      /**
1156      * Returns an associative array containing information about the indexes
1157      */
1158  	public function index_stats()
1159      {
1160          if (empty($this->stats))
1161          {
1162              $this->get_stats();
1163          }
1164  
1165          return array(
1166              $this->user->lang['FULLTEXT_MYSQL_TOTAL_POSTS']            => ($this->index_created()) ? $this->stats['total_posts'] : 0,
1167          );
1168      }
1169  
1170      /**
1171       * Computes the stats and store them in the $this->stats associative array
1172       */
1173  	protected function get_stats()
1174      {
1175          if (strpos($this->db->get_sql_layer(), 'mysql') === false)
1176          {
1177              $this->stats = array();
1178              return;
1179          }
1180  
1181          $sql = 'SHOW INDEX
1182              FROM ' . POSTS_TABLE;
1183          $result = $this->db->sql_query($sql);
1184  
1185          while ($row = $this->db->sql_fetchrow($result))
1186          {
1187              // deal with older MySQL versions which didn't use Index_type
1188              $index_type = (isset($row['Index_type'])) ? $row['Index_type'] : $row['Comment'];
1189  
1190              if ($index_type == 'FULLTEXT')
1191              {
1192                  if ($row['Key_name'] == 'post_subject')
1193                  {
1194                      $this->stats['post_subject'] = $row;
1195                  }
1196                  else if ($row['Key_name'] == 'post_text')
1197                  {
1198                      $this->stats['post_text'] = $row;
1199                  }
1200                  else if ($row['Key_name'] == 'post_content')
1201                  {
1202                      $this->stats['post_content'] = $row;
1203                  }
1204              }
1205          }
1206          $this->db->sql_freeresult($result);
1207  
1208          $this->stats['total_posts'] = empty($this->stats) ? 0 : $this->db->get_estimated_row_count(POSTS_TABLE);
1209      }
1210  
1211      /**
1212      * Display a note, that UTF-8 support is not available with certain versions of PHP
1213      *
1214      * @return associative array containing template and config variables
1215      */
1216  	public function acp()
1217      {
1218          $tpl = '
1219          <dl>
1220              <dt><label>' . $this->user->lang['MIN_SEARCH_CHARS'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_MYSQL_MIN_SEARCH_CHARS_EXPLAIN'] . '</span></dt>
1221              <dd>' . $this->config['fulltext_mysql_min_word_len'] . '</dd>
1222          </dl>
1223          <dl>
1224              <dt><label>' . $this->user->lang['MAX_SEARCH_CHARS'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_MYSQL_MAX_SEARCH_CHARS_EXPLAIN'] . '</span></dt>
1225              <dd>' . $this->config['fulltext_mysql_max_word_len'] . '</dd>
1226          </dl>
1227          ';
1228  
1229          // These are fields required in the config table
1230          return array(
1231              'tpl'        => $tpl,
1232              'config'    => array()
1233          );
1234      }
1235  }


Generated: Tue Apr 7 19:42:26 2020 Cross-referenced by PHPXref 0.7.1