ManageSearch.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. <?php
  2. /**
  3. * The admin screen to change the search settings.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2011 Simple Machines
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.0
  13. */
  14. if (!defined('SMF'))
  15. die('Hacking attempt...');
  16. /**
  17. * Main entry point for the admin search settings screen.
  18. * It checks permissions, and it forwards to the appropriate function based on
  19. * the given sub-action.
  20. * Defaults to sub-action 'settings'.
  21. * Called by ?action=admin;area=managesearch.
  22. * Requires the admin_forum permission.
  23. *
  24. * @uses ManageSearch template.
  25. * @uses Search language file.
  26. */
  27. function ManageSearch()
  28. {
  29. global $context, $txt, $scripturl;
  30. isAllowedTo('admin_forum');
  31. loadLanguage('Search');
  32. loadTemplate('ManageSearch');
  33. db_extend('search');
  34. $subActions = array(
  35. 'settings' => 'EditSearchSettings',
  36. 'weights' => 'EditWeights',
  37. 'method' => 'EditSearchMethod',
  38. 'createfulltext' => 'EditSearchMethod',
  39. 'removecustom' => 'EditSearchMethod',
  40. 'removefulltext' => 'EditSearchMethod',
  41. 'createmsgindex' => 'CreateMessageIndex',
  42. );
  43. call_integration_hook('integrate_manage_search', array(&$subActions));
  44. // Default the sub-action to 'edit search settings'.
  45. $_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'weights';
  46. $context['sub_action'] = $_REQUEST['sa'];
  47. // Create the tabs for the template.
  48. $context[$context['admin_menu_name']]['tab_data'] = array(
  49. 'title' => $txt['manage_search'],
  50. 'help' => 'search',
  51. 'description' => $txt['search_settings_desc'],
  52. 'tabs' => array(
  53. 'weights' => array(
  54. 'description' => $txt['search_weights_desc'],
  55. ),
  56. 'method' => array(
  57. 'description' => $txt['search_method_desc'],
  58. ),
  59. 'settings' => array(
  60. 'description' => $txt['search_settings_desc'],
  61. ),
  62. ),
  63. );
  64. // Call the right function for this sub-acton.
  65. $subActions[$_REQUEST['sa']]();
  66. }
  67. /**
  68. * Edit some general settings related to the search function.
  69. * Called by ?action=admin;area=managesearch;sa=settings.
  70. * Requires the admin_forum permission.
  71. *
  72. * @param $return_config
  73. * @uses ManageSearch template, 'modify_settings' sub-template.
  74. */
  75. function EditSearchSettings($return_config = false)
  76. {
  77. global $txt, $context, $scripturl, $sourcedir, $modSettings;
  78. // What are we editing anyway?
  79. $config_vars = array(
  80. // Permission...
  81. array('permissions', 'search_posts'),
  82. // Some simple settings.
  83. array('check', 'simpleSearch'),
  84. array('int', 'search_results_per_page'),
  85. array('int', 'search_max_results', 'subtext' => $txt['search_max_results_disable']),
  86. '',
  87. // Some limitations.
  88. array('int', 'search_floodcontrol_time', 'subtext' => $txt['search_floodcontrol_time_desc']),
  89. );
  90. call_integration_hook('integrate_modify_search_settings', array(&$config_vars));
  91. // Perhaps the search method wants to add some settings?
  92. $modSettings['search_index'] = empty($modSettings['search_index']) ? 'standard' : $modSettings['search_index'];
  93. if (file_exists($sourcedir . '/SearchAPI-' . ucwords($modSettings['search_index']) . '.php'))
  94. {
  95. loadClassFile('SearchAPI-' . ucwords($modSettings['search_index']) . '.php');
  96. $method_call = array($modSettings['search_index'] . '_search', 'searchSettings');
  97. if (is_callable($method_call))
  98. call_user_func_array($method_call, array(&$config_vars));
  99. }
  100. if ($return_config)
  101. return $config_vars;
  102. $context['page_title'] = $txt['search_settings_title'];
  103. $context['sub_template'] = 'show_settings';
  104. // We'll need this for the settings.
  105. require_once($sourcedir . '/ManageServer.php');
  106. // A form was submitted.
  107. if (isset($_REQUEST['save']))
  108. {
  109. checkSession();
  110. call_integration_hook('integrate_save_search_settings');
  111. saveDBSettings($config_vars);
  112. redirectexit('action=admin;area=managesearch;sa=settings;' . $context['session_var'] . '=' . $context['session_id']);
  113. }
  114. // Prep the template!
  115. $context['post_url'] = $scripturl . '?action=admin;area=managesearch;save;sa=settings';
  116. $context['settings_title'] = $txt['search_settings_title'];
  117. prepareDBSettingContext($config_vars);
  118. }
  119. /**
  120. * Edit the relative weight of the search factors.
  121. * Called by ?action=admin;area=managesearch;sa=weights.
  122. * Requires the admin_forum permission.
  123. *
  124. * @uses ManageSearch template, 'modify_weights' sub-template.
  125. */
  126. function EditWeights()
  127. {
  128. global $txt, $context, $modSettings;
  129. $context['page_title'] = $txt['search_weights_title'];
  130. $context['sub_template'] = 'modify_weights';
  131. $factors = array(
  132. 'search_weight_frequency',
  133. 'search_weight_age',
  134. 'search_weight_length',
  135. 'search_weight_subject',
  136. 'search_weight_first_message',
  137. 'search_weight_sticky',
  138. );
  139. // A form was submitted.
  140. if (isset($_POST['save']))
  141. {
  142. checkSession();
  143. validateToken('admin-msw');
  144. $changes = array();
  145. foreach ($factors as $factor)
  146. $changes[$factor] = (int) $_POST[$factor];
  147. updateSettings($changes);
  148. }
  149. $context['relative_weights'] = array('total' => 0);
  150. foreach ($factors as $factor)
  151. $context['relative_weights']['total'] += isset($modSettings[$factor]) ? $modSettings[$factor] : 0;
  152. foreach ($factors as $factor)
  153. $context['relative_weights'][$factor] = round(100 * (isset($modSettings[$factor]) ? $modSettings[$factor] : 0) / $context['relative_weights']['total'], 1);
  154. createToken('admin-msw');
  155. }
  156. /**
  157. * Edit the search method and search index used.
  158. * Calculates the size of the current search indexes in use.
  159. * Allows to create and delete a fulltext index on the messages table.
  160. * Allows to delete a custom index (that CreateMessageIndex() created).
  161. * Called by ?action=admin;area=managesearch;sa=method.
  162. * Requires the admin_forum permission.
  163. *
  164. * @uses ManageSearch template, 'select_search_method' sub-template.
  165. */
  166. function EditSearchMethod()
  167. {
  168. global $txt, $context, $modSettings, $smcFunc, $db_type, $db_prefix;
  169. $context[$context['admin_menu_name']]['current_subsection'] = 'method';
  170. $context['page_title'] = $txt['search_method_title'];
  171. $context['sub_template'] = 'select_search_method';
  172. $context['supports_fulltext'] = $smcFunc['db_search_support']('fulltext');
  173. // Load any apis.
  174. $context['search_apis'] = loadSearchAPIs();
  175. // Detect whether a fulltext index is set.
  176. if ($context['supports_fulltext'])
  177. {
  178. $request = $smcFunc['db_query']('', '
  179. SHOW INDEX
  180. FROM {db_prefix}messages',
  181. array(
  182. )
  183. );
  184. $context['fulltext_index'] = '';
  185. if ($request !== false || $smcFunc['db_num_rows']($request) != 0)
  186. {
  187. while ($row = $smcFunc['db_fetch_assoc']($request))
  188. if ($row['Column_name'] == 'body' && (isset($row['Index_type']) && $row['Index_type'] == 'FULLTEXT' || isset($row['Comment']) && $row['Comment'] == 'FULLTEXT'))
  189. $context['fulltext_index'][] = $row['Key_name'];
  190. $smcFunc['db_free_result']($request);
  191. if (is_array($context['fulltext_index']))
  192. $context['fulltext_index'] = array_unique($context['fulltext_index']);
  193. }
  194. $request = $smcFunc['db_query']('', '
  195. SHOW COLUMNS
  196. FROM {db_prefix}messages',
  197. array(
  198. )
  199. );
  200. if ($request !== false)
  201. {
  202. while ($row = $smcFunc['db_fetch_assoc']($request))
  203. if ($row['Field'] == 'body' && $row['Type'] == 'mediumtext')
  204. $context['cannot_create_fulltext'] = true;
  205. $smcFunc['db_free_result']($request);
  206. }
  207. if (preg_match('~^`(.+?)`\.(.+?)$~', $db_prefix, $match) !== 0)
  208. $request = $smcFunc['db_query']('', '
  209. SHOW TABLE STATUS
  210. FROM {string:database_name}
  211. LIKE {string:table_name}',
  212. array(
  213. 'database_name' => '`' . strtr($match[1], array('`' => '')) . '`',
  214. 'table_name' => str_replace('_', '\_', $match[2]) . 'messages',
  215. )
  216. );
  217. else
  218. $request = $smcFunc['db_query']('', '
  219. SHOW TABLE STATUS
  220. LIKE {string:table_name}',
  221. array(
  222. 'table_name' => str_replace('_', '\_', $db_prefix) . 'messages',
  223. )
  224. );
  225. if ($request !== false)
  226. {
  227. while ($row = $smcFunc['db_fetch_assoc']($request))
  228. if ((isset($row['Type']) && strtolower($row['Type']) != 'myisam') || (isset($row['Engine']) && strtolower($row['Engine']) != 'myisam'))
  229. $context['cannot_create_fulltext'] = true;
  230. $smcFunc['db_free_result']($request);
  231. }
  232. }
  233. if (!empty($_REQUEST['sa']) && $_REQUEST['sa'] == 'createfulltext')
  234. {
  235. checkSession('get');
  236. validateToken('admin-msm');
  237. // Make sure it's gone before creating it.
  238. $smcFunc['db_query']('', '
  239. ALTER TABLE {db_prefix}messages
  240. DROP INDEX body',
  241. array(
  242. 'db_error_skip' => true,
  243. )
  244. );
  245. $smcFunc['db_query']('', '
  246. ALTER TABLE {db_prefix}messages
  247. ADD FULLTEXT body (body)',
  248. array(
  249. )
  250. );
  251. $context['fulltext_index'] = 'body';
  252. }
  253. elseif (!empty($_REQUEST['sa']) && $_REQUEST['sa'] == 'removefulltext' && !empty($context['fulltext_index']))
  254. {
  255. checkSession('get');
  256. validateToken('admin-msm');
  257. $smcFunc['db_query']('', '
  258. ALTER TABLE {db_prefix}messages
  259. DROP INDEX ' . implode(',
  260. DROP INDEX ', $context['fulltext_index']),
  261. array(
  262. 'db_error_skip' => true,
  263. )
  264. );
  265. $context['fulltext_index'] = '';
  266. // Go back to the default search method.
  267. if (!empty($modSettings['search_index']) && $modSettings['search_index'] == 'fulltext')
  268. updateSettings(array(
  269. 'search_index' => '',
  270. ));
  271. }
  272. elseif (!empty($_REQUEST['sa']) && $_REQUEST['sa'] == 'removecustom')
  273. {
  274. checkSession('get');
  275. validateToken('admin-msm');
  276. db_extend();
  277. $tables = $smcFunc['db_list_tables'](false, $db_prefix . 'log_search_words');
  278. if (!empty($tables))
  279. {
  280. $smcFunc['db_search_query']('drop_words_table', '
  281. DROP TABLE {db_prefix}log_search_words',
  282. array(
  283. )
  284. );
  285. }
  286. updateSettings(array(
  287. 'search_custom_index_config' => '',
  288. 'search_custom_index_resume' => '',
  289. ));
  290. // Go back to the default search method.
  291. if (!empty($modSettings['search_index']) && $modSettings['search_index'] == 'custom')
  292. updateSettings(array(
  293. 'search_index' => '',
  294. ));
  295. }
  296. elseif (isset($_POST['save']))
  297. {
  298. checkSession();
  299. validateToken('admin-msm');
  300. updateSettings(array(
  301. 'search_index' => empty($_POST['search_index']) || (!in_array($_POST['search_index'], array('fulltext', 'custom')) && !isset($context['search_apis'][$_POST['search_index']])) ? '' : $_POST['search_index'],
  302. 'search_force_index' => isset($_POST['search_force_index']) ? '1' : '0',
  303. 'search_match_words' => isset($_POST['search_match_words']) ? '1' : '0',
  304. ));
  305. }
  306. $context['table_info'] = array(
  307. 'data_length' => 0,
  308. 'index_length' => 0,
  309. 'fulltext_length' => 0,
  310. 'custom_index_length' => 0,
  311. );
  312. // Get some info about the messages table, to show its size and index size.
  313. if ($db_type == 'mysql')
  314. {
  315. if (preg_match('~^`(.+?)`\.(.+?)$~', $db_prefix, $match) !== 0)
  316. $request = $smcFunc['db_query']('', '
  317. SHOW TABLE STATUS
  318. FROM {string:database_name}
  319. LIKE {string:table_name}',
  320. array(
  321. 'database_name' => '`' . strtr($match[1], array('`' => '')) . '`',
  322. 'table_name' => str_replace('_', '\_', $match[2]) . 'messages',
  323. )
  324. );
  325. else
  326. $request = $smcFunc['db_query']('', '
  327. SHOW TABLE STATUS
  328. LIKE {string:table_name}',
  329. array(
  330. 'table_name' => str_replace('_', '\_', $db_prefix) . 'messages',
  331. )
  332. );
  333. if ($request !== false && $smcFunc['db_num_rows']($request) == 1)
  334. {
  335. // Only do this if the user has permission to execute this query.
  336. $row = $smcFunc['db_fetch_assoc']($request);
  337. $context['table_info']['data_length'] = $row['Data_length'];
  338. $context['table_info']['index_length'] = $row['Index_length'];
  339. $context['table_info']['fulltext_length'] = $row['Index_length'];
  340. $smcFunc['db_free_result']($request);
  341. }
  342. // Now check the custom index table, if it exists at all.
  343. if (preg_match('~^`(.+?)`\.(.+?)$~', $db_prefix, $match) !== 0)
  344. $request = $smcFunc['db_query']('', '
  345. SHOW TABLE STATUS
  346. FROM {string:database_name}
  347. LIKE {string:table_name}',
  348. array(
  349. 'database_name' => '`' . strtr($match[1], array('`' => '')) . '`',
  350. 'table_name' => str_replace('_', '\_', $match[2]) . 'log_search_words',
  351. )
  352. );
  353. else
  354. $request = $smcFunc['db_query']('', '
  355. SHOW TABLE STATUS
  356. LIKE {string:table_name}',
  357. array(
  358. 'table_name' => str_replace('_', '\_', $db_prefix) . 'log_search_words',
  359. )
  360. );
  361. if ($request !== false && $smcFunc['db_num_rows']($request) == 1)
  362. {
  363. // Only do this if the user has permission to execute this query.
  364. $row = $smcFunc['db_fetch_assoc']($request);
  365. $context['table_info']['index_length'] += $row['Data_length'] + $row['Index_length'];
  366. $context['table_info']['custom_index_length'] = $row['Data_length'] + $row['Index_length'];
  367. $smcFunc['db_free_result']($request);
  368. }
  369. }
  370. elseif ($db_type == 'postgresql')
  371. {
  372. // In order to report the sizes correctly we need to perform vacuum (optimize) on the tables we will be using.
  373. db_extend();
  374. $temp_tables = $smcFunc['db_list_tables']();
  375. foreach ($temp_tables as $table)
  376. if ($table == $db_prefix. 'messages' || $table == $db_prefix. 'log_search_words')
  377. $smcFunc['db_optimize_table']($table);
  378. // PostGreSql has some hidden sizes.
  379. $request = $smcFunc['db_query']('', '
  380. SELECT relname, relpages * 8 *1024 AS "KB" FROM pg_class
  381. WHERE relname = {string:messages} OR relname = {string:log_search_words}
  382. ORDER BY relpages DESC',
  383. array(
  384. 'messages' => $db_prefix. 'messages',
  385. 'log_search_words' => $db_prefix. 'log_search_words',
  386. )
  387. );
  388. if ($request !== false && $smcFunc['db_num_rows']($request) > 0)
  389. {
  390. while ($row = $smcFunc['db_fetch_assoc']($request))
  391. {
  392. if ($row['relname'] == $db_prefix . 'messages')
  393. {
  394. $context['table_info']['data_length'] = (int) $row['KB'];
  395. $context['table_info']['index_length'] = (int) $row['KB'];
  396. // Doesn't support fulltext
  397. $context['table_info']['fulltext_length'] = $txt['not_applicable'];
  398. }
  399. elseif ($row['relname'] == $db_prefix. 'log_search_words')
  400. {
  401. $context['table_info']['index_length'] = (int) $row['KB'];
  402. $context['table_info']['custom_index_length'] = (int) $row['KB'];
  403. }
  404. }
  405. $smcFunc['db_free_result']($request);
  406. }
  407. else
  408. // Didn't work for some reason...
  409. $context['table_info'] = array(
  410. 'data_length' => $txt['not_applicable'],
  411. 'index_length' => $txt['not_applicable'],
  412. 'fulltext_length' => $txt['not_applicable'],
  413. 'custom_index_length' => $txt['not_applicable'],
  414. );
  415. }
  416. else
  417. $context['table_info'] = array(
  418. 'data_length' => $txt['not_applicable'],
  419. 'index_length' => $txt['not_applicable'],
  420. 'fulltext_length' => $txt['not_applicable'],
  421. 'custom_index_length' => $txt['not_applicable'],
  422. );
  423. // Format the data and index length in kilobytes.
  424. foreach ($context['table_info'] as $type => $size)
  425. {
  426. // If it's not numeric then just break. This database engine doesn't support size.
  427. if (!is_numeric($size))
  428. break;
  429. $context['table_info'][$type] = comma_format($context['table_info'][$type] / 1024) . ' ' . $txt['search_method_kilobytes'];
  430. }
  431. $context['custom_index'] = !empty($modSettings['search_custom_index_config']);
  432. $context['partial_custom_index'] = !empty($modSettings['search_custom_index_resume']) && empty($modSettings['search_custom_index_config']);
  433. $context['double_index'] = !empty($context['fulltext_index']) && $context['custom_index'];
  434. createToken('admin-msm');
  435. }
  436. /**
  437. * Create a custom search index for the messages table.
  438. * Called by ?action=admin;area=managesearch;sa=createmsgindex.
  439. * Linked from the EditSearchMethod screen.
  440. * Requires the admin_forum permission.
  441. * Depending on the size of the message table, the process is divided in steps.
  442. *
  443. * @uses ManageSearch template, 'create_index', 'create_index_progress', and 'create_index_done'
  444. * sub-templates.
  445. */
  446. function CreateMessageIndex()
  447. {
  448. global $modSettings, $context, $smcFunc, $db_prefix, $txt;
  449. // Scotty, we need more time...
  450. @set_time_limit(600);
  451. if (function_exists('apache_reset_timeout'))
  452. @apache_reset_timeout();
  453. $context[$context['admin_menu_name']]['current_subsection'] = 'method';
  454. $context['page_title'] = $txt['search_index_custom'];
  455. $messages_per_batch = 50;
  456. $index_properties = array(
  457. 2 => array(
  458. 'column_definition' => 'small',
  459. 'step_size' => 1000000,
  460. ),
  461. 4 => array(
  462. 'column_definition' => 'medium',
  463. 'step_size' => 1000000,
  464. 'max_size' => 16777215,
  465. ),
  466. 5 => array(
  467. 'column_definition' => 'large',
  468. 'step_size' => 100000000,
  469. 'max_size' => 2000000000,
  470. ),
  471. );
  472. if (isset($_REQUEST['resume']) && !empty($modSettings['search_custom_index_resume']))
  473. {
  474. $context['index_settings'] = unserialize($modSettings['search_custom_index_resume']);
  475. $context['start'] = (int) $context['index_settings']['resume_at'];
  476. unset($context['index_settings']['resume_at']);
  477. $context['step'] = 1;
  478. }
  479. else
  480. {
  481. $context['index_settings'] = array(
  482. 'bytes_per_word' => isset($_REQUEST['bytes_per_word']) && isset($index_properties[$_REQUEST['bytes_per_word']]) ? (int) $_REQUEST['bytes_per_word'] : 2,
  483. );
  484. $context['start'] = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;
  485. $context['step'] = isset($_REQUEST['step']) ? (int) $_REQUEST['step'] : 0;
  486. }
  487. if ($context['step'] !== 0)
  488. checkSession('request');
  489. // Step 0: let the user determine how they like their index.
  490. if ($context['step'] === 0)
  491. {
  492. $context['sub_template'] = 'create_index';
  493. }
  494. // Step 1: insert all the words.
  495. if ($context['step'] === 1)
  496. {
  497. $context['sub_template'] = 'create_index_progress';
  498. if ($context['start'] === 0)
  499. {
  500. db_extend();
  501. $tables = $smcFunc['db_list_tables'](false, $db_prefix . 'log_search_words');
  502. if (!empty($tables))
  503. {
  504. $smcFunc['db_search_query']('drop_words_table', '
  505. DROP TABLE {db_prefix}log_search_words',
  506. array(
  507. )
  508. );
  509. }
  510. $smcFunc['db_create_word_search']($index_properties[$context['index_settings']['bytes_per_word']]['column_definition']);
  511. // Temporarily switch back to not using a search index.
  512. if (!empty($modSettings['search_index']) && $modSettings['search_index'] == 'custom')
  513. updateSettings(array('search_index' => ''));
  514. // Don't let simultanious processes be updating the search index.
  515. if (!empty($modSettings['search_custom_index_config']))
  516. updateSettings(array('search_custom_index_config' => ''));
  517. }
  518. $num_messages = array(
  519. 'done' => 0,
  520. 'todo' => 0,
  521. );
  522. $request = $smcFunc['db_query']('', '
  523. SELECT id_msg >= {int:starting_id} AS todo, COUNT(*) AS num_messages
  524. FROM {db_prefix}messages
  525. GROUP BY todo',
  526. array(
  527. 'starting_id' => $context['start'],
  528. )
  529. );
  530. while ($row = $smcFunc['db_fetch_assoc']($request))
  531. $num_messages[empty($row['todo']) ? 'done' : 'todo'] = $row['num_messages'];
  532. if (empty($num_messages['todo']))
  533. {
  534. $context['step'] = 2;
  535. $context['percentage'] = 80;
  536. $context['start'] = 0;
  537. }
  538. else
  539. {
  540. // Number of seconds before the next step.
  541. $stop = time() + 3;
  542. while (time() < $stop)
  543. {
  544. $inserts = array();
  545. $request = $smcFunc['db_query']('', '
  546. SELECT id_msg, body
  547. FROM {db_prefix}messages
  548. WHERE id_msg BETWEEN {int:starting_id} AND {int:ending_id}
  549. LIMIT {int:limit}',
  550. array(
  551. 'starting_id' => $context['start'],
  552. 'ending_id' => $context['start'] + $messages_per_batch - 1,
  553. 'limit' => $messages_per_batch,
  554. )
  555. );
  556. $forced_break = false;
  557. $number_processed = 0;
  558. while ($row = $smcFunc['db_fetch_assoc']($request))
  559. {
  560. // In theory it's possible for one of these to take friggin ages so add more timeout protection.
  561. if ($stop < time())
  562. {
  563. $forced_break = true;
  564. break;
  565. }
  566. $number_processed++;
  567. foreach (text2words($row['body'], $context['index_settings']['bytes_per_word'], true) as $id_word)
  568. {
  569. $inserts[] = array($id_word, $row['id_msg']);
  570. }
  571. }
  572. $num_messages['done'] += $number_processed;
  573. $num_messages['todo'] -= $number_processed;
  574. $smcFunc['db_free_result']($request);
  575. $context['start'] += $forced_break ? $number_processed : $messages_per_batch;
  576. if (!empty($inserts))
  577. $smcFunc['db_insert']('ignore',
  578. '{db_prefix}log_search_words',
  579. array('id_word' => 'int', 'id_msg' => 'int'),
  580. $inserts,
  581. array('id_word', 'id_msg')
  582. );
  583. if ($num_messages['todo'] === 0)
  584. {
  585. $context['step'] = 2;
  586. $context['start'] = 0;
  587. break;
  588. }
  589. else
  590. updateSettings(array('search_custom_index_resume' => serialize(array_merge($context['index_settings'], array('resume_at' => $context['start'])))));
  591. }
  592. // Since there are still two steps to go, 90% is the maximum here.
  593. $context['percentage'] = round($num_messages['done'] / ($num_messages['done'] + $num_messages['todo']), 3) * 80;
  594. }
  595. }
  596. // Step 2: removing the words that occur too often and are of no use.
  597. elseif ($context['step'] === 2)
  598. {
  599. if ($context['index_settings']['bytes_per_word'] < 4)
  600. $context['step'] = 3;
  601. else
  602. {
  603. $stop_words = $context['start'] === 0 || empty($modSettings['search_stopwords']) ? array() : explode(',', $modSettings['search_stopwords']);
  604. $stop = time() + 3;
  605. $context['sub_template'] = 'create_index_progress';
  606. $max_messages = ceil(60 * $modSettings['totalMessages'] / 100);
  607. while (time() < $stop)
  608. {
  609. $request = $smcFunc['db_query']('', '
  610. SELECT id_word, COUNT(id_word) AS num_words
  611. FROM {db_prefix}log_search_words
  612. WHERE id_word BETWEEN {int:starting_id} AND {int:ending_id}
  613. GROUP BY id_word
  614. HAVING COUNT(id_word) > {int:minimum_messages}',
  615. array(
  616. 'starting_id' => $context['start'],
  617. 'ending_id' => $context['start'] + $index_properties[$context['index_settings']['bytes_per_word']]['step_size'] - 1,
  618. 'minimum_messages' => $max_messages,
  619. )
  620. );
  621. while ($row = $smcFunc['db_fetch_assoc']($request))
  622. $stop_words[] = $row['id_word'];
  623. $smcFunc['db_free_result']($request);
  624. updateSettings(array('search_stopwords' => implode(',', $stop_words)));
  625. if (!empty($stop_words))
  626. $smcFunc['db_query']('', '
  627. DELETE FROM {db_prefix}log_search_words
  628. WHERE id_word in ({array_int:stop_words})',
  629. array(
  630. 'stop_words' => $stop_words,
  631. )
  632. );
  633. $context['start'] += $index_properties[$context['index_settings']['bytes_per_word']]['step_size'];
  634. if ($context['start'] > $index_properties[$context['index_settings']['bytes_per_word']]['max_size'])
  635. {
  636. $context['step'] = 3;
  637. break;
  638. }
  639. }
  640. $context['percentage'] = 80 + round($context['start'] / $index_properties[$context['index_settings']['bytes_per_word']]['max_size'], 3) * 20;
  641. }
  642. }
  643. // Step 3: remove words not distinctive enough.
  644. if ($context['step'] === 3)
  645. {
  646. $context['sub_template'] = 'create_index_done';
  647. updateSettings(array('search_index' => 'custom', 'search_custom_index_config' => serialize($context['index_settings'])));
  648. $smcFunc['db_query']('', '
  649. DELETE FROM {db_prefix}settings
  650. WHERE variable = {string:search_custom_index_resume}',
  651. array(
  652. 'search_custom_index_resume' => 'search_custom_index_resume',
  653. )
  654. );
  655. }
  656. }
  657. /**
  658. * Get the installed Search API implementations.
  659. * This function checks for patterns in comments on top of the Search-API files!
  660. * In addition to filenames pattern.
  661. * It loads the search API classes if identified.
  662. * This function is used by EditSearchMethod to list all installed API implementations.
  663. */
  664. function loadSearchAPIs()
  665. {
  666. global $sourcedir, $txt;
  667. $apis = array();
  668. if ($dh = opendir($sourcedir))
  669. {
  670. while (($file = readdir($dh)) !== false)
  671. {
  672. if (is_file($sourcedir . '/' . $file) && preg_match('~SearchAPI-([A-Za-z\d_]+)\.php~', $file, $matches))
  673. {
  674. // Check this is definitely a valid API!
  675. $fp = fopen($sourcedir . '/' . $file, 'rb');
  676. $header = fread($fp, 4096);
  677. fclose($fp);
  678. if (strpos($header, '* SearchAPI-' . $matches[1] . '.php') !== false)
  679. {
  680. loadClassFile($file);
  681. $index_name = strtolower($matches[1]);
  682. $search_class_name = $index_name . '_search';
  683. $searchAPI = new $search_class_name();
  684. // No Support? NEXT!
  685. if (!$searchAPI->is_supported)
  686. continue;
  687. $apis[$index_name] = array(
  688. 'filename' => $file,
  689. 'setting_index' => $index_name,
  690. 'has_template' => in_array($index_name, array('custom', 'fulltext', 'standard')),
  691. 'label' => $index_name && isset($txt['search_index_' . $index_name]) ? $txt['search_index_' . $index_name] : '',
  692. 'desc' => $index_name && isset($txt['search_index_' . $index_name . '_desc']) ? $txt['search_index_' . $index_name . '_desc'] : '',
  693. );
  694. }
  695. }
  696. }
  697. }
  698. closedir($dh);
  699. return $apis;
  700. }
  701. ?>