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