ManageMaintenance.php 73 KB

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