ManageMaintenance.php 73 KB

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