ManageSearch.php 24 KB

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