ManageSearch.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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', 'get');
  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', 'get');
  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', 'get');
  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-msmpost');
  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-msmpost');
  437. createToken('admin-msm', 'get');
  438. }
  439. /**
  440. * Create a custom search index for the messages table.
  441. * Called by ?action=admin;area=managesearch;sa=createmsgindex.
  442. * Linked from the EditSearchMethod screen.
  443. * Requires the admin_forum permission.
  444. * Depending on the size of the message table, the process is divided in steps.
  445. *
  446. * @uses ManageSearch template, 'create_index', 'create_index_progress', and 'create_index_done'
  447. * sub-templates.
  448. */
  449. function CreateMessageIndex()
  450. {
  451. global $modSettings, $context, $smcFunc, $db_prefix, $txt;
  452. // Scotty, we need more time...
  453. @set_time_limit(600);
  454. if (function_exists('apache_reset_timeout'))
  455. @apache_reset_timeout();
  456. $context[$context['admin_menu_name']]['current_subsection'] = 'method';
  457. $context['page_title'] = $txt['search_index_custom'];
  458. $messages_per_batch = 50;
  459. $index_properties = array(
  460. 2 => array(
  461. 'column_definition' => 'small',
  462. 'step_size' => 1000000,
  463. ),
  464. 4 => array(
  465. 'column_definition' => 'medium',
  466. 'step_size' => 1000000,
  467. 'max_size' => 16777215,
  468. ),
  469. 5 => array(
  470. 'column_definition' => 'large',
  471. 'step_size' => 100000000,
  472. 'max_size' => 2000000000,
  473. ),
  474. );
  475. if (isset($_REQUEST['resume']) && !empty($modSettings['search_custom_index_resume']))
  476. {
  477. $context['index_settings'] = unserialize($modSettings['search_custom_index_resume']);
  478. $context['start'] = (int) $context['index_settings']['resume_at'];
  479. unset($context['index_settings']['resume_at']);
  480. $context['step'] = 1;
  481. }
  482. else
  483. {
  484. $context['index_settings'] = array(
  485. 'bytes_per_word' => isset($_REQUEST['bytes_per_word']) && isset($index_properties[$_REQUEST['bytes_per_word']]) ? (int) $_REQUEST['bytes_per_word'] : 2,
  486. );
  487. $context['start'] = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;
  488. $context['step'] = isset($_REQUEST['step']) ? (int) $_REQUEST['step'] : 0;
  489. // admin timeouts are painful when building these long indexes
  490. if ($_SESSION['admin_time'] + 3300 < time() && $context['step'] >= 1)
  491. $_SESSION['admin_time'] = time();
  492. }
  493. if ($context['step'] !== 0)
  494. checkSession('request');
  495. // Step 0: let the user determine how they like their index.
  496. if ($context['step'] === 0)
  497. {
  498. $context['sub_template'] = 'create_index';
  499. }
  500. // Step 1: insert all the words.
  501. if ($context['step'] === 1)
  502. {
  503. $context['sub_template'] = 'create_index_progress';
  504. if ($context['start'] === 0)
  505. {
  506. db_extend();
  507. $tables = $smcFunc['db_list_tables'](false, $db_prefix . 'log_search_words');
  508. if (!empty($tables))
  509. {
  510. $smcFunc['db_search_query']('drop_words_table', '
  511. DROP TABLE {db_prefix}log_search_words',
  512. array(
  513. )
  514. );
  515. }
  516. $smcFunc['db_create_word_search']($index_properties[$context['index_settings']['bytes_per_word']]['column_definition']);
  517. // Temporarily switch back to not using a search index.
  518. if (!empty($modSettings['search_index']) && $modSettings['search_index'] == 'custom')
  519. updateSettings(array('search_index' => ''));
  520. // Don't let simultanious processes be updating the search index.
  521. if (!empty($modSettings['search_custom_index_config']))
  522. updateSettings(array('search_custom_index_config' => ''));
  523. }
  524. $num_messages = array(
  525. 'done' => 0,
  526. 'todo' => 0,
  527. );
  528. $request = $smcFunc['db_query']('', '
  529. SELECT id_msg >= {int:starting_id} AS todo, COUNT(*) AS num_messages
  530. FROM {db_prefix}messages
  531. GROUP BY todo',
  532. array(
  533. 'starting_id' => $context['start'],
  534. )
  535. );
  536. while ($row = $smcFunc['db_fetch_assoc']($request))
  537. $num_messages[empty($row['todo']) ? 'done' : 'todo'] = $row['num_messages'];
  538. if (empty($num_messages['todo']))
  539. {
  540. $context['step'] = 2;
  541. $context['percentage'] = 80;
  542. $context['start'] = 0;
  543. }
  544. else
  545. {
  546. // Number of seconds before the next step.
  547. $stop = time() + 3;
  548. while (time() < $stop)
  549. {
  550. $inserts = array();
  551. $request = $smcFunc['db_query']('', '
  552. SELECT id_msg, body
  553. FROM {db_prefix}messages
  554. WHERE id_msg BETWEEN {int:starting_id} AND {int:ending_id}
  555. LIMIT {int:limit}',
  556. array(
  557. 'starting_id' => $context['start'],
  558. 'ending_id' => $context['start'] + $messages_per_batch - 1,
  559. 'limit' => $messages_per_batch,
  560. )
  561. );
  562. $forced_break = false;
  563. $number_processed = 0;
  564. while ($row = $smcFunc['db_fetch_assoc']($request))
  565. {
  566. // In theory it's possible for one of these to take friggin ages so add more timeout protection.
  567. if ($stop < time())
  568. {
  569. $forced_break = true;
  570. break;
  571. }
  572. $number_processed++;
  573. foreach (text2words($row['body'], $context['index_settings']['bytes_per_word'], true) as $id_word)
  574. {
  575. $inserts[] = array($id_word, $row['id_msg']);
  576. }
  577. }
  578. $num_messages['done'] += $number_processed;
  579. $num_messages['todo'] -= $number_processed;
  580. $smcFunc['db_free_result']($request);
  581. $context['start'] += $forced_break ? $number_processed : $messages_per_batch;
  582. if (!empty($inserts))
  583. $smcFunc['db_insert']('ignore',
  584. '{db_prefix}log_search_words',
  585. array('id_word' => 'int', 'id_msg' => 'int'),
  586. $inserts,
  587. array('id_word', 'id_msg')
  588. );
  589. if ($num_messages['todo'] === 0)
  590. {
  591. $context['step'] = 2;
  592. $context['start'] = 0;
  593. break;
  594. }
  595. else
  596. updateSettings(array('search_custom_index_resume' => serialize(array_merge($context['index_settings'], array('resume_at' => $context['start'])))));
  597. }
  598. // Since there are still two steps to go, 80% is the maximum here.
  599. $context['percentage'] = round($num_messages['done'] / ($num_messages['done'] + $num_messages['todo']), 3) * 80;
  600. }
  601. }
  602. // Step 2: removing the words that occur too often and are of no use.
  603. elseif ($context['step'] === 2)
  604. {
  605. if ($context['index_settings']['bytes_per_word'] < 4)
  606. $context['step'] = 3;
  607. else
  608. {
  609. $stop_words = $context['start'] === 0 || empty($modSettings['search_stopwords']) ? array() : explode(',', $modSettings['search_stopwords']);
  610. $stop = time() + 3;
  611. $context['sub_template'] = 'create_index_progress';
  612. $max_messages = ceil(60 * $modSettings['totalMessages'] / 100);
  613. while (time() < $stop)
  614. {
  615. $request = $smcFunc['db_query']('', '
  616. SELECT id_word, COUNT(id_word) AS num_words
  617. FROM {db_prefix}log_search_words
  618. WHERE id_word BETWEEN {int:starting_id} AND {int:ending_id}
  619. GROUP BY id_word
  620. HAVING COUNT(id_word) > {int:minimum_messages}',
  621. array(
  622. 'starting_id' => $context['start'],
  623. 'ending_id' => $context['start'] + $index_properties[$context['index_settings']['bytes_per_word']]['step_size'] - 1,
  624. 'minimum_messages' => $max_messages,
  625. )
  626. );
  627. while ($row = $smcFunc['db_fetch_assoc']($request))
  628. $stop_words[] = $row['id_word'];
  629. $smcFunc['db_free_result']($request);
  630. updateSettings(array('search_stopwords' => implode(',', $stop_words)));
  631. if (!empty($stop_words))
  632. $smcFunc['db_query']('', '
  633. DELETE FROM {db_prefix}log_search_words
  634. WHERE id_word in ({array_int:stop_words})',
  635. array(
  636. 'stop_words' => $stop_words,
  637. )
  638. );
  639. $context['start'] += $index_properties[$context['index_settings']['bytes_per_word']]['step_size'];
  640. if ($context['start'] > $index_properties[$context['index_settings']['bytes_per_word']]['max_size'])
  641. {
  642. $context['step'] = 3;
  643. break;
  644. }
  645. }
  646. $context['percentage'] = 80 + round($context['start'] / $index_properties[$context['index_settings']['bytes_per_word']]['max_size'], 3) * 20;
  647. }
  648. }
  649. // Step 3: remove words not distinctive enough.
  650. if ($context['step'] === 3)
  651. {
  652. $context['sub_template'] = 'create_index_done';
  653. updateSettings(array('search_index' => 'custom', 'search_custom_index_config' => serialize($context['index_settings'])));
  654. $smcFunc['db_query']('', '
  655. DELETE FROM {db_prefix}settings
  656. WHERE variable = {string:search_custom_index_resume}',
  657. array(
  658. 'search_custom_index_resume' => 'search_custom_index_resume',
  659. )
  660. );
  661. }
  662. }
  663. /**
  664. * Get the installed Search API implementations.
  665. * This function checks for patterns in comments on top of the Search-API files!
  666. * In addition to filenames pattern.
  667. * It loads the search API classes if identified.
  668. * This function is used by EditSearchMethod to list all installed API implementations.
  669. */
  670. function loadSearchAPIs()
  671. {
  672. global $sourcedir, $txt;
  673. $apis = array();
  674. if ($dh = opendir($sourcedir))
  675. {
  676. while (($file = readdir($dh)) !== false)
  677. {
  678. if (is_file($sourcedir . '/' . $file) && preg_match('~^SearchAPI-([A-Za-z\d_]+)\.php$~', $file, $matches))
  679. {
  680. // Check this is definitely a valid API!
  681. $fp = fopen($sourcedir . '/' . $file, 'rb');
  682. $header = fread($fp, 4096);
  683. fclose($fp);
  684. if (strpos($header, '* SearchAPI-' . $matches[1] . '.php') !== false)
  685. {
  686. require_once($sourcedir . '/' . $file);
  687. $index_name = strtolower($matches[1]);
  688. $search_class_name = $index_name . '_search';
  689. $searchAPI = new $search_class_name();
  690. // No Support? NEXT!
  691. if (!$searchAPI->is_supported)
  692. continue;
  693. $apis[$index_name] = array(
  694. 'filename' => $file,
  695. 'setting_index' => $index_name,
  696. 'has_template' => in_array($index_name, array('custom', 'fulltext', 'standard')),
  697. 'label' => $index_name && isset($txt['search_index_' . $index_name]) ? $txt['search_index_' . $index_name] : '',
  698. 'desc' => $index_name && isset($txt['search_index_' . $index_name . '_desc']) ? $txt['search_index_' . $index_name . '_desc'] : '',
  699. );
  700. }
  701. }
  702. }
  703. }
  704. closedir($dh);
  705. return $apis;
  706. }
  707. ?>