2
0

ManageMaintenance.php 86 KB

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