PageRenderTime 52ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/Sources/ManageSearch.php

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