ManageSearch.php 24 KB

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