ManageSearch.php 24 KB

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