PageRenderTime 42ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

/Sources/ManageMaintenance.php

https://github.com/smf-portal/SMF2.1
PHP | 2195 lines | 1588 code | 287 blank | 320 comment | 216 complexity | b81932c4bcacf607ae8149b08e3627c9 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Forum maintenance. Important stuff.
  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 dispatcher, the maintenance access point.
  18. * This, as usual, checks permissions, loads language files, and forwards to the actual workers.
  19. */
  20. function ManageMaintenance()
  21. {
  22. global $txt, $modSettings, $scripturl, $context, $options;
  23. // You absolutely must be an admin by here!
  24. isAllowedTo('admin_forum');
  25. // Need something to talk about?
  26. loadLanguage('ManageMaintenance');
  27. loadTemplate('ManageMaintenance');
  28. // This uses admin tabs - as it should!
  29. $context[$context['admin_menu_name']]['tab_data'] = array(
  30. 'title' => $txt['maintain_title'],
  31. 'description' => $txt['maintain_info'],
  32. 'tabs' => array(
  33. 'routine' => array(),
  34. 'database' => array(),
  35. 'members' => array(),
  36. 'topics' => array(),
  37. ),
  38. );
  39. // So many things you can do - but frankly I won't let you - just these!
  40. $subActions = array(
  41. 'routine' => array(
  42. 'function' => 'MaintainRoutine',
  43. 'template' => 'maintain_routine',
  44. 'activities' => array(
  45. 'version' => 'VersionDetail',
  46. 'repair' => 'MaintainFindFixErrors',
  47. 'recount' => 'AdminBoardRecount',
  48. 'logs' => 'MaintainEmptyUnimportantLogs',
  49. 'cleancache' => 'MaintainCleanCache',
  50. ),
  51. ),
  52. 'database' => array(
  53. 'function' => 'MaintainDatabase',
  54. 'template' => 'maintain_database',
  55. 'activities' => array(
  56. 'optimize' => 'OptimizeTables',
  57. 'backup' => 'MaintainDownloadBackup',
  58. 'convertentities' => 'ConvertEntities',
  59. 'convertutf8' => 'ConvertUtf8',
  60. 'convertmsgbody' => 'ConvertMsgBody',
  61. ),
  62. ),
  63. 'members' => array(
  64. 'function' => 'MaintainMembers',
  65. 'template' => 'maintain_members',
  66. 'activities' => array(
  67. 'reattribute' => 'MaintainReattributePosts',
  68. 'purgeinactive' => 'MaintainPurgeInactiveMembers',
  69. 'recountposts' => 'MaintainRecountPosts',
  70. ),
  71. ),
  72. 'topics' => array(
  73. 'function' => 'MaintainTopics',
  74. 'template' => 'maintain_topics',
  75. 'activities' => array(
  76. 'massmove' => 'MaintainMassMoveTopics',
  77. 'pruneold' => 'MaintainRemoveOldPosts',
  78. 'olddrafts' => 'MaintainRemoveOldDrafts',
  79. ),
  80. ),
  81. 'destroy' => array(
  82. 'function' => 'Destroy',
  83. 'activities' => array(),
  84. ),
  85. );
  86. call_integration_hook('integrate_manage_maintenance', array($subActions));
  87. // Yep, sub-action time!
  88. if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
  89. $subAction = $_REQUEST['sa'];
  90. else
  91. $subAction = 'routine';
  92. // Doing something special?
  93. if (isset($_REQUEST['activity']) && isset($subActions[$subAction]['activities'][$_REQUEST['activity']]))
  94. $activity = $_REQUEST['activity'];
  95. // Set a few things.
  96. $context['page_title'] = $txt['maintain_title'];
  97. $context['sub_action'] = $subAction;
  98. $context['sub_template'] = !empty($subActions[$subAction]['template']) ? $subActions[$subAction]['template'] : '';
  99. // Finally fall through to what we are doing.
  100. $subActions[$subAction]['function']();
  101. // Any special activity?
  102. if (isset($activity))
  103. $subActions[$subAction]['activities'][$activity]();
  104. //converted to UTF-8? show a small maintenance info
  105. if (isset($_GET['done']) && $_GET['done'] == 'convertutf8')
  106. $context['maintenance_finished'] = $txt['utf8_title'];
  107. // Create a maintenance token. Kinda hard to do it any other way.
  108. createToken('admin-maint');
  109. }
  110. /**
  111. * Supporting function for the database maintenance area.
  112. */
  113. function MaintainDatabase()
  114. {
  115. global $context, $db_type, $db_character_set, $modSettings, $smcFunc, $txt, $maintenance;
  116. // Show some conversion options?
  117. $context['convert_utf8'] = $db_type == 'mysql' && (!isset($db_character_set) || $db_character_set !== 'utf8' || empty($modSettings['global_character_set']) || $modSettings['global_character_set'] !== 'UTF-8') && version_compare('4.1.2', preg_replace('~\-.+?$~', '', $smcFunc['db_server_info']()), '<=');
  118. $context['convert_entities'] = $db_type == 'mysql' && isset($db_character_set, $modSettings['global_character_set']) && $db_character_set === 'utf8' && $modSettings['global_character_set'] === 'UTF-8';
  119. if ($db_type == 'mysql')
  120. {
  121. db_extend('packages');
  122. $colData = $smcFunc['db_list_columns']('{db_prefix}messages', true);
  123. foreach ($colData as $column)
  124. if ($column['name'] == 'body')
  125. $body_type = $column['type'];
  126. $context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text';
  127. $context['convert_to_suggest'] = ($body_type != 'text' && !empty($modSettings['max_messageLength']) && $modSettings['max_messageLength'] < 65536);
  128. }
  129. // Check few things to give advices before make a backup
  130. // If safe mod is enable the external tool is *always* the best (and probably the only) solution
  131. $context['safe_mode_enable'] = @ini_get('safe_mode');
  132. // This is just a...guess
  133. $result = $smcFunc['db_query']('', '
  134. SELECT COUNT(*)
  135. FROM {db_prefix}messages',
  136. array()
  137. );
  138. list($messages) = $smcFunc['db_fetch_row']($result);
  139. $smcFunc['db_free_result']($result);
  140. // 256 is what we use in the backup script
  141. setMemoryLimit('256M');
  142. $memory_limit = memoryReturnBytes(ini_get('memory_limit')) / (1024 * 1024);
  143. // Zip limit is set to more or less 1/4th the size of the available memory * 1500
  144. // 1500 is an estimate of the number of messages that generates a database of 1 MB (yeah I know IT'S AN ESTIMATION!!!)
  145. // Why that? Because the only reliable zip package is the one sent out the first time,
  146. // so when the backup takes 1/5th (just to stay on the safe side) of the memory available
  147. $zip_limit = $memory_limit * 1500 / 5;
  148. // Here is more tricky: it depends on many factors, but the main idea is that
  149. // if it takes "too long" the backup is not reliable. So, I know that on my computer it take
  150. // 20 minutes to backup 2.5 GB, of course my computer is not representative, so I'll multiply by 4 the time.
  151. // I would consider "too long" 5 minutes (I know it can be a long time, but let's start with that):
  152. // 80 minutes for a 2.5 GB and a 5 minutes limit means 160 MB approx
  153. $plain_limit = 240000;
  154. // Last thing: are we able to gain time?
  155. $current_time_limit = ini_get('max_execution_time');
  156. @set_time_limit(159); //something strange just to be sure
  157. $new_time_limit = ini_get('max_execution_time');
  158. $context['use_maintenance'] = 0;
  159. // External tool if:
  160. // * safe_mode enable OR
  161. // * cannot change the execution time OR
  162. // * cannot reset timeout
  163. if ($context['safe_mode_enable'] || empty($new_time_limit) || ($current_time_limit == $new_time_limit && !function_exists('apache_reset_timeout')))
  164. $context['suggested_method'] = 'use_external_tool';
  165. elseif ($zip_limit < $plain_limit && $messages < $zip_limit)
  166. $context['suggested_method'] = 'zipped_file';
  167. elseif ($zip_limit > $plain_limit || ($zip_limit < $plain_limit && $plain_limit < $messages))
  168. {
  169. $context['suggested_method'] = 'use_external_tool';
  170. $context['use_maintenance'] = empty($maintenance) ? 2 : 0;
  171. }
  172. else
  173. {
  174. $context['use_maintenance'] = 1;
  175. $context['suggested_method'] = 'plain_text';
  176. }
  177. if (isset($_GET['done']) && $_GET['done'] == 'convertutf8')
  178. $context['maintenance_finished'] = $txt['utf8_title'];
  179. if (isset($_GET['done']) && $_GET['done'] == 'convertentities')
  180. $context['maintenance_finished'] = $txt['entity_convert_title'];
  181. }
  182. /**
  183. * Supporting function for the routine maintenance area.
  184. */
  185. function MaintainRoutine()
  186. {
  187. global $context, $txt;
  188. if (isset($_GET['done']) && $_GET['done'] == 'recount')
  189. $context['maintenance_finished'] = $txt['maintain_recount'];
  190. }
  191. /**
  192. * Supporting function for the members maintenance area.
  193. */
  194. function MaintainMembers()
  195. {
  196. global $context, $smcFunc, $txt;
  197. // Get membergroups - for deleting members and the like.
  198. $result = $smcFunc['db_query']('', '
  199. SELECT id_group, group_name
  200. FROM {db_prefix}membergroups',
  201. array(
  202. )
  203. );
  204. $context['membergroups'] = array(
  205. array(
  206. 'id' => 0,
  207. 'name' => $txt['maintain_members_ungrouped']
  208. ),
  209. );
  210. while ($row = $smcFunc['db_fetch_assoc']($result))
  211. {
  212. $context['membergroups'][] = array(
  213. 'id' => $row['id_group'],
  214. 'name' => $row['group_name']
  215. );
  216. }
  217. $smcFunc['db_free_result']($result);
  218. if (isset($_GET['done']) && $_GET['done'] == 'recountposts')
  219. $context['maintenance_finished'] = $txt['maintain_recountposts'];
  220. }
  221. /**
  222. * Supporting function for the topics maintenance area.
  223. */
  224. function MaintainTopics()
  225. {
  226. global $context, $smcFunc, $txt;
  227. // Let's load up the boards in case they are useful.
  228. $result = $smcFunc['db_query']('order_by_board_order', '
  229. SELECT b.id_board, b.name, b.child_level, c.name AS cat_name, c.id_cat
  230. FROM {db_prefix}boards AS b
  231. LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
  232. WHERE {query_see_board}
  233. AND redirect = {string:blank_redirect}',
  234. array(
  235. 'blank_redirect' => '',
  236. )
  237. );
  238. $context['categories'] = array();
  239. while ($row = $smcFunc['db_fetch_assoc']($result))
  240. {
  241. if (!isset($context['categories'][$row['id_cat']]))
  242. $context['categories'][$row['id_cat']] = array(
  243. 'name' => $row['cat_name'],
  244. 'boards' => array()
  245. );
  246. $context['categories'][$row['id_cat']]['boards'][] = array(
  247. 'id' => $row['id_board'],
  248. 'name' => $row['name'],
  249. 'child_level' => $row['child_level']
  250. );
  251. }
  252. $smcFunc['db_free_result']($result);
  253. if (isset($_GET['done']) && $_GET['done'] == 'purgeold')
  254. $context['maintenance_finished'] = $txt['maintain_old'];
  255. elseif (isset($_GET['done']) && $_GET['done'] == 'massmove')
  256. $context['maintenance_finished'] = $txt['move_topics_maintenance'];
  257. }
  258. /**
  259. * Find and fix all errors on the forum.
  260. */
  261. function MaintainFindFixErrors()
  262. {
  263. global $sourcedir;
  264. // Honestly, this should be done in the sub function.
  265. validateToken('admin-maint');
  266. require_once($sourcedir . '/RepairBoards.php');
  267. RepairBoards();
  268. }
  269. /**
  270. * Wipes the whole cache directory.
  271. * This only applies to SMF's own cache directory, though.
  272. */
  273. function MaintainCleanCache()
  274. {
  275. global $context, $txt;
  276. checkSession();
  277. validateToken('admin-maint');
  278. // Just wipe the whole cache directory!
  279. clean_cache();
  280. $context['maintenance_finished'] = $txt['maintain_cache'];
  281. }
  282. /**
  283. * Empties all uninmportant logs
  284. */
  285. function MaintainEmptyUnimportantLogs()
  286. {
  287. global $context, $smcFunc, $txt;
  288. checkSession();
  289. validateToken('admin-maint');
  290. // No one's online now.... MUHAHAHAHA :P.
  291. $smcFunc['db_query']('', '
  292. DELETE FROM {db_prefix}log_online');
  293. // Dump the banning logs.
  294. $smcFunc['db_query']('', '
  295. DELETE FROM {db_prefix}log_banned');
  296. // Start id_error back at 0 and dump the error log.
  297. $smcFunc['db_query']('truncate_table', '
  298. TRUNCATE {db_prefix}log_errors');
  299. // Clear out the spam log.
  300. $smcFunc['db_query']('', '
  301. DELETE FROM {db_prefix}log_floodcontrol');
  302. // Clear out the karma actions.
  303. $smcFunc['db_query']('', '
  304. DELETE FROM {db_prefix}log_karma');
  305. // Last but not least, the search logs!
  306. $smcFunc['db_query']('truncate_table', '
  307. TRUNCATE {db_prefix}log_search_topics');
  308. $smcFunc['db_query']('truncate_table', '
  309. TRUNCATE {db_prefix}log_search_messages');
  310. $smcFunc['db_query']('truncate_table', '
  311. TRUNCATE {db_prefix}log_search_results');
  312. updateSettings(array('search_pointer' => 0));
  313. $context['maintenance_finished'] = $txt['maintain_logs'];
  314. }
  315. /**
  316. * Oh noes! I'd document this but that would give it away
  317. */
  318. function Destroy()
  319. {
  320. global $context;
  321. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  322. <html xmlns="http://www.w3.org/1999/xhtml"', $context['right_to_left'] ? ' dir="rtl"' : '', '><head><title>', $context['forum_name_html_safe'], ' deleted!</title></head>
  323. <body style="background-color: orange; font-family: arial, sans-serif; text-align: center;">
  324. <div style="margin-top: 8%; font-size: 400%; color: black;">Oh my, you killed ', $context['forum_name_html_safe'], '!</div>
  325. <div style="margin-top: 7%; font-size: 500%; color: red;"><strong>You lazy bum!</strong></div>
  326. </body></html>';
  327. obExit(false);
  328. }
  329. /**
  330. * Convert both data and database tables to UTF-8 character set.
  331. * It requires the admin_forum permission.
  332. * This only works if UTF-8 is not the global character set.
  333. * It supports all character sets used by SMF's language files.
  334. * It redirects to ?action=admin;area=maintain after finishing.
  335. * This action is linked from the maintenance screen (if it's applicable).
  336. * Accessed by ?action=admin;area=maintain;sa=database;activity=convertutf8.
  337. *
  338. * @uses the convert_utf8 sub template of the Admin template.
  339. */
  340. function ConvertUtf8()
  341. {
  342. global $scripturl, $context, $txt, $language, $db_character_set;
  343. global $modSettings, $user_info, $sourcedir, $smcFunc, $db_prefix;
  344. // Show me your badge!
  345. isAllowedTo('admin_forum');
  346. // The character sets used in SMF's language files with their db equivalent.
  347. $charsets = array(
  348. // Chinese-traditional.
  349. 'big5' => 'big5',
  350. // Chinese-simplified.
  351. 'gbk' => 'gbk',
  352. // West European.
  353. 'ISO-8859-1' => 'latin1',
  354. // Romanian.
  355. 'ISO-8859-2' => 'latin2',
  356. // Turkish.
  357. 'ISO-8859-9' => 'latin5',
  358. // West European with Euro sign.
  359. 'ISO-8859-15' => 'latin9',
  360. // Thai.
  361. 'tis-620' => 'tis620',
  362. // Persian, Chinese, etc.
  363. 'UTF-8' => 'utf8',
  364. // Russian.
  365. 'windows-1251' => 'cp1251',
  366. // Greek.
  367. 'windows-1253' => 'utf8',
  368. // Hebrew.
  369. 'windows-1255' => 'utf8',
  370. // Arabic.
  371. 'windows-1256' => 'cp1256',
  372. );
  373. // Get a list of character sets supported by your MySQL server.
  374. $request = $smcFunc['db_query']('', '
  375. SHOW CHARACTER SET',
  376. array(
  377. )
  378. );
  379. $db_charsets = array();
  380. while ($row = $smcFunc['db_fetch_assoc']($request))
  381. $db_charsets[] = $row['Charset'];
  382. $smcFunc['db_free_result']($request);
  383. // Character sets supported by both MySQL and SMF's language files.
  384. $charsets = array_intersect($charsets, $db_charsets);
  385. // This is for the first screen telling backups is good.
  386. if (!isset($_POST['proceed']))
  387. {
  388. validateToken('admin-maint');
  389. // Character set conversions are only supported as of MySQL 4.1.2.
  390. if (version_compare('4.1.2', preg_replace('~\-.+?$~', '', $smcFunc['db_server_info']()), '>'))
  391. fatal_lang_error('utf8_db_version_too_low');
  392. // Use the messages.body column as indicator for the database charset.
  393. $request = $smcFunc['db_query']('', '
  394. SHOW FULL COLUMNS
  395. FROM {db_prefix}messages
  396. LIKE {string:body_like}',
  397. array(
  398. 'body_like' => 'body',
  399. )
  400. );
  401. $column_info = $smcFunc['db_fetch_assoc']($request);
  402. $smcFunc['db_free_result']($request);
  403. // A collation looks like latin1_swedish. We only need the character set.
  404. list($context['database_charset']) = explode('_', $column_info['Collation']);
  405. $context['database_charset'] = in_array($context['database_charset'], $charsets) ? array_search($context['database_charset'], $charsets) : $context['database_charset'];
  406. // No need to convert to UTF-8 if it already is.
  407. if ($db_character_set === 'utf8' && !empty($modSettings['global_character_set']) && $modSettings['global_character_set'] === 'UTF-8')
  408. fatal_lang_error('utf8_already_utf8');
  409. // Detect whether a fulltext index is set.
  410. db_extend('search');
  411. if ($smcFunc['db_search_support']('fulltext'))
  412. {
  413. require_once($sourcedir . '/ManageSearch.php');
  414. detectFulltextIndex();
  415. }
  416. // Cannot do conversion if using a fulltext index
  417. if (!empty($modSettings['search_index']) && $modSettings['search_index'] == 'fulltext' || !empty($context['fulltext_index']))
  418. fatal_lang_error('utf8_cannot_convert_fulltext');
  419. // Grab the character set from the default language file.
  420. loadLanguage('index', $language, true);
  421. $context['charset_detected'] = $txt['lang_character_set'];
  422. $context['charset_about_detected'] = sprintf($txt['utf8_detected_charset'], $language, $context['charset_detected']);
  423. // Go back to your own language.
  424. loadLanguage('index', $user_info['language'], true);
  425. // Show a warning if the character set seems not to be supported.
  426. if (!isset($charsets[strtr(strtolower($context['charset_detected']), array('utf' => 'UTF', 'iso' => 'ISO'))]))
  427. {
  428. $context['charset_warning'] = sprintf($txt['utf8_charset_not_supported'], $txt['lang_character_set']);
  429. // Default to ISO-8859-1.
  430. $context['charset_detected'] = 'ISO-8859-1';
  431. }
  432. $context['charset_list'] = array_keys($charsets);
  433. $context['page_title'] = $txt['utf8_title'];
  434. $context['sub_template'] = 'convert_utf8';
  435. createToken('admin-maint');
  436. return;
  437. }
  438. // After this point we're starting the conversion. But first: session check.
  439. checkSession();
  440. validateToken('admin-maint');
  441. createToken('admin-maint');
  442. // Translation table for the character sets not native for MySQL.
  443. $translation_tables = array(
  444. 'windows-1255' => array(
  445. '0x81' => '\'\'', '0x8A' => '\'\'', '0x8C' => '\'\'',
  446. '0x8D' => '\'\'', '0x8E' => '\'\'', '0x8F' => '\'\'',
  447. '0x90' => '\'\'', '0x9A' => '\'\'', '0x9C' => '\'\'',
  448. '0x9D' => '\'\'', '0x9E' => '\'\'', '0x9F' => '\'\'',
  449. '0xCA' => '\'\'', '0xD9' => '\'\'', '0xDA' => '\'\'',
  450. '0xDB' => '\'\'', '0xDC' => '\'\'', '0xDD' => '\'\'',
  451. '0xDE' => '\'\'', '0xDF' => '\'\'', '0xFB' => '\'\'',
  452. '0xFC' => '\'\'', '0xFF' => '\'\'', '0xC2' => '0xFF',
  453. '0x80' => '0xFC', '0xE2' => '0xFB', '0xA0' => '0xC2A0',
  454. '0xA1' => '0xC2A1', '0xA2' => '0xC2A2', '0xA3' => '0xC2A3',
  455. '0xA5' => '0xC2A5', '0xA6' => '0xC2A6', '0xA7' => '0xC2A7',
  456. '0xA8' => '0xC2A8', '0xA9' => '0xC2A9', '0xAB' => '0xC2AB',
  457. '0xAC' => '0xC2AC', '0xAD' => '0xC2AD', '0xAE' => '0xC2AE',
  458. '0xAF' => '0xC2AF', '0xB0' => '0xC2B0', '0xB1' => '0xC2B1',
  459. '0xB2' => '0xC2B2', '0xB3' => '0xC2B3', '0xB4' => '0xC2B4',
  460. '0xB5' => '0xC2B5', '0xB6' => '0xC2B6', '0xB7' => '0xC2B7',
  461. '0xB8' => '0xC2B8', '0xB9' => '0xC2B9', '0xBB' => '0xC2BB',
  462. '0xBC' => '0xC2BC', '0xBD' => '0xC2BD', '0xBE' => '0xC2BE',
  463. '0xBF' => '0xC2BF', '0xD7' => '0xD7B3', '0xD1' => '0xD781',
  464. '0xD4' => '0xD7B0', '0xD5' => '0xD7B1', '0xD6' => '0xD7B2',
  465. '0xE0' => '0xD790', '0xEA' => '0xD79A', '0xEC' => '0xD79C',
  466. '0xED' => '0xD79D', '0xEE' => '0xD79E', '0xEF' => '0xD79F',
  467. '0xF0' => '0xD7A0', '0xF1' => '0xD7A1', '0xF2' => '0xD7A2',
  468. '0xF3' => '0xD7A3', '0xF5' => '0xD7A5', '0xF6' => '0xD7A6',
  469. '0xF7' => '0xD7A7', '0xF8' => '0xD7A8', '0xF9' => '0xD7A9',
  470. '0x82' => '0xE2809A', '0x84' => '0xE2809E', '0x85' => '0xE280A6',
  471. '0x86' => '0xE280A0', '0x87' => '0xE280A1', '0x89' => '0xE280B0',
  472. '0x8B' => '0xE280B9', '0x93' => '0xE2809C', '0x94' => '0xE2809D',
  473. '0x95' => '0xE280A2', '0x97' => '0xE28094', '0x99' => '0xE284A2',
  474. '0xC0' => '0xD6B0', '0xC1' => '0xD6B1', '0xC3' => '0xD6B3',
  475. '0xC4' => '0xD6B4', '0xC5' => '0xD6B5', '0xC6' => '0xD6B6',
  476. '0xC7' => '0xD6B7', '0xC8' => '0xD6B8', '0xC9' => '0xD6B9',
  477. '0xCB' => '0xD6BB', '0xCC' => '0xD6BC', '0xCD' => '0xD6BD',
  478. '0xCE' => '0xD6BE', '0xCF' => '0xD6BF', '0xD0' => '0xD780',
  479. '0xD2' => '0xD782', '0xE3' => '0xD793', '0xE4' => '0xD794',
  480. '0xE5' => '0xD795', '0xE7' => '0xD797', '0xE9' => '0xD799',
  481. '0xFD' => '0xE2808E', '0xFE' => '0xE2808F', '0x92' => '0xE28099',
  482. '0x83' => '0xC692', '0xD3' => '0xD783', '0x88' => '0xCB86',
  483. '0x98' => '0xCB9C', '0x91' => '0xE28098', '0x96' => '0xE28093',
  484. '0xBA' => '0xC3B7', '0x9B' => '0xE280BA', '0xAA' => '0xC397',
  485. '0xA4' => '0xE282AA', '0xE1' => '0xD791', '0xE6' => '0xD796',
  486. '0xE8' => '0xD798', '0xEB' => '0xD79B', '0xF4' => '0xD7A4',
  487. '0xFA' => '0xD7AA', '0xFF' => '0xD6B2', '0xFC' => '0xE282AC',
  488. '0xFB' => '0xD792',
  489. ),
  490. 'windows-1253' => array(
  491. '0x81' => '\'\'', '0x88' => '\'\'', '0x8A' => '\'\'',
  492. '0x8C' => '\'\'', '0x8D' => '\'\'', '0x8E' => '\'\'',
  493. '0x8F' => '\'\'', '0x90' => '\'\'', '0x98' => '\'\'',
  494. '0x9A' => '\'\'', '0x9C' => '\'\'', '0x9D' => '\'\'',
  495. '0x9E' => '\'\'', '0x9F' => '\'\'', '0xAA' => '\'\'',
  496. '0xD2' => '\'\'', '0xFF' => '\'\'', '0xCE' => '0xCE9E',
  497. '0xB8' => '0xCE88', '0xBA' => '0xCE8A', '0xBC' => '0xCE8C',
  498. '0xBE' => '0xCE8E', '0xBF' => '0xCE8F', '0xC0' => '0xCE90',
  499. '0xC8' => '0xCE98', '0xCA' => '0xCE9A', '0xCC' => '0xCE9C',
  500. '0xCD' => '0xCE9D', '0xCF' => '0xCE9F', '0xDA' => '0xCEAA',
  501. '0xE8' => '0xCEB8', '0xEA' => '0xCEBA', '0xEC' => '0xCEBC',
  502. '0xEE' => '0xCEBE', '0xEF' => '0xCEBF', '0xC2' => '0xFF',
  503. '0xBD' => '0xC2BD', '0xED' => '0xCEBD', '0xB2' => '0xC2B2',
  504. '0xA0' => '0xC2A0', '0xA3' => '0xC2A3', '0xA4' => '0xC2A4',
  505. '0xA5' => '0xC2A5', '0xA6' => '0xC2A6', '0xA7' => '0xC2A7',
  506. '0xA8' => '0xC2A8', '0xA9' => '0xC2A9', '0xAB' => '0xC2AB',
  507. '0xAC' => '0xC2AC', '0xAD' => '0xC2AD', '0xAE' => '0xC2AE',
  508. '0xB0' => '0xC2B0', '0xB1' => '0xC2B1', '0xB3' => '0xC2B3',
  509. '0xB5' => '0xC2B5', '0xB6' => '0xC2B6', '0xB7' => '0xC2B7',
  510. '0xBB' => '0xC2BB', '0xE2' => '0xCEB2', '0x80' => '0xD2',
  511. '0x82' => '0xE2809A', '0x84' => '0xE2809E', '0x85' => '0xE280A6',
  512. '0x86' => '0xE280A0', '0xA1' => '0xCE85', '0xA2' => '0xCE86',
  513. '0x87' => '0xE280A1', '0x89' => '0xE280B0', '0xB9' => '0xCE89',
  514. '0x8B' => '0xE280B9', '0x91' => '0xE28098', '0x99' => '0xE284A2',
  515. '0x92' => '0xE28099', '0x93' => '0xE2809C', '0x94' => '0xE2809D',
  516. '0x95' => '0xE280A2', '0x96' => '0xE28093', '0x97' => '0xE28094',
  517. '0x9B' => '0xE280BA', '0xAF' => '0xE28095', '0xB4' => '0xCE84',
  518. '0xC1' => '0xCE91', '0xC3' => '0xCE93', '0xC4' => '0xCE94',
  519. '0xC5' => '0xCE95', '0xC6' => '0xCE96', '0x83' => '0xC692',
  520. '0xC7' => '0xCE97', '0xC9' => '0xCE99', '0xCB' => '0xCE9B',
  521. '0xD0' => '0xCEA0', '0xD1' => '0xCEA1', '0xD3' => '0xCEA3',
  522. '0xD4' => '0xCEA4', '0xD5' => '0xCEA5', '0xD6' => '0xCEA6',
  523. '0xD7' => '0xCEA7', '0xD8' => '0xCEA8', '0xD9' => '0xCEA9',
  524. '0xDB' => '0xCEAB', '0xDC' => '0xCEAC', '0xDD' => '0xCEAD',
  525. '0xDE' => '0xCEAE', '0xDF' => '0xCEAF', '0xE0' => '0xCEB0',
  526. '0xE1' => '0xCEB1', '0xE3' => '0xCEB3', '0xE4' => '0xCEB4',
  527. '0xE5' => '0xCEB5', '0xE6' => '0xCEB6', '0xE7' => '0xCEB7',
  528. '0xE9' => '0xCEB9', '0xEB' => '0xCEBB', '0xF0' => '0xCF80',
  529. '0xF1' => '0xCF81', '0xF2' => '0xCF82', '0xF3' => '0xCF83',
  530. '0xF4' => '0xCF84', '0xF5' => '0xCF85', '0xF6' => '0xCF86',
  531. '0xF7' => '0xCF87', '0xF8' => '0xCF88', '0xF9' => '0xCF89',
  532. '0xFA' => '0xCF8A', '0xFB' => '0xCF8B', '0xFC' => '0xCF8C',
  533. '0xFD' => '0xCF8D', '0xFE' => '0xCF8E', '0xFF' => '0xCE92',
  534. '0xD2' => '0xE282AC',
  535. ),
  536. );
  537. // Make some preparations.
  538. if (isset($translation_tables[$_POST['src_charset']]))
  539. {
  540. $replace = '%field%';
  541. foreach ($translation_tables[$_POST['src_charset']] as $from => $to)
  542. $replace = 'REPLACE(' . $replace . ', ' . $from . ', ' . $to . ')';
  543. }
  544. // Grab a list of tables.
  545. if (preg_match('~^`(.+?)`\.(.+?)$~', $db_prefix, $match) === 1)
  546. $queryTables = $smcFunc['db_query']('', '
  547. SHOW TABLE STATUS
  548. FROM `' . strtr($match[1], array('`' => '')) . '`
  549. LIKE {string:table_name}',
  550. array(
  551. 'table_name' => str_replace('_', '\_', $match[2]) . '%',
  552. )
  553. );
  554. else
  555. $queryTables = $smcFunc['db_query']('', '
  556. SHOW TABLE STATUS
  557. LIKE {string:table_name}',
  558. array(
  559. 'table_name' => str_replace('_', '\_', $db_prefix) . '%',
  560. )
  561. );
  562. while ($table_info = $smcFunc['db_fetch_assoc']($queryTables))
  563. {
  564. // Just to make sure it doesn't time out.
  565. if (function_exists('apache_reset_timeout'))
  566. @apache_reset_timeout();
  567. $table_charsets = array();
  568. // Loop through each column.
  569. $queryColumns = $smcFunc['db_query']('', '
  570. SHOW FULL COLUMNS
  571. FROM ' . $table_info['Name'],
  572. array(
  573. )
  574. );
  575. while ($column_info = $smcFunc['db_fetch_assoc']($queryColumns))
  576. {
  577. // Only text'ish columns have a character set and need converting.
  578. if (strpos($column_info['Type'], 'text') !== false || strpos($column_info['Type'], 'char') !== false)
  579. {
  580. $collation = empty($column_info['Collation']) || $column_info['Collation'] === 'NULL' ? $table_info['Collation'] : $column_info['Collation'];
  581. if (!empty($collation) && $collation !== 'NULL')
  582. {
  583. list($charset) = explode('_', $collation);
  584. if (!isset($table_charsets[$charset]))
  585. $table_charsets[$charset] = array();
  586. $table_charsets[$charset][] = $column_info;
  587. }
  588. }
  589. }
  590. $smcFunc['db_free_result']($queryColumns);
  591. // Only change the column if the data doesn't match the current charset.
  592. if ((count($table_charsets) === 1 && key($table_charsets) !== $charsets[$_POST['src_charset']]) || count($table_charsets) > 1)
  593. {
  594. $updates_blob = '';
  595. $updates_text = '';
  596. foreach ($table_charsets as $charset => $columns)
  597. {
  598. if ($charset !== $charsets[$_POST['src_charset']])
  599. {
  600. foreach ($columns as $column)
  601. {
  602. $updates_blob .= '
  603. CHANGE COLUMN `' . $column['Field'] . '` `' . $column['Field'] . '` ' . strtr($column['Type'], array('text' => 'blob', 'char' => 'binary')) . ($column['Null'] === 'YES' ? ' NULL' : ' NOT NULL') . (strpos($column['Type'], 'char') === false ? '' : ' default \'' . $column['Default'] . '\'') . ',';
  604. $updates_text .= '
  605. CHANGE COLUMN `' . $column['Field'] . '` `' . $column['Field'] . '` ' . $column['Type'] . ' CHARACTER SET ' . $charsets[$_POST['src_charset']] . ($column['Null'] === 'YES' ? '' : ' NOT NULL') . (strpos($column['Type'], 'char') === false ? '' : ' default \'' . $column['Default'] . '\'') . ',';
  606. }
  607. }
  608. }
  609. // Change the columns to binary form.
  610. $smcFunc['db_query']('', '
  611. ALTER TABLE {raw:table_name}{raw:updates_blob}',
  612. array(
  613. 'table_name' => $table_info['Name'],
  614. 'updates_blob' => substr($updates_blob, 0, -1),
  615. )
  616. );
  617. // Convert the character set if MySQL has no native support for it.
  618. if (isset($translation_tables[$_POST['src_charset']]))
  619. {
  620. $update = '';
  621. foreach ($table_charsets as $charset => $columns)
  622. foreach ($columns as $column)
  623. $update .= '
  624. ' . $column['Field'] . ' = ' . strtr($replace, array('%field%' => $column['Field'])) . ',';
  625. $smcFunc['db_query']('', '
  626. UPDATE {raw:table_name}
  627. SET {raw:updates}',
  628. array(
  629. 'table_name' => $table_info['Name'],
  630. 'updates' => substr($update, 0, -1),
  631. )
  632. );
  633. }
  634. // Change the columns back, but with the proper character set.
  635. $smcFunc['db_query']('', '
  636. ALTER TABLE {raw:table_name}{raw:updates_text}',
  637. array(
  638. 'table_name' => $table_info['Name'],
  639. 'updates_text' => substr($updates_text, 0, -1),
  640. )
  641. );
  642. }
  643. // Now do the actual conversion (if still needed).
  644. if ($charsets[$_POST['src_charset']] !== 'utf8')
  645. $smcFunc['db_query']('', '
  646. ALTER TABLE {raw:table_name}
  647. CONVERT TO CHARACTER SET utf8',
  648. array(
  649. 'table_name' => $table_info['Name'],
  650. )
  651. );
  652. }
  653. $smcFunc['db_free_result']($queryTables);
  654. call_integration_hook('integrate_convert_utf8');
  655. // Let the settings know we have a new character set.
  656. updateSettings(array('global_character_set' => 'UTF-8', 'previousCharacterSet' => (empty($translation_tables[$_POST['src_charset']])) ? $charsets[$_POST['src_charset']] : $translation_tables[$_POST['src_charset']]));
  657. // Store it in Settings.php too because it's needed before db connection.
  658. require_once($sourcedir . '/Subs-Admin.php');
  659. updateSettingsFile(array('db_character_set' => '\'utf8\''));
  660. // The conversion might have messed up some serialized strings. Fix them!
  661. require_once($sourcedir . '/Subs-Charset.php');
  662. fix_serialized_columns();
  663. redirectexit('action=admin;area=maintain;done=convertutf8');
  664. }
  665. /**
  666. * Convert the column "body" of the table {db_prefix}messages from TEXT to MEDIUMTEXT and vice versa.
  667. * It requires the admin_forum permission.
  668. * This is needed only for MySQL.
  669. * During the convertion from MEDIUMTEXT to TEXT it check if any of the posts exceed the TEXT length and if so it aborts.
  670. * This action is linked from the maintenance screen (if it's applicable).
  671. * Accessed by ?action=admin;area=maintain;sa=database;activity=convertmsgbody.
  672. *
  673. * @uses the convert_msgbody sub template of the Admin template.
  674. */
  675. function ConvertMsgBody()
  676. {
  677. global $scripturl, $context, $txt, $language, $db_character_set, $db_type;
  678. global $modSettings, $user_info, $sourcedir, $smcFunc, $db_prefix, $time_start;
  679. // Show me your badge!
  680. isAllowedTo('admin_forum');
  681. if ($db_type != 'mysql')
  682. return;
  683. db_extend('packages');
  684. $colData = $smcFunc['db_list_columns']('{db_prefix}messages', true);
  685. foreach ($colData as $column)
  686. if ($column['name'] == 'body')
  687. $body_type = $column['type'];
  688. $context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text';
  689. if ($body_type == 'text' || ($body_type != 'text' && isset($_POST['do_conversion'])))
  690. {
  691. checkSession();
  692. validateToken('admin-maint');
  693. // Make it longer so we can do their limit.
  694. if ($body_type == 'text')
  695. $smcFunc['db_change_column']('{db_prefix}messages', 'body', array('type' => 'mediumtext'));
  696. // Shorten the column so we can have a bit (literally per record) less space occupied
  697. else
  698. $smcFunc['db_change_column']('{db_prefix}messages', 'body', array('type' => 'text'));
  699. $colData = $smcFunc['db_list_columns']('{db_prefix}messages', true);
  700. foreach ($colData as $column)
  701. if ($column['name'] == 'body')
  702. $body_type = $column['type'];
  703. $context['maintenance_finished'] = $txt[$context['convert_to'] . '_title'];
  704. $context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text';
  705. $context['convert_to_suggest'] = ($body_type != 'text' && !empty($modSettings['max_messageLength']) && $modSettings['max_messageLength'] < 65536);
  706. return;
  707. redirectexit('action=admin;area=maintain;sa=database');
  708. }
  709. elseif ($body_type != 'text' && (!isset($_POST['do_conversion']) || isset($_POST['cont'])))
  710. {
  711. checkSession();
  712. if (empty($_REQUEST['start']))
  713. validateToken('admin-maint');
  714. else
  715. validateToken('admin-convertMsg');
  716. $context['page_title'] = $txt['not_done_title'];
  717. $context['continue_post_data'] = '';
  718. $context['continue_countdown'] = 3;
  719. $context['sub_template'] = 'not_done';
  720. $increment = 500;
  721. $id_msg_exceeding = isset($_POST['id_msg_exceeding']) ? explode(',', $_POST['id_msg_exceeding']) : array();
  722. $request = $smcFunc['db_query']('', '
  723. SELECT COUNT(*) as count
  724. FROM {db_prefix}messages',
  725. array()
  726. );
  727. list($max_msgs) = $smcFunc['db_fetch_row']($request);
  728. $smcFunc['db_free_result']($request);
  729. // Try for as much time as possible.
  730. @set_time_limit(600);
  731. while ($_REQUEST['start'] < $max_msgs)
  732. {
  733. $request = $smcFunc['db_query']('', '
  734. SELECT /*!40001 SQL_NO_CACHE */ id_msg
  735. FROM {db_prefix}messages
  736. WHERE id_msg BETWEEN {int:start} AND {int:start} + {int:increment}
  737. AND LENGTH(body) > 65535',
  738. array(
  739. 'start' => $_REQUEST['start'],
  740. 'increment' => $increment - 1,
  741. )
  742. );
  743. while ($row = $smcFunc['db_fetch_assoc']($request))
  744. $id_msg_exceeding[] = $row['id_msg'];
  745. $smcFunc['db_free_result']($request);
  746. $_REQUEST['start'] += $increment;
  747. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3)
  748. {
  749. createToken('admin-convertMsg');
  750. $context['continue_post_data'] = '
  751. <input type="hidden" name="' . $context['admin-convertMsg_token_var'] . '" value="' . $context['admin-convertMsg_token'] . '" />
  752. <input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" />
  753. <input type="hidden" name="id_msg_exceeding" value="' . implode(',', $id_msg_exceeding) . '" />';
  754. $context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=convertmsgbody;start=' . $_REQUEST['start'];
  755. $context['continue_percent'] = round(100 * $_REQUEST['start'] / $max_msgs);
  756. return;
  757. }
  758. }
  759. createToken('admin-maint');
  760. $context['page_title'] = $txt[$context['convert_to'] . '_title'];
  761. $context['sub_template'] = 'convert_msgbody';
  762. if (!empty($id_msg_exceeding))
  763. {
  764. if (count($id_msg_exceeding) > 100)
  765. {
  766. $query_msg = array_slice($id_msg_exceeding, 0, 100);
  767. $context['exceeding_messages_morethan'] = sprintf($txt['exceeding_messages_morethan'], count($id_msg_exceeding));
  768. }
  769. else
  770. $query_msg = $id_msg_exceeding;
  771. $context['exceeding_messages'] = array();
  772. $request = $smcFunc['db_query']('', '
  773. SELECT id_msg, id_topic, subject
  774. FROM {db_prefix}messages
  775. WHERE id_msg IN ({array_int:messages})',
  776. array(
  777. 'messages' => $query_msg,
  778. )
  779. );
  780. while ($row = $smcFunc['db_fetch_assoc']($request))
  781. $context['exceeding_messages'][] = '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '">' . $row['subject'] . '</a>';
  782. $smcFunc['db_free_result']($request);
  783. }
  784. }
  785. }
  786. /**
  787. * Converts HTML-entities to their UTF-8 character equivalents.
  788. * This requires the admin_forum permission.
  789. * Pre-condition: UTF-8 has been set as database and global character set.
  790. *
  791. * It is divided in steps of 10 seconds.
  792. * This action is linked from the maintenance screen (if applicable).
  793. * It is accessed by ?action=admin;area=maintain;sa=database;activity=convertentities.
  794. *
  795. * @uses Admin template, convert_entities sub-template.
  796. */
  797. function ConvertEntities()
  798. {
  799. global $db_character_set, $modSettings, $context, $sourcedir, $smcFunc;
  800. isAllowedTo('admin_forum');
  801. // Check to see if UTF-8 is currently the default character set.
  802. if ($modSettings['global_character_set'] !== 'UTF-8' || !isset($db_character_set) || $db_character_set !== 'utf8')
  803. fatal_lang_error('entity_convert_only_utf8');
  804. // Some starting values.
  805. $context['table'] = empty($_REQUEST['table']) ? 0 : (int) $_REQUEST['table'];
  806. $context['start'] = empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'];
  807. $context['start_time'] = time();
  808. $context['first_step'] = !isset($_REQUEST[$context['session_var']]);
  809. $context['last_step'] = false;
  810. // The first step is just a text screen with some explanation.
  811. if ($context['first_step'])
  812. {
  813. validateToken('admin-maint');
  814. createToken('admin-maint');
  815. $context['sub_template'] = 'convert_entities';
  816. return;
  817. }
  818. // Otherwise use the generic "not done" template.
  819. $context['sub_template'] = 'not_done';
  820. $context['continue_post_data'] = '';
  821. $context['continue_countdown'] = 3;
  822. // Now we're actually going to convert...
  823. checkSession('request');
  824. validateToken('admin-maint');
  825. createToken('admin-maint');
  826. // A list of tables ready for conversion.
  827. $tables = array(
  828. 'ban_groups',
  829. 'ban_items',
  830. 'boards',
  831. 'calendar',
  832. 'calendar_holidays',
  833. 'categories',
  834. 'log_errors',
  835. 'log_search_subjects',
  836. 'membergroups',
  837. 'members',
  838. 'message_icons',
  839. 'messages',
  840. 'package_servers',
  841. 'personal_messages',
  842. 'pm_recipients',
  843. 'polls',
  844. 'poll_choices',
  845. 'smileys',
  846. 'themes',
  847. );
  848. $context['num_tables'] = count($tables);
  849. // Loop through all tables that need converting.
  850. for (; $context['table'] < $context['num_tables']; $context['table']++)
  851. {
  852. $cur_table = $tables[$context['table']];
  853. $primary_key = '';
  854. // Make sure we keep stuff unique!
  855. $primary_keys = array();
  856. if (function_exists('apache_reset_timeout'))
  857. @apache_reset_timeout();
  858. // Get a list of text columns.
  859. $columns = array();
  860. $request = $smcFunc['db_query']('', '
  861. SHOW FULL COLUMNS
  862. FROM {db_prefix}' . $cur_table,
  863. array(
  864. )
  865. );
  866. while ($column_info = $smcFunc['db_fetch_assoc']($request))
  867. if (strpos($column_info['Type'], 'text') !== false || strpos($column_info['Type'], 'char') !== false)
  868. $columns[] = strtolower($column_info['Field']);
  869. // Get the column with the (first) primary key.
  870. $request = $smcFunc['db_query']('', '
  871. SHOW KEYS
  872. FROM {db_prefix}' . $cur_table,
  873. array(
  874. )
  875. );
  876. while ($row = $smcFunc['db_fetch_assoc']($request))
  877. {
  878. if ($row['Key_name'] === 'PRIMARY')
  879. {
  880. if (empty($primary_key) || ($row['Seq_in_index'] == 1 && !in_array(strtolower($row['Column_name']), $columns)))
  881. $primary_key = $row['Column_name'];
  882. $primary_keys[] = $row['Column_name'];
  883. }
  884. }
  885. $smcFunc['db_free_result']($request);
  886. // No primary key, no glory.
  887. // Same for columns. Just to be sure we've work to do!
  888. if (empty($primary_key) || empty($columns))
  889. continue;
  890. // Get the maximum value for the primary key.
  891. $request = $smcFunc['db_query']('', '
  892. SELECT MAX(' . $primary_key . ')
  893. FROM {db_prefix}' . $cur_table,
  894. array(
  895. )
  896. );
  897. list($max_value) = $smcFunc['db_fetch_row']($request);
  898. $smcFunc['db_free_result']($request);
  899. if (empty($max_value))
  900. continue;
  901. while ($context['start'] <= $max_value)
  902. {
  903. // Retrieve a list of rows that has at least one entity to convert.
  904. $request = $smcFunc['db_query']('', '
  905. SELECT {raw:primary_keys}, {raw:columns}
  906. FROM {db_prefix}{raw:cur_table}
  907. WHERE {raw:primary_key} BETWEEN {int:start} AND {int:start} + 499
  908. AND {raw:like_compare}
  909. LIMIT 500',
  910. array(
  911. 'primary_keys' => implode(', ', $primary_keys),
  912. 'columns' => implode(', ', $columns),
  913. 'cur_table' => $cur_table,
  914. 'primary_key' => $primary_key,
  915. 'start' => $context['start'],
  916. 'like_compare' => '(' . implode(' LIKE \'%&#%\' OR ', $columns) . ' LIKE \'%&#%\')',
  917. )
  918. );
  919. while ($row = $smcFunc['db_fetch_assoc']($request))
  920. {
  921. $insertion_variables = array();
  922. $changes = array();
  923. foreach ($row as $column_name => $column_value)
  924. if ($column_name !== $primary_key && strpos($column_value, '&#') !== false)
  925. {
  926. $changes[] = $column_name . ' = {string:changes_' . $column_name . '}';
  927. $insertion_variables['changes_' . $column_name] = preg_replace_callback('~&#(\d{1,7}|x[0-9a-fA-F]{1,6});~', 'fixchar__callback', $column_value);
  928. }
  929. $where = array();
  930. foreach ($primary_keys as $key)
  931. {
  932. $where[] = $key . ' = {string:where_' . $key . '}';
  933. $insertion_variables['where_' . $key] = $row[$key];
  934. }
  935. // Update the row.
  936. if (!empty($changes))
  937. $smcFunc['db_query']('', '
  938. UPDATE {db_prefix}' . $cur_table . '
  939. SET
  940. ' . implode(',
  941. ', $changes) . '
  942. WHERE ' . implode(' AND ', $where),
  943. $insertion_variables
  944. );
  945. }
  946. $smcFunc['db_free_result']($request);
  947. $context['start'] += 500;
  948. // After ten seconds interrupt.
  949. if (time() - $context['start_time'] > 10)
  950. {
  951. // Calculate an approximation of the percentage done.
  952. $context['continue_percent'] = round(100 * ($context['table'] + ($context['start'] / $max_value)) / $context['num_tables'], 1);
  953. $context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=convertentities;table=' . $context['table'] . ';start=' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  954. return;
  955. }
  956. }
  957. $context['start'] = 0;
  958. }
  959. // Make sure all serialized strings are all right.
  960. require_once($sourcedir . '/Subs-Charset.php');
  961. fix_serialized_columns();
  962. // If we're here, we must be done.
  963. $context['continue_percent'] = 100;
  964. $context['continue_get_data'] = '?action=admin;area=maintain;sa=database;done=convertentities';
  965. $context['last_step'] = true;
  966. $context['continue_countdown'] = -1;
  967. }
  968. /**
  969. * Optimizes all tables in the database and lists how much was saved.
  970. * It requires the admin_forum permission.
  971. * It shows as the maintain_forum admin area.
  972. * It is accessed from ?action=admin;area=maintain;sa=database;activity=optimize.
  973. * It also updates the optimize scheduled task such that the tables are not automatically optimized again too soon.
  974. * @uses the rawdata sub template (built in.)
  975. */
  976. function OptimizeTables()
  977. {
  978. global $db_type, $db_name, $db_prefix, $txt, $context, $scripturl, $sourcedir, $smcFunc;
  979. isAllowedTo('admin_forum');
  980. checkSession('post');
  981. validateToken('admin-maint');
  982. ignore_user_abort(true);
  983. db_extend();
  984. // Start with no tables optimized.
  985. $opttab = 0;
  986. $context['page_title'] = $txt['database_optimize'];
  987. $context['sub_template'] = 'optimize';
  988. // Only optimize the tables related to this smf install, not all the tables in the db
  989. $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
  990. // Get a list of tables, as well as how many there are.
  991. $temp_tables = $smcFunc['db_list_tables'](false, $real_prefix . '%');
  992. $tables = array();
  993. foreach ($temp_tables as $table)
  994. $tables[] = array('table_name' => $table);
  995. // If there aren't any tables then I believe that would mean the world has exploded...
  996. $context['num_tables'] = count($tables);
  997. if ($context['num_tables'] == 0)
  998. fatal_error('You appear to be running SMF in a flat file mode... fantastic!', false);
  999. // For each table....
  1000. $context['optimized_tables'] = array();
  1001. foreach ($tables as $table)
  1002. {
  1003. // Optimize the table! We use backticks here because it might be a custom table.
  1004. $data_freed = $smcFunc['db_optimize_table']($table['table_name']);
  1005. // Optimizing one sqlite table optimizes them all.
  1006. if ($db_type == 'sqlite')
  1007. break;
  1008. if ($data_freed > 0)
  1009. $context['optimized_tables'][] = array(
  1010. 'name' => $table['table_name'],
  1011. 'data_freed' => $data_freed,
  1012. );
  1013. }
  1014. // Number of tables, etc....
  1015. $txt['database_numb_tables'] = sprintf($txt['database_numb_tables'], $context['num_tables']);
  1016. $context['num_tables_optimized'] = count($context['optimized_tables']);
  1017. // Check that we don't auto optimise again too soon!
  1018. require_once($sourcedir . '/ScheduledTasks.php');
  1019. CalculateNextTrigger('auto_optimize', true);
  1020. }
  1021. /**
  1022. * Recount many forum totals that can be recounted automatically without harm.
  1023. * it requires the admin_forum permission.
  1024. * It shows the maintain_forum admin area.
  1025. *
  1026. * Totals recounted:
  1027. * - fixes for topics with wrong num_replies.
  1028. * - updates for num_posts and num_topics of all boards.
  1029. * - recounts instant_messages but not unread_messages.
  1030. * - repairs messages pointing to boards with topics pointing to other boards.
  1031. * - updates the last message posted in boards and children.
  1032. * - updates member count, latest member, topic count, and message count.
  1033. *
  1034. * The function redirects back to ?action=admin;area=maintain when complete.
  1035. * It is accessed via ?action=admin;area=maintain;sa=database;activity=recount.
  1036. */
  1037. function AdminBoardRecount()
  1038. {
  1039. global $txt, $context, $scripturl, $modSettings, $sourcedir;
  1040. global $time_start, $smcFunc;
  1041. isAllowedTo('admin_forum');
  1042. checkSession('request');
  1043. // validate the request or the loop
  1044. if (!isset($_REQUEST['step']))
  1045. validateToken('admin-maint');
  1046. else
  1047. validateToken('admin-boardrecount');
  1048. $context['page_title'] = $txt['not_done_title'];
  1049. $context['continue_post_data'] = '';
  1050. $context['continue_countdown'] = 3;
  1051. $context['sub_template'] = 'not_done';
  1052. // Try for as much time as possible.
  1053. @set_time_limit(600);
  1054. // Step the number of topics at a time so things don't time out...
  1055. $request = $smcFunc['db_query']('', '
  1056. SELECT MAX(id_topic)
  1057. FROM {db_prefix}topics',
  1058. array(
  1059. )
  1060. );
  1061. list ($max_topics) = $smcFunc['db_fetch_row']($request);
  1062. $smcFunc['db_free_result']($request);
  1063. $increment = min(max(50, ceil($max_topics / 4)), 2000);
  1064. if (empty($_REQUEST['start']))
  1065. $_REQUEST['start'] = 0;
  1066. $total_steps = 8;
  1067. // Get each topic with a wrong reply count and fix it - let's just do some at a time, though.
  1068. if (empty($_REQUEST['step']))
  1069. {
  1070. $_REQUEST['step'] = 0;
  1071. while ($_REQUEST['start'] < $max_topics)
  1072. {
  1073. // Recount approved messages
  1074. $request = $smcFunc['db_query']('', '
  1075. SELECT /*!40001 SQL_NO_CACHE */ t.id_topic, MAX(t.num_replies) AS num_replies,
  1076. CASE WHEN COUNT(ma.id_msg) >= 1 THEN COUNT(ma.id_msg) - 1 ELSE 0 END AS real_num_replies
  1077. FROM {db_prefix}topics AS t
  1078. LEFT JOIN {db_prefix}messages AS ma ON (ma.id_topic = t.id_topic AND ma.approved = {int:is_approved})
  1079. WHERE t.id_topic > {int:start}
  1080. AND t.id_topic <= {int:max_id}
  1081. GROUP BY t.id_topic
  1082. HAVING CASE WHEN COUNT(ma.id_msg) >= 1 THEN COUNT(ma.id_msg) - 1 ELSE 0 END != MAX(t.num_replies)',
  1083. array(
  1084. 'is_approved' => 1,
  1085. 'start' => $_REQUEST['start'],
  1086. 'max_id' => $_REQUEST['start'] + $increment,
  1087. )
  1088. );
  1089. while ($row = $smcFunc['db_fetch_assoc']($request))
  1090. $smcFunc['db_query']('', '
  1091. UPDATE {db_prefix}topics
  1092. SET num_replies = {int:num_replies}
  1093. WHERE id_topic = {int:id_topic}',
  1094. array(
  1095. 'num_replies' => $row['real_num_replies'],
  1096. 'id_topic' => $row['id_topic'],
  1097. )
  1098. );
  1099. $smcFunc['db_free_result']($request);
  1100. // Recount unapproved messages
  1101. $request = $smcFunc['db_query']('', '
  1102. SELECT /*!40001 SQL_NO_CACHE */ t.id_topic, MAX(t.unapproved_posts) AS unapproved_posts,
  1103. COUNT(mu.id_msg) AS real_unapproved_posts
  1104. FROM {db_prefix}topics AS t
  1105. LEFT JOIN {db_prefix}messages AS mu ON (mu.id_topic = t.id_topic AND mu.approved = {int:not_approved})
  1106. WHERE t.id_topic > {int:start}
  1107. AND t.id_topic <= {int:max_id}
  1108. GROUP BY t.id_topic
  1109. HAVING COUNT(mu.id_msg) != MAX(t.unapproved_posts)',
  1110. array(
  1111. 'not_approved' => 0,
  1112. 'start' => $_REQUEST['start'],
  1113. 'max_id' => $_REQUEST['start'] + $increment,
  1114. )
  1115. );
  1116. while ($row = $smcFunc['db_fetch_assoc']($request))
  1117. $smcFunc['db_query']('', '
  1118. UPDATE {db_prefix}topics
  1119. SET unapproved_posts = {int:unapproved_posts}
  1120. WHERE id_topic = {int:id_topic}',
  1121. array(
  1122. 'unapproved_posts' => $row['real_unapproved_posts'],
  1123. 'id_topic' => $row['id_topic'],
  1124. )
  1125. );
  1126. $smcFunc['db_free_result']($request);
  1127. $_REQUEST['start'] += $increment;
  1128. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3)
  1129. {
  1130. createToken('admin-boardrecount');
  1131. $context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '" />';
  1132. $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=0;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1133. $context['continue_percent'] = round((100 * $_REQUEST['start'] / $max_topics) / $total_steps);
  1134. return;
  1135. }
  1136. }
  1137. $_REQUEST['start'] = 0;
  1138. }
  1139. // Update the post count of each board.
  1140. if ($_REQUEST['step'] <= 1)
  1141. {
  1142. if (empty($_REQUEST['start']))
  1143. $smcFunc['db_query']('', '
  1144. UPDATE {db_prefix}boards
  1145. SET num_posts = {int:num_posts}
  1146. WHERE redirect = {string:redirect}',
  1147. array(
  1148. 'num_posts' => 0,
  1149. 'redirect' => '',
  1150. )
  1151. );
  1152. while ($_REQUEST['start'] < $max_topics)
  1153. {
  1154. $request = $smcFunc['db_query']('', '
  1155. SELECT /*!40001 SQL_NO_CACHE */ m.id_board, COUNT(*) AS real_num_posts
  1156. FROM {db_prefix}messages AS m
  1157. WHERE m.id_topic > {int:id_topic_min}
  1158. AND m.id_topic <= {int:id_topic_max}
  1159. AND m.approved = {int:is_approved}
  1160. GROUP BY m.id_board',
  1161. array(
  1162. 'id_topic_min' => $_REQUEST['start'],
  1163. 'id_topic_max' => $_REQUEST['start'] + $increment,
  1164. 'is_approved' => 1,
  1165. )
  1166. );
  1167. while ($row = $smcFunc['db_fetch_assoc']($request))
  1168. $smcFunc['db_query']('', '
  1169. UPDATE {db_prefix}boards
  1170. SET num_posts = num_posts + {int:real_num_posts}
  1171. WHERE id_board = {int:id_board}',
  1172. array(
  1173. 'id_board' => $row['id_board'],
  1174. 'real_num_posts' => $row['real_num_posts'],
  1175. )
  1176. );
  1177. $smcFunc['db_free_result']($request);
  1178. $_REQUEST['start'] += $increment;
  1179. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3)
  1180. {
  1181. createToken('admin-boardrecount');
  1182. $context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '" />';
  1183. $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=1;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1184. $context['continue_percent'] = round((200 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
  1185. return;
  1186. }
  1187. }
  1188. $_REQUEST['start'] = 0;
  1189. }
  1190. // Update the topic count of each board.
  1191. if ($_REQUEST['step'] <= 2)
  1192. {
  1193. if (empty($_REQUEST['start']))
  1194. $smcFunc['db_query']('', '
  1195. UPDATE {db_prefix}boards
  1196. SET num_topics = {int:num_topics}',
  1197. array(
  1198. 'num_topics' => 0,
  1199. )
  1200. );
  1201. while ($_REQUEST['start'] < $max_topics)
  1202. {
  1203. $request = $smcFunc['db_query']('', '
  1204. SELECT /*!40001 SQL_NO_CACHE */ t.id_board, COUNT(*) AS real_num_topics
  1205. FROM {db_prefix}topics AS t
  1206. WHERE t.approved = {int:is_approved}
  1207. AND t.id_topic > {int:id_topic_min}
  1208. AND t.id_topic <= {int:id_topic_max}
  1209. GROUP BY t.id_board',
  1210. array(
  1211. 'is_approved' => 1,
  1212. 'id_topic_min' => $_REQUEST['start'],
  1213. 'id_topic_max' => $_REQUEST['start'] + $increment,
  1214. )
  1215. );
  1216. while ($row = $smcFunc['db_fetch_assoc']($request))
  1217. $smcFunc['db_query']('', '
  1218. UPDATE {db_prefix}boards
  1219. SET num_topics = num_topics + {int:real_num_topics}
  1220. WHERE id_board = {int:id_board}',
  1221. array(
  1222. 'id_board' => $row['id_board'],
  1223. 'real_num_topics' => $row['real_num_topics'],
  1224. )
  1225. );
  1226. $smcFunc['db_free_result']($request);
  1227. $_REQUEST['start'] += $increment;
  1228. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3)
  1229. {
  1230. createToken('admin-boardrecount');
  1231. $context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '" />';
  1232. $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=2;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1233. $context['continue_percent'] = round((300 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
  1234. return;
  1235. }
  1236. }
  1237. $_REQUEST['start'] = 0;
  1238. }
  1239. // Update the unapproved post count of each board.
  1240. if ($_REQUEST['step'] <= 3)
  1241. {
  1242. if (empty($_REQUEST['start']))
  1243. $smcFunc['db_query']('', '
  1244. UPDATE {db_prefix}boards
  1245. SET unapproved_posts

Large files files are truncated, but you can click here to view the full file