ManageMaintenance.php 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157
  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 2011 Simple Machines
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.1 Alpha 1
  13. */
  14. if (!defined('SMF'))
  15. die('Hacking attempt...');
  16. /**
  17. * Main 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. ),
  79. ),
  80. 'destroy' => array(
  81. 'function' => 'Destroy',
  82. 'activities' => array(),
  83. ),
  84. );
  85. call_integration_hook('integrate_manage_maintenance', array(&$subActions));
  86. // Yep, sub-action time!
  87. if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
  88. $subAction = $_REQUEST['sa'];
  89. else
  90. $subAction = 'routine';
  91. // Doing something special?
  92. if (isset($_REQUEST['activity']) && isset($subActions[$subAction]['activities'][$_REQUEST['activity']]))
  93. $activity = $_REQUEST['activity'];
  94. // Set a few things.
  95. $context['page_title'] = $txt['maintain_title'];
  96. $context['sub_action'] = $subAction;
  97. $context['sub_template'] = !empty($subActions[$subAction]['template']) ? $subActions[$subAction]['template'] : '';
  98. // Finally fall through to what we are doing.
  99. $subActions[$subAction]['function']();
  100. // Any special activity?
  101. if (isset($activity))
  102. $subActions[$subAction]['activities'][$activity]();
  103. //converted to UTF-8? show a small maintenance info
  104. if (isset($_GET['done']) && $_GET['done'] == 'convertutf8')
  105. $context['maintenance_finished'] = $txt['utf8_title'];
  106. // Create a maintenance token. Kinda hard to do it any other way.
  107. createToken('admin-maint');
  108. }
  109. /**
  110. * Supporting function for the database maintenance area.
  111. */
  112. function MaintainDatabase()
  113. {
  114. global $context, $db_type, $db_character_set, $modSettings, $smcFunc, $txt, $maintenance;
  115. // Show some conversion options?
  116. $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']()), '<=');
  117. $context['convert_entities'] = $db_type == 'mysql' && isset($db_character_set, $modSettings['global_character_set']) && $db_character_set === 'utf8' && $modSettings['global_character_set'] === 'UTF-8';
  118. if ($db_type == 'mysql')
  119. {
  120. db_extend('packages');
  121. $colData = $smcFunc['db_list_columns']('{db_prefix}messages', true);
  122. foreach ($colData as $column)
  123. if ($column['name'] == 'body')
  124. $body_type = $column['type'];
  125. $context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text';
  126. $context['convert_to_suggest'] = ($body_type != 'text' && !empty($modSettings['max_messageLength']) && $modSettings['max_messageLength'] < 65536);
  127. }
  128. // Check few things to give advices before make a backup
  129. // If safe mod is enable the external tool is *always* the best (and probably the only) solution
  130. $context['safe_mode_enable'] = @ini_get('safe_mode');
  131. // This is just a...guess
  132. $result = $smcFunc['db_query']('', '
  133. SELECT COUNT(*)
  134. FROM {db_prefix}messages',
  135. array()
  136. );
  137. list($messages) = $smcFunc['db_fetch_row']($result);
  138. $smcFunc['db_free_result']($result);
  139. // 256 is what we use in the backup script
  140. setMemoryLimit('256M');
  141. $memory_limit = memoryReturnBytes(ini_get('memory_limit')) / (1024 * 1024);
  142. // Zip limit is set to more or less 1/4th the size of the available memory * 1500
  143. // 1500 is an estimate of the number of messages that generates a database of 1 MB (yeah I know IT'S AN ESTIMATION!!!)
  144. // Why that? Because the only reliable zip package is the one sent out the first time,
  145. // so when the backup takes 1/5th (just to stay on the safe side) of the memory available
  146. $zip_limit = $memory_limit * 1500 / 5;
  147. // Here is more tricky: it depends on many factors, but the main idea is that
  148. // if it takes "too long" the backup is not reliable. So, I know that on my computer it take
  149. // 20 minutes to backup 2.5 GB, of course my computer is not representative, so I'll multiply by 4 the time.
  150. // I would consider "too long" 5 minutes (I know it can be a long time, but let's start with that):
  151. // 80 minutes for a 2.5 GB and a 5 minutes limit means 160 MB approx
  152. $plain_limit = 240000;
  153. // Last thing: are we able to gain time?
  154. $current_time_limit = ini_get('max_execution_time');
  155. @set_time_limit(159); //something strange just to be sure
  156. $new_time_limit = ini_get('max_execution_time');
  157. $context['use_maintenance'] = 0;
  158. // External tool if:
  159. // * safe_mode enable OR
  160. // * cannot change the execution time OR
  161. // * cannot reset timeout
  162. if ($context['safe_mode_enable'] || empty($new_time_limit) || ($current_time_limit == $new_time_limit && !function_exists('apache_reset_timeout')))
  163. $context['suggested_method'] = 'use_external_tool';
  164. elseif ($zip_limit < $plain_limit && $messages < $zip_limit)
  165. $context['suggested_method'] = 'zipped_file';
  166. elseif ($zip_limit > $plain_limit || ($zip_limit < $plain_limit && $plain_limit < $messages))
  167. {
  168. $context['suggested_method'] = 'use_external_tool';
  169. $context['use_maintenance'] = empty($maintenance) ? 2 : 0;
  170. }
  171. else
  172. {
  173. $context['use_maintenance'] = 1;
  174. $context['suggested_method'] = 'plain_text';
  175. }
  176. if (isset($_GET['done']) && $_GET['done'] == 'convertutf8')
  177. $context['maintenance_finished'] = $txt['utf8_title'];
  178. if (isset($_GET['done']) && $_GET['done'] == 'convertentities')
  179. $context['maintenance_finished'] = $txt['entity_convert_title'];
  180. }
  181. /**
  182. * Supporting function for the routine maintenance area.
  183. */
  184. function MaintainRoutine()
  185. {
  186. global $context, $txt;
  187. if (isset($_GET['done']) && $_GET['done'] == 'recount')
  188. $context['maintenance_finished'] = $txt['maintain_recount'];
  189. }
  190. /**
  191. * Supporting function for the members maintenance area.
  192. */
  193. function MaintainMembers()
  194. {
  195. global $context, $smcFunc, $txt;
  196. // Get membergroups - for deleting members and the like.
  197. $result = $smcFunc['db_query']('', '
  198. SELECT id_group, group_name
  199. FROM {db_prefix}membergroups',
  200. array(
  201. )
  202. );
  203. $context['membergroups'] = array(
  204. array(
  205. 'id' => 0,
  206. 'name' => $txt['maintain_members_ungrouped']
  207. ),
  208. );
  209. while ($row = $smcFunc['db_fetch_assoc']($result))
  210. {
  211. $context['membergroups'][] = array(
  212. 'id' => $row['id_group'],
  213. 'name' => $row['group_name']
  214. );
  215. }
  216. $smcFunc['db_free_result']($result);
  217. if (isset($_GET['done']) && $_GET['done'] == 'recountposts')
  218. $context['maintenance_finished'] = $txt['maintain_recountposts'];
  219. }
  220. /**
  221. * Supporting function for the topics maintenance area.
  222. */
  223. function MaintainTopics()
  224. {
  225. global $context, $smcFunc, $txt;
  226. // Let's load up the boards in case they are useful.
  227. $result = $smcFunc['db_query']('order_by_board_order', '
  228. SELECT b.id_board, b.name, b.child_level, c.name AS cat_name, c.id_cat
  229. FROM {db_prefix}boards AS b
  230. LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
  231. WHERE {query_see_board}
  232. AND redirect = {string:blank_redirect}',
  233. array(
  234. 'blank_redirect' => '',
  235. )
  236. );
  237. $context['categories'] = array();
  238. while ($row = $smcFunc['db_fetch_assoc']($result))
  239. {
  240. if (!isset($context['categories'][$row['id_cat']]))
  241. $context['categories'][$row['id_cat']] = array(
  242. 'name' => $row['cat_name'],
  243. 'boards' => array()
  244. );
  245. $context['categories'][$row['id_cat']]['boards'][] = array(
  246. 'id' => $row['id_board'],
  247. 'name' => $row['name'],
  248. 'child_level' => $row['child_level']
  249. );
  250. }
  251. $smcFunc['db_free_result']($result);
  252. if (isset($_GET['done']) && $_GET['done'] == 'purgeold')
  253. $context['maintenance_finished'] = $txt['maintain_old'];
  254. elseif (isset($_GET['done']) && $_GET['done'] == 'massmove')
  255. $context['maintenance_finished'] = $txt['move_topics_maintenance'];
  256. }
  257. /**
  258. * Find and fix all errors on the forum.
  259. */
  260. function MaintainFindFixErrors()
  261. {
  262. global $sourcedir;
  263. // Honestly, this should be done in the sub function.
  264. validateToken('admin-maint');
  265. require_once($sourcedir . '/RepairBoards.php');
  266. RepairBoards();
  267. }
  268. /**
  269. * Wipes the whole cache directory.
  270. * This only applies to SMF's own cache directory, though.
  271. */
  272. function MaintainCleanCache()
  273. {
  274. global $context, $txt;
  275. checkSession();
  276. validateToken('admin-maint');
  277. // Just wipe the whole cache directory!
  278. clean_cache();
  279. $context['maintenance_finished'] = $txt['maintain_cache'];
  280. }
  281. /**
  282. * Empties all uninmportant logs
  283. */
  284. function MaintainEmptyUnimportantLogs()
  285. {
  286. global $context, $smcFunc, $txt;
  287. checkSession();
  288. validateToken('admin-maint');
  289. // No one's online now.... MUHAHAHAHA :P.
  290. $smcFunc['db_query']('', '
  291. DELETE FROM {db_prefix}log_online');
  292. // Dump the banning logs.
  293. $smcFunc['db_query']('', '
  294. DELETE FROM {db_prefix}log_banned');
  295. // Start id_error back at 0 and dump the error log.
  296. $smcFunc['db_query']('truncate_table', '
  297. TRUNCATE {db_prefix}log_errors');
  298. // Clear out the spam log.
  299. $smcFunc['db_query']('', '
  300. DELETE FROM {db_prefix}log_floodcontrol');
  301. // Clear out the karma actions.
  302. $smcFunc['db_query']('', '
  303. DELETE FROM {db_prefix}log_karma');
  304. // Last but not least, the search logs!
  305. $smcFunc['db_query']('truncate_table', '
  306. TRUNCATE {db_prefix}log_search_topics');
  307. $smcFunc['db_query']('truncate_table', '
  308. TRUNCATE {db_prefix}log_search_messages');
  309. $smcFunc['db_query']('truncate_table', '
  310. TRUNCATE {db_prefix}log_search_results');
  311. updateSettings(array('search_pointer' => 0));
  312. $context['maintenance_finished'] = $txt['maintain_logs'];
  313. }
  314. // Oh noes!
  315. function Destroy()
  316. {
  317. global $context;
  318. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  319. <html xmlns="http://www.w3.org/1999/xhtml"', $context['right_to_left'] ? ' dir="rtl"' : '', '><head><title>', $context['forum_name_html_safe'], ' deleted!</title></head>
  320. <body style="background-color: orange; font-family: arial, sans-serif; text-align: center;">
  321. <div style="margin-top: 8%; font-size: 400%; color: black;">Oh my, you killed ', $context['forum_name_html_safe'], '!</div>
  322. <div style="margin-top: 7%; font-size: 500%; color: red;"><strong>You lazy bum!</strong></div>
  323. </body></html>';
  324. obExit(false);
  325. }
  326. /**
  327. * Convert both data and database tables to UTF-8 character set.
  328. * It requires the admin_forum permission.
  329. * This only works if UTF-8 is not the global character set.
  330. * It supports all character sets used by SMF's language files.
  331. * It redirects to ?action=admin;area=maintain after finishing.
  332. * This action is linked from the maintenance screen (if it's applicable).
  333. * Accessed by ?action=admin;area=maintain;sa=database;activity=convertutf8.
  334. *
  335. * @uses the convert_utf8 sub template of the Admin template.
  336. */
  337. function ConvertUtf8()
  338. {
  339. global $scripturl, $context, $txt, $language, $db_character_set;
  340. global $modSettings, $user_info, $sourcedir, $smcFunc, $db_prefix;
  341. // Show me your badge!
  342. isAllowedTo('admin_forum');
  343. // The character sets used in SMF's language files with their db equivalent.
  344. $charsets = array(
  345. // Chinese-traditional.
  346. 'big5' => 'big5',
  347. // Chinese-simplified.
  348. 'gbk' => 'gbk',
  349. // West European.
  350. 'ISO-8859-1' => 'latin1',
  351. // Romanian.
  352. 'ISO-8859-2' => 'latin2',
  353. // Turkish.
  354. 'ISO-8859-9' => 'latin5',
  355. // West European with Euro sign.
  356. 'ISO-8859-15' => 'latin9',
  357. // Thai.
  358. 'tis-620' => 'tis620',
  359. // Persian, Chinese, etc.
  360. 'UTF-8' => 'utf8',
  361. // Russian.
  362. 'windows-1251' => 'cp1251',
  363. // Greek.
  364. 'windows-1253' => 'utf8',
  365. // Hebrew.
  366. 'windows-1255' => 'utf8',
  367. // Arabic.
  368. 'windows-1256' => 'cp1256',
  369. );
  370. // Get a list of character sets supported by your MySQL server.
  371. $request = $smcFunc['db_query']('', '
  372. SHOW CHARACTER SET',
  373. array(
  374. )
  375. );
  376. $db_charsets = array();
  377. while ($row = $smcFunc['db_fetch_assoc']($request))
  378. $db_charsets[] = $row['Charset'];
  379. $smcFunc['db_free_result']($request);
  380. // Character sets supported by both MySQL and SMF's language files.
  381. $charsets = array_intersect($charsets, $db_charsets);
  382. // This is for the first screen telling backups is good.
  383. if (!isset($_POST['proceed']))
  384. {
  385. validateToken('admin-maint');
  386. // Character set conversions are only supported as of MySQL 4.1.2.
  387. if (version_compare('4.1.2', preg_replace('~\-.+?$~', '', $smcFunc['db_server_info']()), '>'))
  388. fatal_lang_error('utf8_db_version_too_low');
  389. // Use the messages.body column as indicator for the database charset.
  390. $request = $smcFunc['db_query']('', '
  391. SHOW FULL COLUMNS
  392. FROM {db_prefix}messages
  393. LIKE {string:body_like}',
  394. array(
  395. 'body_like' => 'body',
  396. )
  397. );
  398. $column_info = $smcFunc['db_fetch_assoc']($request);
  399. $smcFunc['db_free_result']($request);
  400. // A collation looks like latin1_swedish. We only need the character set.
  401. list($context['database_charset']) = explode('_', $column_info['Collation']);
  402. $context['database_charset'] = in_array($context['database_charset'], $charsets) ? array_search($context['database_charset'], $charsets) : $context['database_charset'];
  403. // No need to convert to UTF-8 if it already is.
  404. if ($db_character_set === 'utf8' && !empty($modSettings['global_character_set']) && $modSettings['global_character_set'] === 'UTF-8')
  405. fatal_lang_error('utf8_already_utf8');
  406. // Cannot do conversion if using a fulltext index
  407. if (!empty($modSettings['search_index']) && $modSettings['search_index'] == 'fulltext')
  408. fatal_lang_error('utf8_cannot_convert_fulltext');
  409. // Grab the character set from the default language file.
  410. loadLanguage('index', $language, true);
  411. $context['charset_detected'] = $txt['lang_character_set'];
  412. $context['charset_about_detected'] = sprintf($txt['utf8_detected_charset'], $language, $context['charset_detected']);
  413. // Go back to your own language.
  414. loadLanguage('index', $user_info['language'], true);
  415. // Show a warning if the character set seems not to be supported.
  416. if (!isset($charsets[strtr(strtolower($context['charset_detected']), array('utf' => 'UTF', 'iso' => 'ISO'))]))
  417. {
  418. $context['charset_warning'] = sprintf($txt['utf8_charset_not_supported'], $txt['lang_character_set']);
  419. // Default to ISO-8859-1.
  420. $context['charset_detected'] = 'ISO-8859-1';
  421. }
  422. $context['charset_list'] = array_keys($charsets);
  423. $context['page_title'] = $txt['utf8_title'];
  424. $context['sub_template'] = 'convert_utf8';
  425. createToken('admin-maint');
  426. return;
  427. }
  428. // After this point we're starting the conversion. But first: session check.
  429. checkSession();
  430. validateToken('admin-maint');
  431. createToken('admin-maint');
  432. // Translation table for the character sets not native for MySQL.
  433. $translation_tables = array(
  434. 'windows-1255' => array(
  435. '0x81' => '\'\'', '0x8A' => '\'\'', '0x8C' => '\'\'',
  436. '0x8D' => '\'\'', '0x8E' => '\'\'', '0x8F' => '\'\'',
  437. '0x90' => '\'\'', '0x9A' => '\'\'', '0x9C' => '\'\'',
  438. '0x9D' => '\'\'', '0x9E' => '\'\'', '0x9F' => '\'\'',
  439. '0xCA' => '\'\'', '0xD9' => '\'\'', '0xDA' => '\'\'',
  440. '0xDB' => '\'\'', '0xDC' => '\'\'', '0xDD' => '\'\'',
  441. '0xDE' => '\'\'', '0xDF' => '\'\'', '0xFB' => '\'\'',
  442. '0xFC' => '\'\'', '0xFF' => '\'\'', '0xC2' => '0xFF',
  443. '0x80' => '0xFC', '0xE2' => '0xFB', '0xA0' => '0xC2A0',
  444. '0xA1' => '0xC2A1', '0xA2' => '0xC2A2', '0xA3' => '0xC2A3',
  445. '0xA5' => '0xC2A5', '0xA6' => '0xC2A6', '0xA7' => '0xC2A7',
  446. '0xA8' => '0xC2A8', '0xA9' => '0xC2A9', '0xAB' => '0xC2AB',
  447. '0xAC' => '0xC2AC', '0xAD' => '0xC2AD', '0xAE' => '0xC2AE',
  448. '0xAF' => '0xC2AF', '0xB0' => '0xC2B0', '0xB1' => '0xC2B1',
  449. '0xB2' => '0xC2B2', '0xB3' => '0xC2B3', '0xB4' => '0xC2B4',
  450. '0xB5' => '0xC2B5', '0xB6' => '0xC2B6', '0xB7' => '0xC2B7',
  451. '0xB8' => '0xC2B8', '0xB9' => '0xC2B9', '0xBB' => '0xC2BB',
  452. '0xBC' => '0xC2BC', '0xBD' => '0xC2BD', '0xBE' => '0xC2BE',
  453. '0xBF' => '0xC2BF', '0xD7' => '0xD7B3', '0xD1' => '0xD781',
  454. '0xD4' => '0xD7B0', '0xD5' => '0xD7B1', '0xD6' => '0xD7B2',
  455. '0xE0' => '0xD790', '0xEA' => '0xD79A', '0xEC' => '0xD79C',
  456. '0xED' => '0xD79D', '0xEE' => '0xD79E', '0xEF' => '0xD79F',
  457. '0xF0' => '0xD7A0', '0xF1' => '0xD7A1', '0xF2' => '0xD7A2',
  458. '0xF3' => '0xD7A3', '0xF5' => '0xD7A5', '0xF6' => '0xD7A6',
  459. '0xF7' => '0xD7A7', '0xF8' => '0xD7A8', '0xF9' => '0xD7A9',
  460. '0x82' => '0xE2809A', '0x84' => '0xE2809E', '0x85' => '0xE280A6',
  461. '0x86' => '0xE280A0', '0x87' => '0xE280A1', '0x89' => '0xE280B0',
  462. '0x8B' => '0xE280B9', '0x93' => '0xE2809C', '0x94' => '0xE2809D',
  463. '0x95' => '0xE280A2', '0x97' => '0xE28094', '0x99' => '0xE284A2',
  464. '0xC0' => '0xD6B0', '0xC1' => '0xD6B1', '0xC3' => '0xD6B3',
  465. '0xC4' => '0xD6B4', '0xC5' => '0xD6B5', '0xC6' => '0xD6B6',
  466. '0xC7' => '0xD6B7', '0xC8' => '0xD6B8', '0xC9' => '0xD6B9',
  467. '0xCB' => '0xD6BB', '0xCC' => '0xD6BC', '0xCD' => '0xD6BD',
  468. '0xCE' => '0xD6BE', '0xCF' => '0xD6BF', '0xD0' => '0xD780',
  469. '0xD2' => '0xD782', '0xE3' => '0xD793', '0xE4' => '0xD794',
  470. '0xE5' => '0xD795', '0xE7' => '0xD797', '0xE9' => '0xD799',
  471. '0xFD' => '0xE2808E', '0xFE' => '0xE2808F', '0x92' => '0xE28099',
  472. '0x83' => '0xC692', '0xD3' => '0xD783', '0x88' => '0xCB86',
  473. '0x98' => '0xCB9C', '0x91' => '0xE28098', '0x96' => '0xE28093',
  474. '0xBA' => '0xC3B7', '0x9B' => '0xE280BA', '0xAA' => '0xC397',
  475. '0xA4' => '0xE282AA', '0xE1' => '0xD791', '0xE6' => '0xD796',
  476. '0xE8' => '0xD798', '0xEB' => '0xD79B', '0xF4' => '0xD7A4',
  477. '0xFA' => '0xD7AA', '0xFF' => '0xD6B2', '0xFC' => '0xE282AC',
  478. '0xFB' => '0xD792',
  479. ),
  480. 'windows-1253' => array(
  481. '0x81' => '\'\'', '0x88' => '\'\'', '0x8A' => '\'\'',
  482. '0x8C' => '\'\'', '0x8D' => '\'\'', '0x8E' => '\'\'',
  483. '0x8F' => '\'\'', '0x90' => '\'\'', '0x98' => '\'\'',
  484. '0x9A' => '\'\'', '0x9C' => '\'\'', '0x9D' => '\'\'',
  485. '0x9E' => '\'\'', '0x9F' => '\'\'', '0xAA' => '\'\'',
  486. '0xD2' => '\'\'', '0xFF' => '\'\'', '0xCE' => '0xCE9E',
  487. '0xB8' => '0xCE88', '0xBA' => '0xCE8A', '0xBC' => '0xCE8C',
  488. '0xBE' => '0xCE8E', '0xBF' => '0xCE8F', '0xC0' => '0xCE90',
  489. '0xC8' => '0xCE98', '0xCA' => '0xCE9A', '0xCC' => '0xCE9C',
  490. '0xCD' => '0xCE9D', '0xCF' => '0xCE9F', '0xDA' => '0xCEAA',
  491. '0xE8' => '0xCEB8', '0xEA' => '0xCEBA', '0xEC' => '0xCEBC',
  492. '0xEE' => '0xCEBE', '0xEF' => '0xCEBF', '0xC2' => '0xFF',
  493. '0xBD' => '0xC2BD', '0xED' => '0xCEBD', '0xB2' => '0xC2B2',
  494. '0xA0' => '0xC2A0', '0xA3' => '0xC2A3', '0xA4' => '0xC2A4',
  495. '0xA5' => '0xC2A5', '0xA6' => '0xC2A6', '0xA7' => '0xC2A7',
  496. '0xA8' => '0xC2A8', '0xA9' => '0xC2A9', '0xAB' => '0xC2AB',
  497. '0xAC' => '0xC2AC', '0xAD' => '0xC2AD', '0xAE' => '0xC2AE',
  498. '0xB0' => '0xC2B0', '0xB1' => '0xC2B1', '0xB3' => '0xC2B3',
  499. '0xB5' => '0xC2B5', '0xB6' => '0xC2B6', '0xB7' => '0xC2B7',
  500. '0xBB' => '0xC2BB', '0xE2' => '0xCEB2', '0x80' => '0xD2',
  501. '0x82' => '0xE2809A', '0x84' => '0xE2809E', '0x85' => '0xE280A6',
  502. '0x86' => '0xE280A0', '0xA1' => '0xCE85', '0xA2' => '0xCE86',
  503. '0x87' => '0xE280A1', '0x89' => '0xE280B0', '0xB9' => '0xCE89',
  504. '0x8B' => '0xE280B9', '0x91' => '0xE28098', '0x99' => '0xE284A2',
  505. '0x92' => '0xE28099', '0x93' => '0xE2809C', '0x94' => '0xE2809D',
  506. '0x95' => '0xE280A2', '0x96' => '0xE28093', '0x97' => '0xE28094',
  507. '0x9B' => '0xE280BA', '0xAF' => '0xE28095', '0xB4' => '0xCE84',
  508. '0xC1' => '0xCE91', '0xC3' => '0xCE93', '0xC4' => '0xCE94',
  509. '0xC5' => '0xCE95', '0xC6' => '0xCE96', '0x83' => '0xC692',
  510. '0xC7' => '0xCE97', '0xC9' => '0xCE99', '0xCB' => '0xCE9B',
  511. '0xD0' => '0xCEA0', '0xD1' => '0xCEA1', '0xD3' => '0xCEA3',
  512. '0xD4' => '0xCEA4', '0xD5' => '0xCEA5', '0xD6' => '0xCEA6',
  513. '0xD7' => '0xCEA7', '0xD8' => '0xCEA8', '0xD9' => '0xCEA9',
  514. '0xDB' => '0xCEAB', '0xDC' => '0xCEAC', '0xDD' => '0xCEAD',
  515. '0xDE' => '0xCEAE', '0xDF' => '0xCEAF', '0xE0' => '0xCEB0',
  516. '0xE1' => '0xCEB1', '0xE3' => '0xCEB3', '0xE4' => '0xCEB4',
  517. '0xE5' => '0xCEB5', '0xE6' => '0xCEB6', '0xE7' => '0xCEB7',
  518. '0xE9' => '0xCEB9', '0xEB' => '0xCEBB', '0xF0' => '0xCF80',
  519. '0xF1' => '0xCF81', '0xF2' => '0xCF82', '0xF3' => '0xCF83',
  520. '0xF4' => '0xCF84', '0xF5' => '0xCF85', '0xF6' => '0xCF86',
  521. '0xF7' => '0xCF87', '0xF8' => '0xCF88', '0xF9' => '0xCF89',
  522. '0xFA' => '0xCF8A', '0xFB' => '0xCF8B', '0xFC' => '0xCF8C',
  523. '0xFD' => '0xCF8D', '0xFE' => '0xCF8E', '0xFF' => '0xCE92',
  524. '0xD2' => '0xE282AC',
  525. ),
  526. );
  527. // Make some preparations.
  528. if (isset($translation_tables[$_POST['src_charset']]))
  529. {
  530. $replace = '%field%';
  531. foreach ($translation_tables[$_POST['src_charset']] as $from => $to)
  532. $replace = 'REPLACE(' . $replace . ', ' . $from . ', ' . $to . ')';
  533. }
  534. // Grab a list of tables.
  535. if (preg_match('~^`(.+?)`\.(.+?)$~', $db_prefix, $match) === 1)
  536. $queryTables = $smcFunc['db_query']('', '
  537. SHOW TABLE STATUS
  538. FROM `' . strtr($match[1], array('`' => '')) . '`
  539. LIKE {string:table_name}',
  540. array(
  541. 'table_name' => str_replace('_', '\_', $match[2]) . '%',
  542. )
  543. );
  544. else
  545. $queryTables = $smcFunc['db_query']('', '
  546. SHOW TABLE STATUS
  547. LIKE {string:table_name}',
  548. array(
  549. 'table_name' => str_replace('_', '\_', $db_prefix) . '%',
  550. )
  551. );
  552. while ($table_info = $smcFunc['db_fetch_assoc']($queryTables))
  553. {
  554. // Just to make sure it doesn't time out.
  555. if (function_exists('apache_reset_timeout'))
  556. @apache_reset_timeout();
  557. $table_charsets = array();
  558. // Loop through each column.
  559. $queryColumns = $smcFunc['db_query']('', '
  560. SHOW FULL COLUMNS
  561. FROM ' . $table_info['Name'],
  562. array(
  563. )
  564. );
  565. while ($column_info = $smcFunc['db_fetch_assoc']($queryColumns))
  566. {
  567. // Only text'ish columns have a character set and need converting.
  568. if (strpos($column_info['Type'], 'text') !== false || strpos($column_info['Type'], 'char') !== false)
  569. {
  570. $collation = empty($column_info['Collation']) || $column_info['Collation'] === 'NULL' ? $table_info['Collation'] : $column_info['Collation'];
  571. if (!empty($collation) && $collation !== 'NULL')
  572. {
  573. list($charset) = explode('_', $collation);
  574. if (!isset($table_charsets[$charset]))
  575. $table_charsets[$charset] = array();
  576. $table_charsets[$charset][] = $column_info;
  577. }
  578. }
  579. }
  580. $smcFunc['db_free_result']($queryColumns);
  581. // Only change the column if the data doesn't match the current charset.
  582. if ((count($table_charsets) === 1 && key($table_charsets) !== $charsets[$_POST['src_charset']]) || count($table_charsets) > 1)
  583. {
  584. $updates_blob = '';
  585. $updates_text = '';
  586. foreach ($table_charsets as $charset => $columns)
  587. {
  588. if ($charset !== $charsets[$_POST['src_charset']])
  589. {
  590. foreach ($columns as $column)
  591. {
  592. $updates_blob .= '
  593. 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'] . '\'') . ',';
  594. $updates_text .= '
  595. 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'] . '\'') . ',';
  596. }
  597. }
  598. }
  599. // Change the columns to binary form.
  600. $smcFunc['db_query']('', '
  601. ALTER TABLE {raw:table_name}{raw:updates_blob}',
  602. array(
  603. 'table_name' => $table_info['Name'],
  604. 'updates_blob' => substr($updates_blob, 0, -1),
  605. )
  606. );
  607. // Convert the character set if MySQL has no native support for it.
  608. if (isset($translation_tables[$_POST['src_charset']]))
  609. {
  610. $update = '';
  611. foreach ($table_charsets as $charset => $columns)
  612. foreach ($columns as $column)
  613. $update .= '
  614. ' . $column['Field'] . ' = ' . strtr($replace, array('%field%' => $column['Field'])) . ',';
  615. $smcFunc['db_query']('', '
  616. UPDATE {raw:table_name}
  617. SET {raw:updates}',
  618. array(
  619. 'table_name' => $table_info['Name'],
  620. 'updates' => substr($update, 0, -1),
  621. )
  622. );
  623. }
  624. // Change the columns back, but with the proper character set.
  625. $smcFunc['db_query']('', '
  626. ALTER TABLE {raw:table_name}{raw:updates_text}',
  627. array(
  628. 'table_name' => $table_info['Name'],
  629. 'updates_text' => substr($updates_text, 0, -1),
  630. )
  631. );
  632. }
  633. // Now do the actual conversion (if still needed).
  634. if ($charsets[$_POST['src_charset']] !== 'utf8')
  635. $smcFunc['db_query']('', '
  636. ALTER TABLE {raw:table_name}
  637. CONVERT TO CHARACTER SET utf8',
  638. array(
  639. 'table_name' => $table_info['Name'],
  640. )
  641. );
  642. }
  643. $smcFunc['db_free_result']($queryTables);
  644. call_integration_hook('integrate_convert_utf8');
  645. // Let the settings know we have a new character set.
  646. updateSettings(array('global_character_set' => 'UTF-8', 'previousCharacterSet' => (empty($translation_tables[$_POST['src_charset']])) ? $charsets[$_POST['src_charset']] : $translation_tables[$_POST['src_charset']]));
  647. // Store it in Settings.php too because it's needed before db connection.
  648. require_once($sourcedir . '/Subs-Admin.php');
  649. updateSettingsFile(array('db_character_set' => '\'utf8\''));
  650. // The conversion might have messed up some serialized strings. Fix them!
  651. require_once($sourcedir . '/Subs-Charset.php');
  652. fix_serialized_columns();
  653. redirectexit('action=admin;area=maintain;done=convertutf8');
  654. }
  655. /**
  656. * Convert the column "body" of the table {db_prefix}messages from TEXT to MEDIUMTEXT and vice versa.
  657. * It requires the admin_forum permission.
  658. * This is needed only for MySQL.
  659. * During the convertion from MEDIUMTEXT to TEXT it check if any of the posts exceed the TEXT length and if so it aborts.
  660. * This action is linked from the maintenance screen (if it's applicable).
  661. * Accessed by ?action=admin;area=maintain;sa=database;activity=convertmsgbody.
  662. *
  663. * @uses the convert_msgbody sub template of the Admin template.
  664. */
  665. function ConvertMsgBody()
  666. {
  667. global $scripturl, $context, $txt, $language, $db_character_set, $db_type;
  668. global $modSettings, $user_info, $sourcedir, $smcFunc, $db_prefix, $time_start;
  669. // Show me your badge!
  670. isAllowedTo('admin_forum');
  671. if ($db_type != 'mysql')
  672. return;
  673. db_extend('packages');
  674. $colData = $smcFunc['db_list_columns']('{db_prefix}messages', true);
  675. foreach ($colData as $column)
  676. if ($column['name'] == 'body')
  677. $body_type = $column['type'];
  678. $context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text';
  679. if ($body_type == 'text' || ($body_type != 'text' && isset($_POST['do_conversion'])))
  680. {
  681. checkSession();
  682. validateToken('admin-maint');
  683. // Make it longer so we can do their limit.
  684. if ($body_type == 'text')
  685. $smcFunc['db_change_column']('{db_prefix}messages', 'body', array('type' => 'mediumtext'));
  686. // Shorten the column so we can have a bit (literally per record) less space occupied
  687. else
  688. $smcFunc['db_change_column']('{db_prefix}messages', 'body', array('type' => 'text'));
  689. $colData = $smcFunc['db_list_columns']('{db_prefix}messages', true);
  690. foreach ($colData as $column)
  691. if ($column['name'] == 'body')
  692. $body_type = $column['type'];
  693. $context['maintenance_finished'] = $txt[$context['convert_to'] . '_title'];
  694. $context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text';
  695. $context['convert_to_suggest'] = ($body_type != 'text' && !empty($modSettings['max_messageLength']) && $modSettings['max_messageLength'] < 65536);
  696. return;
  697. redirectexit('action=admin;area=maintain;sa=database');
  698. }
  699. elseif ($body_type != 'text' && (!isset($_POST['do_conversion']) || isset($_POST['cont'])))
  700. {
  701. checkSession();
  702. if (empty($_REQUEST['start']))
  703. validateToken('admin-maint');
  704. else
  705. validateToken('admin-convertMsg');
  706. $context['page_title'] = $txt['not_done_title'];
  707. $context['continue_post_data'] = '';
  708. $context['continue_countdown'] = 3;
  709. $context['sub_template'] = 'not_done';
  710. $increment = 500;
  711. $id_msg_exceeding = isset($_POST['id_msg_exceeding']) ? explode(',', $_POST['id_msg_exceeding']) : array();
  712. $request = $smcFunc['db_query']('', '
  713. SELECT COUNT(*) as count
  714. FROM {db_prefix}messages',
  715. array()
  716. );
  717. list($max_msgs) = $smcFunc['db_fetch_row']($request);
  718. $smcFunc['db_free_result']($request);
  719. // Try for as much time as possible.
  720. @set_time_limit(600);
  721. while ($_REQUEST['start'] < $max_msgs)
  722. {
  723. $request = $smcFunc['db_query']('', '
  724. SELECT /*!40001 SQL_NO_CACHE */ id_msg
  725. FROM {db_prefix}messages
  726. WHERE id_msg BETWEEN {int:start} AND {int:start} + {int:increment}
  727. AND LENGTH(body) > 65535',
  728. array(
  729. 'start' => $_REQUEST['start'],
  730. 'increment' => $increment - 1,
  731. )
  732. );
  733. while ($row = $smcFunc['db_fetch_assoc']($request))
  734. $id_msg_exceeding[] = $row['id_msg'];
  735. $smcFunc['db_free_result']($request);
  736. $_REQUEST['start'] += $increment;
  737. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3)
  738. {
  739. createToken('admin-convertMsg');
  740. $context['continue_post_data'] = '
  741. <input type="hidden" name="' . $context['admin-convertMsg_token_var'] . '" value="' . $context['admin-convertMsg_token'] . '" />
  742. <input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" />
  743. <input type="hidden" name="id_msg_exceeding" value="' . implode(',', $id_msg_exceeding) . '" />';
  744. $context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=convertmsgbody;start=' . $_REQUEST['start'];
  745. $context['continue_percent'] = round(100 * $_REQUEST['start'] / $max_msgs);
  746. return;
  747. }
  748. }
  749. createToken('admin-maint');
  750. $context['page_title'] = $txt[$context['convert_to'] . '_title'];
  751. $context['sub_template'] = 'convert_msgbody';
  752. if (!empty($id_msg_exceeding))
  753. {
  754. if (count($id_msg_exceeding) > 100)
  755. {
  756. $query_msg = array_slice($id_msg_exceeding, 0, 100);
  757. $context['exceeding_messages_morethan'] = sprintf($txt['exceeding_messages_morethan'], count($id_msg_exceeding));
  758. }
  759. else
  760. $query_msg = $id_msg_exceeding;
  761. $context['exceeding_messages'] = array();
  762. $request = $smcFunc['db_query']('', '
  763. SELECT id_msg, id_topic, subject
  764. FROM {db_prefix}messages
  765. WHERE id_msg IN ({array_int:messages})',
  766. array(
  767. 'messages' => $query_msg,
  768. )
  769. );
  770. while ($row = $smcFunc['db_fetch_assoc']($request))
  771. $context['exceeding_messages'][] = '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '">' . $row['subject'] . '</a>';
  772. $smcFunc['db_free_result']($request);
  773. }
  774. }
  775. }
  776. /**
  777. * Converts HTML-entities to their UTF-8 character equivalents.
  778. * This requires the admin_forum permission.
  779. * Pre-condition: UTF-8 has been set as database and global character set.
  780. *
  781. * It is divided in steps of 10 seconds.
  782. * This action is linked from the maintenance screen (if applicable).
  783. * It is accessed by ?action=admin;area=maintain;sa=database;activity=convertentities.
  784. *
  785. * @uses Admin template, convert_entities sub-template.
  786. */
  787. function ConvertEntities()
  788. {
  789. global $db_character_set, $modSettings, $context, $sourcedir, $smcFunc;
  790. isAllowedTo('admin_forum');
  791. // Check to see if UTF-8 is currently the default character set.
  792. if ($modSettings['global_character_set'] !== 'UTF-8' || !isset($db_character_set) || $db_character_set !== 'utf8')
  793. fatal_lang_error('entity_convert_only_utf8');
  794. // Some starting values.
  795. $context['table'] = empty($_REQUEST['table']) ? 0 : (int) $_REQUEST['table'];
  796. $context['start'] = empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'];
  797. $context['start_time'] = time();
  798. $context['first_step'] = !isset($_REQUEST[$context['session_var']]);
  799. $context['last_step'] = false;
  800. // The first step is just a text screen with some explanation.
  801. if ($context['first_step'])
  802. {
  803. validateToken('admin-maint');
  804. createToken('admin-maint');
  805. $context['sub_template'] = 'convert_entities';
  806. return;
  807. }
  808. // Otherwise use the generic "not done" template.
  809. $context['sub_template'] = 'not_done';
  810. $context['continue_post_data'] = '';
  811. $context['continue_countdown'] = 3;
  812. // Now we're actually going to convert...
  813. checkSession('request');
  814. validateToken('admin-maint');
  815. createToken('admin-maint');
  816. // A list of tables ready for conversion.
  817. $tables = array(
  818. 'ban_groups',
  819. 'ban_items',
  820. 'boards',
  821. 'calendar',
  822. 'calendar_holidays',
  823. 'categories',
  824. 'log_errors',
  825. 'log_search_subjects',
  826. 'membergroups',
  827. 'members',
  828. 'message_icons',
  829. 'messages',
  830. 'package_servers',
  831. 'personal_messages',
  832. 'pm_recipients',
  833. 'polls',
  834. 'poll_choices',
  835. 'smileys',
  836. 'themes',
  837. );
  838. $context['num_tables'] = count($tables);
  839. // This function will do the conversion later on.
  840. $entity_replace = create_function('$string', '
  841. $num = substr($string, 0, 1) === \'x\' ? hexdec(substr($string, 1)) : (int) $string;
  842. return $num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) ? \'\' : ($num < 0x80 ? \'&#\' . $num . \';\' : ($num < 0x800 ? chr(192 | $num >> 6) . chr(128 | $num & 63) : ($num < 0x10000 ? chr(224 | $num >> 12) . chr(128 | $num >> 6 & 63) . chr(128 | $num & 63) : chr(240 | $num >> 18) . chr(128 | $num >> 12 & 63) . chr(128 | $num >> 6 & 63) . chr(128 | $num & 63))));');
  843. // Loop through all tables that need converting.
  844. for (; $context['table'] < $context['num_tables']; $context['table']++)
  845. {
  846. $cur_table = $tables[$context['table']];
  847. $primary_key = '';
  848. // Make sure we keep stuff unique!
  849. $primary_keys = array();
  850. if (function_exists('apache_reset_timeout'))
  851. @apache_reset_timeout();
  852. // Get a list of text columns.
  853. $columns = array();
  854. $request = $smcFunc['db_query']('', '
  855. SHOW FULL COLUMNS
  856. FROM {db_prefix}' . $cur_table,
  857. array(
  858. )
  859. );
  860. while ($column_info = $smcFunc['db_fetch_assoc']($request))
  861. if (strpos($column_info['Type'], 'text') !== false || strpos($column_info['Type'], 'char') !== false)
  862. $columns[] = strtolower($column_info['Field']);
  863. // Get the column with the (first) primary key.
  864. $request = $smcFunc['db_query']('', '
  865. SHOW KEYS
  866. FROM {db_prefix}' . $cur_table,
  867. array(
  868. )
  869. );
  870. while ($row = $smcFunc['db_fetch_assoc']($request))
  871. {
  872. if ($row['Key_name'] === 'PRIMARY')
  873. {
  874. if (empty($primary_key) || ($row['Seq_in_index'] == 1 && !in_array(strtolower($row['Column_name']), $columns)))
  875. $primary_key = $row['Column_name'];
  876. $primary_keys[] = $row['Column_name'];
  877. }
  878. }
  879. $smcFunc['db_free_result']($request);
  880. // No primary key, no glory.
  881. // Same for columns. Just to be sure we've work to do!
  882. if (empty($primary_key) || empty($columns))
  883. continue;
  884. // Get the maximum value for the primary key.
  885. $request = $smcFunc['db_query']('', '
  886. SELECT MAX(' . $primary_key . ')
  887. FROM {db_prefix}' . $cur_table,
  888. array(
  889. )
  890. );
  891. list($max_value) = $smcFunc['db_fetch_row']($request);
  892. $smcFunc['db_free_result']($request);
  893. if (empty($max_value))
  894. continue;
  895. while ($context['start'] <= $max_value)
  896. {
  897. // Retrieve a list of rows that has at least one entity to convert.
  898. $request = $smcFunc['db_query']('', '
  899. SELECT {raw:primary_keys}, {raw:columns}
  900. FROM {db_prefix}{raw:cur_table}
  901. WHERE {raw:primary_key} BETWEEN {int:start} AND {int:start} + 499
  902. AND {raw:like_compare}
  903. LIMIT 500',
  904. array(
  905. 'primary_keys' => implode(', ', $primary_keys),
  906. 'columns' => implode(', ', $columns),
  907. 'cur_table' => $cur_table,
  908. 'primary_key' => $primary_key,
  909. 'start' => $context['start'],
  910. 'like_compare' => '(' . implode(' LIKE \'%&#%\' OR ', $columns) . ' LIKE \'%&#%\')',
  911. )
  912. );
  913. while ($row = $smcFunc['db_fetch_assoc']($request))
  914. {
  915. $insertion_variables = array();
  916. $changes = array();
  917. foreach ($row as $column_name => $column_value)
  918. if ($column_name !== $primary_key && strpos($column_value, '&#') !== false)
  919. {
  920. $changes[] = $column_name . ' = {string:changes_' . $column_name . '}';
  921. $insertion_variables['changes_' . $column_name] = preg_replace('~(&#(\d{1,7}|x[0-9a-fA-F]{1,6});)~e', '$entity_replace(\'\\2\')', $column_value);
  922. }
  923. $where = array();
  924. foreach ($primary_keys as $key)
  925. {
  926. $where[] = $key . ' = {string:where_' . $key . '}';
  927. $insertion_variables['where_' . $key] = $row[$key];
  928. }
  929. // Update the row.
  930. if (!empty($changes))
  931. $smcFunc['db_query']('', '
  932. UPDATE {db_prefix}' . $cur_table . '
  933. SET
  934. ' . implode(',
  935. ', $changes) . '
  936. WHERE ' . implode(' AND ', $where),
  937. $insertion_variables
  938. );
  939. }
  940. $smcFunc['db_free_result']($request);
  941. $context['start'] += 500;
  942. // After ten seconds interrupt.
  943. if (time() - $context['start_time'] > 10)
  944. {
  945. // Calculate an approximation of the percentage done.
  946. $context['continue_percent'] = round(100 * ($context['table'] + ($context['start'] / $max_value)) / $context['num_tables'], 1);
  947. $context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=convertentities;table=' . $context['table'] . ';start=' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  948. return;
  949. }
  950. }
  951. $context['start'] = 0;
  952. }
  953. // Make sure all serialized strings are all right.
  954. require_once($sourcedir . '/Subs-Charset.php');
  955. fix_serialized_columns();
  956. // If we're here, we must be done.
  957. $context['continue_percent'] = 100;
  958. $context['continue_get_data'] = '?action=admin;area=maintain;sa=database;done=convertentities';
  959. $context['last_step'] = true;
  960. $context['continue_countdown'] = -1;
  961. }
  962. /**
  963. * Optimizes all tables in the database and lists how much was saved.
  964. * It requires the admin_forum permission.
  965. * It shows as the maintain_forum admin area.
  966. * It is accessed from ?action=admin;area=maintain;sa=database;activity=optimize.
  967. * It also updates the optimize scheduled task such that the tables are not automatically optimized again too soon.
  968. * @uses the rawdata sub template (built in.)
  969. */
  970. function OptimizeTables()
  971. {
  972. global $db_type, $db_name, $db_prefix, $txt, $context, $scripturl, $sourcedir, $smcFunc;
  973. isAllowedTo('admin_forum');
  974. checkSession('post');
  975. validateToken('admin-maint');
  976. ignore_user_abort(true);
  977. db_extend();
  978. // Start with no tables optimized.
  979. $opttab = 0;
  980. $context['page_title'] = $txt['database_optimize'];
  981. $context['sub_template'] = 'optimize';
  982. // Only optimize the tables related to this smf install, not all the tables in the db
  983. $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
  984. // Get a list of tables, as well as how many there are.
  985. $temp_tables = $smcFunc['db_list_tables'](false, $real_prefix . '%');
  986. $tables = array();
  987. foreach ($temp_tables as $table)
  988. $tables[] = array('table_name' => $table);
  989. // If there aren't any tables then I believe that would mean the world has exploded...
  990. $context['num_tables'] = count($tables);
  991. if ($context['num_tables'] == 0)
  992. fatal_error('You appear to be running SMF in a flat file mode... fantastic!', false);
  993. // For each table....
  994. $context['optimized_tables'] = array();
  995. foreach ($tables as $table)
  996. {
  997. // Optimize the table! We use backticks here because it might be a custom table.
  998. $data_freed = $smcFunc['db_optimize_table']($table['table_name']);
  999. // Optimizing one sqlite table optimizes them all.
  1000. if ($db_type == 'sqlite')
  1001. break;
  1002. if ($data_freed > 0)
  1003. $context['optimized_tables'][] = array(
  1004. 'name' => $table['table_name'],
  1005. 'data_freed' => $data_freed,
  1006. );
  1007. }
  1008. // Number of tables, etc....
  1009. $txt['database_numb_tables'] = sprintf($txt['database_numb_tables'], $context['num_tables']);
  1010. $context['num_tables_optimized'] = count($context['optimized_tables']);
  1011. // Check that we don't auto optimise again too soon!
  1012. require_once($sourcedir . '/ScheduledTasks.php');
  1013. CalculateNextTrigger('auto_optimize', true);
  1014. }
  1015. /**
  1016. * Recount many forum totals that can be recounted automatically without harm.
  1017. * it requires the admin_forum permission.
  1018. * It shows the maintain_forum admin area.
  1019. *
  1020. * Totals recounted:
  1021. * - fixes for topics with wrong num_replies.
  1022. * - updates for num_posts and num_topics of all boards.
  1023. * - recounts instant_messages but not unread_messages.
  1024. * - repairs messages pointing to boards with topics pointing to other boards.
  1025. * - updates the last message posted in boards and children.
  1026. * - updates member count, latest member, topic count, and message count.
  1027. *
  1028. * The function redirects back to ?action=admin;area=maintain when complete.
  1029. * It is accessed via ?action=admin;area=maintain;sa=database;activity=recount.
  1030. */
  1031. function AdminBoardRecount()
  1032. {
  1033. global $txt, $context, $scripturl, $modSettings, $sourcedir;
  1034. global $time_start, $smcFunc;
  1035. isAllowedTo('admin_forum');
  1036. checkSession('request');
  1037. // validate the request or the loop
  1038. if (!isset($_REQUEST['step']))
  1039. validateToken('admin-maint');
  1040. else
  1041. validateToken('admin-boardrecount');
  1042. $context['page_title'] = $txt['not_done_title'];
  1043. $context['continue_post_data'] = '';
  1044. $context['continue_countdown'] = 3;
  1045. $context['sub_template'] = 'not_done';
  1046. // Try for as much time as possible.
  1047. @set_time_limit(600);
  1048. // Step the number of topics at a time so things don't time out...
  1049. $request = $smcFunc['db_query']('', '
  1050. SELECT MAX(id_topic)
  1051. FROM {db_prefix}topics',
  1052. array(
  1053. )
  1054. );
  1055. list ($max_topics) = $smcFunc['db_fetch_row']($request);
  1056. $smcFunc['db_free_result']($request);
  1057. $increment = min(max(50, ceil($max_topics / 4)), 2000);
  1058. if (empty($_REQUEST['start']))
  1059. $_REQUEST['start'] = 0;
  1060. $total_steps = 8;
  1061. // Get each topic with a wrong reply count and fix it - let's just do some at a time, though.
  1062. if (empty($_REQUEST['step']))
  1063. {
  1064. $_REQUEST['step'] = 0;
  1065. while ($_REQUEST['start'] < $max_topics)
  1066. {
  1067. // Recount approved messages
  1068. $request = $smcFunc['db_query']('', '
  1069. SELECT /*!40001 SQL_NO_CACHE */ t.id_topic, MAX(t.num_replies) AS num_replies,
  1070. CASE WHEN COUNT(ma.id_msg) >= 1 THEN COUNT(ma.id_msg) - 1 ELSE 0 END AS real_num_replies
  1071. FROM {db_prefix}topics AS t
  1072. LEFT JOIN {db_prefix}messages AS ma ON (ma.id_topic = t.id_topic AND ma.approved = {int:is_approved})
  1073. WHERE t.id_topic > {int:start}
  1074. AND t.id_topic <= {int:max_id}
  1075. GROUP BY t.id_topic
  1076. HAVING CASE WHEN COUNT(ma.id_msg) >= 1 THEN COUNT(ma.id_msg) - 1 ELSE 0 END != MAX(t.num_replies)',
  1077. array(
  1078. 'is_approved' => 1,
  1079. 'start' => $_REQUEST['start'],
  1080. 'max_id' => $_REQUEST['start'] + $increment,
  1081. )
  1082. );
  1083. while ($row = $smcFunc['db_fetch_assoc']($request))
  1084. $smcFunc['db_query']('', '
  1085. UPDATE {db_prefix}topics
  1086. SET num_replies = {int:num_replies}
  1087. WHERE id_topic = {int:id_topic}',
  1088. array(
  1089. 'num_replies' => $row['real_num_replies'],
  1090. 'id_topic' => $row['id_topic'],
  1091. )
  1092. );
  1093. $smcFunc['db_free_result']($request);
  1094. // Recount unapproved messages
  1095. $request = $smcFunc['db_query']('', '
  1096. SELECT /*!40001 SQL_NO_CACHE */ t.id_topic, MAX(t.unapproved_posts) AS unapproved_posts,
  1097. COUNT(mu.id_msg) AS real_unapproved_posts
  1098. FROM {db_prefix}topics AS t
  1099. LEFT JOIN {db_prefix}messages AS mu ON (mu.id_topic = t.id_topic AND mu.approved = {int:not_approved})
  1100. WHERE t.id_topic > {int:start}
  1101. AND t.id_topic <= {int:max_id}
  1102. GROUP BY t.id_topic
  1103. HAVING COUNT(mu.id_msg) != MAX(t.unapproved_posts)',
  1104. array(
  1105. 'not_approved' => 0,
  1106. 'start' => $_REQUEST['start'],
  1107. 'max_id' => $_REQUEST['start'] + $increment,
  1108. )
  1109. );
  1110. while ($row = $smcFunc['db_fetch_assoc']($request))
  1111. $smcFunc['db_query']('', '
  1112. UPDATE {db_prefix}topics
  1113. SET unapproved_posts = {int:unapproved_posts}
  1114. WHERE id_topic = {int:id_topic}',
  1115. array(
  1116. 'unapproved_posts' => $row['real_unapproved_posts'],
  1117. 'id_topic' => $row['id_topic'],
  1118. )
  1119. );
  1120. $smcFunc['db_free_result']($request);
  1121. $_REQUEST['start'] += $increment;
  1122. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3)
  1123. {
  1124. createToken('admin-boardrecount');
  1125. $context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '" />';
  1126. $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=0;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1127. $context['continue_percent'] = round((100 * $_REQUEST['start'] / $max_topics) / $total_steps);
  1128. return;
  1129. }
  1130. }
  1131. $_REQUEST['start'] = 0;
  1132. }
  1133. // Update the post count of each board.
  1134. if ($_REQUEST['step'] <= 1)
  1135. {
  1136. if (empty($_REQUEST['start']))
  1137. $smcFunc['db_query']('', '
  1138. UPDATE {db_prefix}boards
  1139. SET num_posts = {int:num_posts}
  1140. WHERE redirect = {string:redirect}',
  1141. array(
  1142. 'num_posts' => 0,
  1143. 'redirect' => '',
  1144. )
  1145. );
  1146. while ($_REQUEST['start'] < $max_topics)
  1147. {
  1148. $request = $smcFunc['db_query']('', '
  1149. SELECT /*!40001 SQL_NO_CACHE */ m.id_board, COUNT(*) AS real_num_posts
  1150. FROM {db_prefix}messages AS m
  1151. WHERE m.id_topic > {int:id_topic_min}
  1152. AND m.id_topic <= {int:id_topic_max}
  1153. AND m.approved = {int:is_approved}
  1154. GROUP BY m.id_board',
  1155. array(
  1156. 'id_topic_min' => $_REQUEST['start'],
  1157. 'id_topic_max' => $_REQUEST['start'] + $increment,
  1158. 'is_approved' => 1,
  1159. )
  1160. );
  1161. while ($row = $smcFunc['db_fetch_assoc']($request))
  1162. $smcFunc['db_query']('', '
  1163. UPDATE {db_prefix}boards
  1164. SET num_posts = num_posts + {int:real_num_posts}
  1165. WHERE id_board = {int:id_board}',
  1166. array(
  1167. 'id_board' => $row['id_board'],
  1168. 'real_num_posts' => $row['real_num_posts'],
  1169. )
  1170. );
  1171. $smcFunc['db_free_result']($request);
  1172. $_REQUEST['start'] += $increment;
  1173. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3)
  1174. {
  1175. createToken('admin-boardrecount');
  1176. $context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '" />';
  1177. $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=1;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1178. $context['continue_percent'] = round((200 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
  1179. return;
  1180. }
  1181. }
  1182. $_REQUEST['start'] = 0;
  1183. }
  1184. // Update the topic count of each board.
  1185. if ($_REQUEST['step'] <= 2)
  1186. {
  1187. if (empty($_REQUEST['start']))
  1188. $smcFunc['db_query']('', '
  1189. UPDATE {db_prefix}boards
  1190. SET num_topics = {int:num_topics}',
  1191. array(
  1192. 'num_topics' => 0,
  1193. )
  1194. );
  1195. while ($_REQUEST['start'] < $max_topics)
  1196. {
  1197. $request = $smcFunc['db_query']('', '
  1198. SELECT /*!40001 SQL_NO_CACHE */ t.id_board, COUNT(*) AS real_num_topics
  1199. FROM {db_prefix}topics AS t
  1200. WHERE t.approved = {int:is_approved}
  1201. AND t.id_topic > {int:id_topic_min}
  1202. AND t.id_topic <= {int:id_topic_max}
  1203. GROUP BY t.id_board',
  1204. array(
  1205. 'is_approved' => 1,
  1206. 'id_topic_min' => $_REQUEST['start'],
  1207. 'id_topic_max' => $_REQUEST['start'] + $increment,
  1208. )
  1209. );
  1210. while ($row = $smcFunc['db_fetch_assoc']($request))
  1211. $smcFunc['db_query']('', '
  1212. UPDATE {db_prefix}boards
  1213. SET num_topics = num_topics + {int:real_num_topics}
  1214. WHERE id_board = {int:id_board}',
  1215. array(
  1216. 'id_board' => $row['id_board'],
  1217. 'real_num_topics' => $row['real_num_topics'],
  1218. )
  1219. );
  1220. $smcFunc['db_free_result']($request);
  1221. $_REQUEST['start'] += $increment;
  1222. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3)
  1223. {
  1224. createToken('admin-boardrecount');
  1225. $context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '" />';
  1226. $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=2;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1227. $context['continue_percent'] = round((300 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
  1228. return;
  1229. }
  1230. }
  1231. $_REQUEST['start'] = 0;
  1232. }
  1233. // Update the unapproved post count of each board.
  1234. if ($_REQUEST['step'] <= 3)
  1235. {
  1236. if (empty($_REQUEST['start']))
  1237. $smcFunc['db_query']('', '
  1238. UPDATE {db_prefix}boards
  1239. SET unapproved_posts = {int:unapproved_posts}',
  1240. array(
  1241. 'unapproved_posts' => 0,
  1242. )
  1243. );
  1244. while ($_REQUEST['start'] < $max_topics)
  1245. {
  1246. $request = $smcFunc['db_query']('', '
  1247. SELECT /*!40001 SQL_NO_CACHE */ m.id_board, COUNT(*) AS real_unapproved_posts
  1248. FROM {db_prefix}messages AS m
  1249. WHERE m.id_topic > {int:id_topic_min}
  1250. AND m.id_topic <= {int:id_topic_max}
  1251. AND m.approved = {int:is_approved}
  1252. GROUP BY m.id_board',
  1253. array(
  1254. 'id_topic_min' => $_REQUEST['start'],
  1255. 'id_topic_max' => $_REQUEST['start'] + $increment,
  1256. 'is_approved' => 0,
  1257. )
  1258. );
  1259. while ($row = $smcFunc['db_fetch_assoc']($request))
  1260. $smcFunc['db_query']('', '
  1261. UPDATE {db_prefix}boards
  1262. SET unapproved_posts = unapproved_posts + {int:unapproved_posts}
  1263. WHERE id_board = {int:id_board}',
  1264. array(
  1265. 'id_board' => $row['id_board'],
  1266. 'unapproved_posts' => $row['real_unapproved_posts'],
  1267. )
  1268. );
  1269. $smcFunc['db_free_result']($request);
  1270. $_REQUEST['start'] += $increment;
  1271. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3)
  1272. {
  1273. createToken('admin-boardrecount');
  1274. $context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '" />';
  1275. $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=3;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1276. $context['continue_percent'] = round((400 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
  1277. return;
  1278. }
  1279. }
  1280. $_REQUEST['start'] = 0;
  1281. }
  1282. // Update the unapproved topic count of each board.
  1283. if ($_REQUEST['step'] <= 4)
  1284. {
  1285. if (empty($_REQUEST['start']))
  1286. $smcFunc['db_query']('', '
  1287. UPDATE {db_prefix}boards
  1288. SET unapproved_topics = {int:unapproved_topics}',
  1289. array(
  1290. 'unapproved_topics' => 0,
  1291. )
  1292. );
  1293. while ($_REQUEST['start'] < $max_topics)
  1294. {
  1295. $request = $smcFunc['db_query']('', '
  1296. SELECT /*!40001 SQL_NO_CACHE */ t.id_board, COUNT(*) AS real_unapproved_topics
  1297. FROM {db_prefix}topics AS t
  1298. WHERE t.approved = {int:is_approved}
  1299. AND t.id_topic > {int:id_topic_min}
  1300. AND t.id_topic <= {int:id_topic_max}
  1301. GROUP BY t.id_board',
  1302. array(
  1303. 'is_approved' => 0,
  1304. 'id_topic_min' => $_REQUEST['start'],
  1305. 'id_topic_max' => $_REQUEST['start'] + $increment,
  1306. )
  1307. );
  1308. while ($row = $smcFunc['db_fetch_assoc']($request))
  1309. $smcFunc['db_query']('', '
  1310. UPDATE {db_prefix}boards
  1311. SET unapproved_topics = unapproved_topics + {int:real_unapproved_topics}
  1312. WHERE id_board = {int:id_board}',
  1313. array(
  1314. 'id_board' => $row['id_board'],
  1315. 'real_unapproved_topics' => $row['real_unapproved_topics'],
  1316. )
  1317. );
  1318. $smcFunc['db_free_result']($request);
  1319. $_REQUEST['start'] += $increment;
  1320. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3)
  1321. {
  1322. createToken('admin-boardrecount');
  1323. $context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '" />';
  1324. $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=4;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1325. $context['continue_percent'] = round((500 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
  1326. return;
  1327. }
  1328. }
  1329. $_REQUEST['start'] = 0;
  1330. }
  1331. // Get all members with wrong number of personal messages.
  1332. if ($_REQUEST['step'] <= 5)
  1333. {
  1334. $request = $smcFunc['db_query']('', '
  1335. SELECT /*!40001 SQL_NO_CACHE */ mem.id_member, COUNT(pmr.id_pm) AS real_num,
  1336. MAX(mem.instant_messages) AS instant_messages
  1337. FROM {db_prefix}members AS mem
  1338. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (mem.id_member = pmr.id_member AND pmr.deleted = {int:is_not_deleted})
  1339. GROUP BY mem.id_member
  1340. HAVING COUNT(pmr.id_pm) != MAX(mem.instant_messages)',
  1341. array(
  1342. 'is_not_deleted' => 0,
  1343. )
  1344. );
  1345. while ($row = $smcFunc['db_fetch_assoc']($request))
  1346. updateMemberData($row['id_member'], array('instant_messages' => $row['real_num']));
  1347. $smcFunc['db_free_result']($request);
  1348. $request = $smcFunc['db_query']('', '
  1349. SELECT /*!40001 SQL_NO_CACHE */ mem.id_member, COUNT(pmr.id_pm) AS real_num,
  1350. MAX(mem.unread_messages) AS unread_messages
  1351. FROM {db_prefix}members AS mem
  1352. LEFT JOIN {db_prefix}pm_recipients AS pmr ON (mem.id_member = pmr.id_member AND pmr.deleted = {int:is_not_deleted} AND pmr.is_read = {int:is_not_read})
  1353. GROUP BY mem.id_member
  1354. HAVING COUNT(pmr.id_pm) != MAX(mem.unread_messages)',
  1355. array(
  1356. 'is_not_deleted' => 0,
  1357. 'is_not_read' => 0,
  1358. )
  1359. );
  1360. while ($row = $smcFunc['db_fetch_assoc']($request))
  1361. updateMemberData($row['id_member'], array('unread_messages' => $row['real_num']));
  1362. $smcFunc['db_free_result']($request);
  1363. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3)
  1364. {
  1365. createToken('admin-boardrecount');
  1366. $context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '" />';
  1367. $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=6;start=0;' . $context['session_var'] . '=' . $context['session_id'];
  1368. $context['continue_percent'] = round(700 / $total_steps);
  1369. return;
  1370. }
  1371. }
  1372. // Any messages pointing to the wrong board?
  1373. if ($_REQUEST['step'] <= 6)
  1374. {
  1375. while ($_REQUEST['start'] < $modSettings['maxMsgID'])
  1376. {
  1377. $request = $smcFunc['db_query']('', '
  1378. SELECT /*!40001 SQL_NO_CACHE */ t.id_board, m.id_msg
  1379. FROM {db_prefix}messages AS m
  1380. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic AND t.id_board != m.id_board)
  1381. WHERE m.id_msg > {int:id_msg_min}
  1382. AND m.id_msg <= {int:id_msg_max}',
  1383. array(
  1384. 'id_msg_min' => $_REQUEST['start'],
  1385. 'id_msg_max' => $_REQUEST['start'] + $increment,
  1386. )
  1387. );
  1388. $boards = array();
  1389. while ($row = $smcFunc['db_fetch_assoc']($request))
  1390. $boards[$row['id_board']][] = $row['id_msg'];
  1391. $smcFunc['db_free_result']($request);
  1392. foreach ($boards as $board_id => $messages)
  1393. $smcFunc['db_query']('', '
  1394. UPDATE {db_prefix}messages
  1395. SET id_board = {int:id_board}
  1396. WHERE id_msg IN ({array_int:id_msg_array})',
  1397. array(
  1398. 'id_msg_array' => $messages,
  1399. 'id_board' => $board_id,
  1400. )
  1401. );
  1402. $_REQUEST['start'] += $increment;
  1403. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3)
  1404. {
  1405. createToken('admin-boardrecount');
  1406. $context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '" />';
  1407. $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=6;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1408. $context['continue_percent'] = round((700 + 100 * $_REQUEST['start'] / $modSettings['maxMsgID']) / $total_steps);
  1409. return;
  1410. }
  1411. }
  1412. $_REQUEST['start'] = 0;
  1413. }
  1414. // Update the latest message of each board.
  1415. $request = $smcFunc['db_query']('', '
  1416. SELECT m.id_board, MAX(m.id_msg) AS local_last_msg
  1417. FROM {db_prefix}messages AS m
  1418. WHERE m.approved = {int:is_approved}
  1419. GROUP BY m.id_board',
  1420. array(
  1421. 'is_approved' => 1,
  1422. )
  1423. );
  1424. $realBoardCounts = array();
  1425. while ($row = $smcFunc['db_fetch_assoc']($request))
  1426. $realBoardCounts[$row['id_board']] = $row['local_last_msg'];
  1427. $smcFunc['db_free_result']($request);
  1428. $request = $smcFunc['db_query']('', '
  1429. SELECT /*!40001 SQL_NO_CACHE */ id_board, id_parent, id_last_msg, child_level, id_msg_updated
  1430. FROM {db_prefix}boards',
  1431. array(
  1432. )
  1433. );
  1434. $resort_me = array();
  1435. while ($row = $smcFunc['db_fetch_assoc']($request))
  1436. {
  1437. $row['local_last_msg'] = isset($realBoardCounts[$row['id_board']]) ? $realBoardCounts[$row['id_board']] : 0;
  1438. $resort_me[$row['child_level']][] = $row;
  1439. }
  1440. $smcFunc['db_free_result']($request);
  1441. krsort($resort_me);
  1442. $lastModifiedMsg = array();
  1443. foreach ($resort_me as $rows)
  1444. foreach ($rows as $row)
  1445. {
  1446. // The latest message is the latest of the current board and its children.
  1447. if (isset($lastModifiedMsg[$row['id_board']]))
  1448. $curLastModifiedMsg = max($row['local_last_msg'], $lastModifiedMsg[$row['id_board']]);
  1449. else
  1450. $curLastModifiedMsg = $row['local_last_msg'];
  1451. // If what is and what should be the latest message differ, an update is necessary.
  1452. if ($row['local_last_msg'] != $row['id_last_msg'] || $curLastModifiedMsg != $row['id_msg_updated'])
  1453. $smcFunc['db_query']('', '
  1454. UPDATE {db_prefix}boards
  1455. SET id_last_msg = {int:id_last_msg}, id_msg_updated = {int:id_msg_updated}
  1456. WHERE id_board = {int:id_board}',
  1457. array(
  1458. 'id_last_msg' => $row['local_last_msg'],
  1459. 'id_msg_updated' => $curLastModifiedMsg,
  1460. 'id_board' => $row['id_board'],
  1461. )
  1462. );
  1463. // Parent boards inherit the latest modified message of their children.
  1464. if (isset($lastModifiedMsg[$row['id_parent']]))
  1465. $lastModifiedMsg[$row['id_parent']] = max($row['local_last_msg'], $lastModifiedMsg[$row['id_parent']]);
  1466. else
  1467. $lastModifiedMsg[$row['id_parent']] = $row['local_last_msg'];
  1468. }
  1469. // Update all the basic statistics.
  1470. updateStats('member');
  1471. updateStats('message');
  1472. updateStats('topic');
  1473. // Finally, update the latest event times.
  1474. require_once($sourcedir . '/ScheduledTasks.php');
  1475. CalculateNextTrigger();
  1476. redirectexit('action=admin;area=maintain;sa=routine;done=recount');
  1477. }
  1478. /**
  1479. * Perform a detailed version check. A very good thing ;).
  1480. * The function parses the comment headers in all files for their version information,
  1481. * and outputs that for some javascript to check with simplemachines.org.
  1482. * It does not connect directly with simplemachines.org, but rather expects the client to.
  1483. *
  1484. * It requires the admin_forum permission.
  1485. * Uses the view_versions admin area.
  1486. * Accessed through ?action=admin;area=maintain;sa=routine;activity=version.
  1487. * @uses Admin template, view_versions sub-template.
  1488. */
  1489. function VersionDetail()
  1490. {
  1491. global $forum_version, $txt, $sourcedir, $context;
  1492. isAllowedTo('admin_forum');
  1493. // Call the function that'll get all the version info we need.
  1494. require_once($sourcedir . '/Subs-Admin.php');
  1495. $versionOptions = array(
  1496. 'include_ssi' => true,
  1497. 'include_subscriptions' => true,
  1498. 'sort_results' => true,
  1499. );
  1500. $version_info = getFileVersions($versionOptions);
  1501. // Add the new info to the template context.
  1502. $context += array(
  1503. 'file_versions' => $version_info['file_versions'],
  1504. 'default_template_versions' => $version_info['default_template_versions'],
  1505. 'template_versions' => $version_info['template_versions'],
  1506. 'default_language_versions' => $version_info['default_language_versions'],
  1507. 'default_known_languages' => array_keys($version_info['default_language_versions']),
  1508. );
  1509. // Make it easier to manage for the template.
  1510. $context['forum_version'] = $forum_version;
  1511. $context['sub_template'] = 'view_versions';
  1512. $context['page_title'] = $txt['admin_version_check'];
  1513. }
  1514. /**
  1515. * Re-attribute posts.
  1516. */
  1517. function MaintainReattributePosts()
  1518. {
  1519. global $sourcedir, $context, $txt;
  1520. checkSession();
  1521. // Find the member.
  1522. require_once($sourcedir . '/Subs-Auth.php');
  1523. $members = findMembers($_POST['to']);
  1524. if (empty($members))
  1525. fatal_lang_error('reattribute_cannot_find_member');
  1526. $memID = array_shift($members);
  1527. $memID = $memID['id'];
  1528. $email = $_POST['type'] == 'email' ? $_POST['from_email'] : '';
  1529. $membername = $_POST['type'] == 'name' ? $_POST['from_name'] : '';
  1530. // Now call the reattribute function.
  1531. require_once($sourcedir . '/Subs-Members.php');
  1532. reattributePosts($memID, $email, $membername, !empty($_POST['posts']));
  1533. $context['maintenance_finished'] = $txt['maintain_reattribute_posts'];
  1534. }
  1535. /**
  1536. * Handling function for the backup stuff.
  1537. */
  1538. function MaintainDownloadBackup()
  1539. {
  1540. global $sourcedir;
  1541. validateToken('admin-maint');
  1542. require_once($sourcedir . '/DumpDatabase.php');
  1543. DumpDatabase2();
  1544. }
  1545. /**
  1546. * Removing old members. Done and out!
  1547. * @todo refactor
  1548. */
  1549. function MaintainPurgeInactiveMembers()
  1550. {
  1551. global $sourcedir, $context, $smcFunc, $txt;
  1552. $_POST['maxdays'] = empty($_POST['maxdays']) ? 0 : (int) $_POST['maxdays'];
  1553. if (!empty($_POST['groups']) && $_POST['maxdays'] > 0)
  1554. {
  1555. checkSession();
  1556. validateToken('admin-maint');
  1557. $groups = array();
  1558. foreach ($_POST['groups'] as $id => $dummy)
  1559. $groups[] = (int) $id;
  1560. $time_limit = (time() - ($_POST['maxdays'] * 24 * 3600));
  1561. $where_vars = array(
  1562. 'time_limit' => $time_limit,
  1563. );
  1564. if ($_POST['del_type'] == 'activated')
  1565. {
  1566. $where = 'mem.date_registered < {int:time_limit} AND mem.is_activated = {int:is_activated}';
  1567. $where_vars['is_activated'] = 0;
  1568. }
  1569. else
  1570. $where = 'mem.last_login < {int:time_limit} AND (mem.last_login != 0 OR mem.date_registered < {int:time_limit})';
  1571. // Need to get *all* groups then work out which (if any) we avoid.
  1572. $request = $smcFunc['db_query']('', '
  1573. SELECT id_group, group_name, min_posts
  1574. FROM {db_prefix}membergroups',
  1575. array(
  1576. )
  1577. );
  1578. while ($row = $smcFunc['db_fetch_assoc']($request))
  1579. {
  1580. // Avoid this one?
  1581. if (!in_array($row['id_group'], $groups))
  1582. {
  1583. // Post group?
  1584. if ($row['min_posts'] != -1)
  1585. {
  1586. $where .= ' AND mem.id_post_group != {int:id_post_group_' . $row['id_group'] . '}';
  1587. $where_vars['id_post_group_' . $row['id_group']] = $row['id_group'];
  1588. }
  1589. else
  1590. {
  1591. $where .= ' AND mem.id_group != {int:id_group_' . $row['id_group'] . '} AND FIND_IN_SET({int:id_group_' . $row['id_group'] . '}, mem.additional_groups) = 0';
  1592. $where_vars['id_group_' . $row['id_group']] = $row['id_group'];
  1593. }
  1594. }
  1595. }
  1596. $smcFunc['db_free_result']($request);
  1597. // If we have ungrouped unselected we need to avoid those guys.
  1598. if (!in_array(0, $groups))
  1599. {
  1600. $where .= ' AND (mem.id_group != 0 OR mem.additional_groups != {string:blank_add_groups})';
  1601. $where_vars['blank_add_groups'] = '';
  1602. }
  1603. // Select all the members we're about to murder/remove...
  1604. $request = $smcFunc['db_query']('', '
  1605. SELECT mem.id_member, IFNULL(m.id_member, 0) AS is_mod
  1606. FROM {db_prefix}members AS mem
  1607. LEFT JOIN {db_prefix}moderators AS m ON (m.id_member = mem.id_member)
  1608. WHERE ' . $where,
  1609. $where_vars
  1610. );
  1611. $members = array();
  1612. while ($row = $smcFunc['db_fetch_assoc']($request))
  1613. {
  1614. if (!$row['is_mod'] || !in_array(3, $groups))
  1615. $members[] = $row['id_member'];
  1616. }
  1617. $smcFunc['db_free_result']($request);
  1618. require_once($sourcedir . '/Subs-Members.php');
  1619. deleteMembers($members);
  1620. }
  1621. $context['maintenance_finished'] = $txt['maintain_members'];
  1622. createToken('admin-maint');
  1623. }
  1624. /**
  1625. * Removing old posts doesn't take much as we really pass through.
  1626. */
  1627. function MaintainRemoveOldPosts()
  1628. {
  1629. global $sourcedir, $context, $txt;
  1630. validateToken('admin-maint');
  1631. // Actually do what we're told!
  1632. require_once($sourcedir . '/RemoveTopic.php');
  1633. RemoveOldTopics2();
  1634. }
  1635. /**
  1636. * Moves topics from one board to another.
  1637. *
  1638. * @uses not_done template to pause the process.
  1639. */
  1640. function MaintainMassMoveTopics()
  1641. {
  1642. global $smcFunc, $sourcedir, $context, $txt;
  1643. // Only admins.
  1644. isAllowedTo('admin_forum');
  1645. checkSession('request');
  1646. validateToken('admin-maint');
  1647. // Set up to the context.
  1648. $context['page_title'] = $txt['not_done_title'];
  1649. $context['continue_countdown'] = 3;
  1650. $context['continue_post_data'] = '';
  1651. $context['continue_get_data'] = '';
  1652. $context['sub_template'] = 'not_done';
  1653. $context['start'] = empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'];
  1654. $context['start_time'] = time();
  1655. // First time we do this?
  1656. $id_board_from = isset($_POST['id_board_from']) ? (int) $_POST['id_board_from'] : (int) $_REQUEST['id_board_from'];
  1657. $id_board_to = isset($_POST['id_board_to']) ? (int) $_POST['id_board_to'] : (int) $_REQUEST['id_board_to'];
  1658. // No boards then this is your stop.
  1659. if (empty($id_board_from) || empty($id_board_to))
  1660. return;
  1661. // How many topics are we converting?
  1662. if (!isset($_REQUEST['totaltopics']))
  1663. {
  1664. $request = $smcFunc['db_query']('', '
  1665. SELECT COUNT(*)
  1666. FROM {db_prefix}topics
  1667. WHERE id_board = {int:id_board_from}',
  1668. array(
  1669. 'id_board_from' => $id_board_from,
  1670. )
  1671. );
  1672. list ($total_topics) = $smcFunc['db_fetch_row']($request);
  1673. $smcFunc['db_free_result']($request);
  1674. }
  1675. else
  1676. $total_topics = (int) $_REQUEST['totaltopics'];
  1677. // Seems like we need this here.
  1678. $context['continue_get_data'] = '?action=admin;area=maintain;sa=topics;activity=massmove;id_board_from=' . $id_board_from . ';id_board_to=' . $id_board_to . ';totaltopics=' . $total_topics . ';start=' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1679. // We have topics to move so start the process.
  1680. if (!empty($total_topics))
  1681. {
  1682. while ($context['start'] <= $total_topics)
  1683. {
  1684. // Lets get the topics.
  1685. $request = $smcFunc['db_query']('', '
  1686. SELECT id_topic
  1687. FROM {db_prefix}topics
  1688. WHERE id_board = {int:id_board_from}
  1689. LIMIT 10',
  1690. array(
  1691. 'id_board_from' => $id_board_from,
  1692. )
  1693. );
  1694. // Get the ids.
  1695. $topics = array();
  1696. while ($row = $smcFunc['db_fetch_assoc']($request))
  1697. $topics[] = $row['id_topic'];
  1698. // Just return if we don't have any topics left to move.
  1699. if (empty($topics))
  1700. {
  1701. cache_put_data('board-' . $id_board_from, null, 120);
  1702. cache_put_data('board-' . $id_board_to, null, 120);
  1703. redirectexit('action=admin;area=maintain;sa=topics;done=massmove');
  1704. }
  1705. // Lets move them.
  1706. require_once($sourcedir . '/MoveTopic.php');
  1707. moveTopics($topics, $id_board_to);
  1708. // We've done at least ten more topics.
  1709. $context['start'] += 10;
  1710. // Lets wait a while.
  1711. if (time() - $context['start_time'] > 3)
  1712. {
  1713. // What's the percent?
  1714. $context['continue_percent'] = round(100 * ($context['start'] / $total_topics), 1);
  1715. $context['continue_get_data'] = '?action=admin;area=maintain;sa=topics;activity=massmove;id_board_from=' . $id_board_from . ';id_board_to=' . $id_board_to . ';totaltopics=' . $total_topics . ';start=' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1716. // Let the template system do it's thang.
  1717. return;
  1718. }
  1719. }
  1720. }
  1721. // Don't confuse admins by having an out of date cache.
  1722. cache_put_data('board-' . $id_board_from, null, 120);
  1723. cache_put_data('board-' . $id_board_to, null, 120);
  1724. redirectexit('action=admin;area=maintain;sa=topics;done=massmove');
  1725. }
  1726. /**
  1727. * Recalculate all members post counts
  1728. * it requires the admin_forum permission.
  1729. *
  1730. * - recounts all posts for members found in the message table
  1731. * - updates the members post count record in the members talbe
  1732. * - honors the boards post count flag
  1733. * - does not count posts in the recyle bin
  1734. * - zeros post counts for all members with no posts in the message table
  1735. * - runs as a delayed loop to avoid server overload
  1736. * - uses the not_done template in Admin.template
  1737. *
  1738. * The function redirects back to action=admin;area=maintain;sa=members when complete.
  1739. * It is accessed via ?action=admin;area=maintain;sa=members;activity=recountposts
  1740. */
  1741. function MaintainRecountPosts()
  1742. {
  1743. global $txt, $context, $modSettings, $smcFunc;
  1744. // You have to be allowed in here
  1745. isAllowedTo('admin_forum');
  1746. checkSession('request');
  1747. // Set up to the context.
  1748. $context['page_title'] = $txt['not_done_title'];
  1749. $context['continue_countdown'] = 3;
  1750. $context['continue_get_data'] = '';
  1751. $context['sub_template'] = 'not_done';
  1752. // init
  1753. $increment = 200;
  1754. $_REQUEST['start'] = !isset($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'];
  1755. // Ask for some extra time, on big boards this may take a bit
  1756. @set_time_limit(600);
  1757. // Only run this query if we don't have the total number of members that have posted
  1758. if (!isset($_SESSION['total_members']))
  1759. {
  1760. validateToken('admin-maint');
  1761. $request = $smcFunc['db_query']('', '
  1762. SELECT COUNT(DISTINCT m.id_member)
  1763. FROM ({db_prefix}messages AS m, {db_prefix}boards AS b)
  1764. WHERE m.id_member != 0
  1765. AND b.count_posts = 0
  1766. AND m.id_board = b.id_board',
  1767. array(
  1768. )
  1769. );
  1770. // save it so we don't do this again for this task
  1771. list ($_SESSION['total_members']) = $smcFunc['db_fetch_row']($request);
  1772. $smcFunc['db_free_result']($request);
  1773. }
  1774. else
  1775. validateToken('admin-recountposts');
  1776. // Lets get a group of members and determine their post count (from the boards that have post count enabled of course).
  1777. $request = $smcFunc['db_query']('', '
  1778. SELECT /*!40001 SQL_NO_CACHE */ m.id_member, COUNT(m.id_member) AS posts
  1779. FROM ({db_prefix}messages AS m, {db_prefix}boards AS b)
  1780. WHERE m.id_member != {int:zero}
  1781. AND b.count_posts = {int:zero}
  1782. AND m.id_board = b.id_board ' . (!empty($modSettings['recycle_enable']) ? '
  1783. AND b.id_board != {int:recycle}' : '') . '
  1784. GROUP BY m.id_member
  1785. LIMIT {int:start}, {int:number}',
  1786. array(
  1787. 'start' => $_REQUEST['start'],
  1788. 'number' => $increment,
  1789. 'recycle' => $modSettings['recycle_board'],
  1790. 'zero' => 0,
  1791. )
  1792. );
  1793. $total_rows = $smcFunc['db_num_rows']($request);
  1794. // Update the post count for this group
  1795. while ($row = $smcFunc['db_fetch_assoc']($request))
  1796. {
  1797. $smcFunc['db_query']('', '
  1798. UPDATE {db_prefix}members
  1799. SET posts = {int:posts}
  1800. WHERE id_member = {int:row}',
  1801. array(
  1802. 'row' => $row['id_member'],
  1803. 'posts' => $row['posts'],
  1804. )
  1805. );
  1806. }
  1807. $smcFunc['db_free_result']($request);
  1808. // Continue?
  1809. if ($total_rows == $increment)
  1810. {
  1811. $_REQUEST['start'] += $increment;
  1812. $context['continue_get_data'] = '?action=admin;area=maintain;sa=members;activity=recountposts;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1813. $context['continue_percent'] = round(100 * $_REQUEST['start'] / $_SESSION['total_members']);
  1814. createToken('admin-recountposts');
  1815. $context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-recountposts_token_var'] . '" value="' . $context['admin-recountposts_token'] . '" />';
  1816. if (function_exists('apache_reset_timeout'))
  1817. apache_reset_timeout();
  1818. return;
  1819. }
  1820. // final steps ... made more difficult since we don't yet support sub-selects on joins
  1821. // place all members who have posts in the message table in a temp table
  1822. $createTemporary = $smcFunc['db_query']('', '
  1823. CREATE TEMPORARY TABLE {db_prefix}tmp_maint_recountposts (
  1824. id_member mediumint(8) unsigned NOT NULL default {string:string_zero},
  1825. PRIMARY KEY (id_member)
  1826. )
  1827. SELECT m.id_member
  1828. FROM ({db_prefix}messages AS m,{db_prefix}boards AS b)
  1829. WHERE m.id_member != {int:zero}
  1830. AND b.count_posts = {int:zero}
  1831. AND m.id_board = b.id_board ' . (!empty($modSettings['recycle_enable']) ? '
  1832. AND b.id_board != {int:recycle}' : '') . '
  1833. GROUP BY m.id_member',
  1834. array(
  1835. 'zero' => 0,
  1836. 'string_zero' => '0',
  1837. 'db_error_skip' => true,
  1838. )
  1839. ) !== false;
  1840. if ($createTemporary)
  1841. {
  1842. // outer join the members table on the temporary table finding the members that have a post count but no posts in the message table
  1843. $request = $smcFunc['db_query']('', '
  1844. SELECT mem.id_member, mem.posts
  1845. FROM {db_prefix}members AS mem
  1846. LEFT OUTER JOIN {db_prefix}tmp_maint_recountposts AS res
  1847. ON res.id_member = mem.id_member
  1848. WHERE res.id_member IS null
  1849. AND mem.posts != {int:zero}',
  1850. array(
  1851. 'zero' => 0,
  1852. )
  1853. );
  1854. // set the post count to zero for any delinquents we may have found
  1855. while ($row = $smcFunc['db_fetch_assoc']($request))
  1856. {
  1857. $smcFunc['db_query']('', '
  1858. UPDATE {db_prefix}members
  1859. SET posts = {int:zero}
  1860. WHERE id_member = {int:row}',
  1861. array(
  1862. 'row' => $row['id_member'],
  1863. 'zero' => 0,
  1864. )
  1865. );
  1866. }
  1867. $smcFunc['db_free_result']($request);
  1868. }
  1869. // all done
  1870. unset($_SESSION['total_members']);
  1871. $context['maintenance_finished'] = $txt['maintain_recountposts'];
  1872. redirectexit('action=admin;area=maintain;sa=members;done=recountposts');
  1873. }
  1874. ?>