ManageMaintenance.php 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616
  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 2014 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>
  276. <html', $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, $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 disabling 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\'] . (!empty($data[\'instance\']) ? \'<br>\'. $txt[\'hooks_field_function_method\'] : \'\');
  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, $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. <span class="generic_icons delete" title="\' . $txt[\'hooks_button_remove\'] . \'"></span>
  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 children 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. $object = false;
  2103. if (strpos($function_o, '#') !== false)
  2104. {
  2105. $function_o = str_replace('#', '', $function_o);
  2106. $object = true;
  2107. }
  2108. $hook_name = str_replace(']', '', $function_o);
  2109. if (strpos($hook_name, '::') !== false)
  2110. {
  2111. $function = explode('::', $hook_name);
  2112. $function = $function[1];
  2113. }
  2114. else
  2115. $function = $hook_name;
  2116. $function = explode(':', $function);
  2117. $function = $function[0];
  2118. if (substr($hook, -8) === '_include')
  2119. {
  2120. $hook_status[$hook][$function]['exists'] = file_exists(strtr(trim($function), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir, '$themedir' => $settings['theme_dir'])));
  2121. // I need to know if there is at least one function called in this file.
  2122. $temp_data['include'][basename($function)] = array('hook' => $hook, 'function' => $function);
  2123. unset($temp_hooks[$hook][$function_o]);
  2124. }
  2125. elseif (strpos(str_replace(' (', '(', $fc), 'function ' . trim($function) . '(') !== false)
  2126. {
  2127. $hook_status[$hook][$function]['exists'] = true;
  2128. $hook_status[$hook][$function]['in_file'] = $file['name'];
  2129. $hook_status[$hook][$function]['instance'] = $object;
  2130. // 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)
  2131. $temp_data['function'][$file['name']][] = $function_o;
  2132. unset($temp_hooks[$hook][$function_o]);
  2133. }
  2134. }
  2135. }
  2136. }
  2137. }
  2138. }
  2139. $sort_types = array(
  2140. 'hook_name' => array('hook', SORT_ASC),
  2141. 'hook_name DESC' => array('hook', SORT_DESC),
  2142. 'function_name' => array('function', SORT_ASC),
  2143. 'function_name DESC' => array('function', SORT_DESC),
  2144. 'file_name' => array('file_name', SORT_ASC),
  2145. 'file_name DESC' => array('file_name', SORT_DESC),
  2146. 'status' => array('status', SORT_ASC),
  2147. 'status DESC' => array('status', SORT_DESC),
  2148. );
  2149. $sort_options = $sort_types[$sort];
  2150. $sort = array();
  2151. $hooks_filters = array();
  2152. foreach ($hooks as $hook => $functions)
  2153. {
  2154. $hooks_filters[] = '<option ' . ($context['current_filter'] == $hook ? 'selected="selected" ' : '') . ' value="' . $hook . '">' . $hook . '</option>';
  2155. foreach ($functions as $function)
  2156. {
  2157. $enabled = strstr($function, ']') === false;
  2158. $function = str_replace(']', '', $function);
  2159. // 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)
  2160. if (substr($hook, -8) !== '_include' && isset($hook_status[$hook][$function]['in_file']))
  2161. {
  2162. $current_hook = isset($temp_data['include'][$hook_status[$hook][$function]['in_file']]) ? $temp_data['include'][$hook_status[$hook][$function]['in_file']] : '';
  2163. $enabled = false;
  2164. // Checking all the functions within this particular file
  2165. // if any of them is enable then the file *must* be included and the integrate_*_include hook cannot be disabled
  2166. foreach ($temp_data['function'][$hook_status[$hook][$function]['in_file']] as $func)
  2167. $enabled = $enabled || strstr($func, ']') !== false;
  2168. if (!$enabled && !empty($current_hook))
  2169. $hook_status[$current_hook['hook']][$current_hook['function']]['enabled'] = true;
  2170. }
  2171. }
  2172. }
  2173. if (!empty($hooks_filters))
  2174. $context['insert_after_template'] .= '
  2175. <script><!-- // --><![CDATA[
  2176. var hook_name_header = document.getElementById(\'header_list_integration_hooks_hook_name\');
  2177. 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>'). ';
  2178. // ]]></script>';
  2179. $temp_data = array();
  2180. $id = 0;
  2181. foreach ($hooks as $hook => $functions)
  2182. {
  2183. if (empty($context['filter']) || (!empty($context['filter']) && $context['filter'] == $hook))
  2184. {
  2185. foreach ($functions as $function)
  2186. {
  2187. // Gotta remove the # bit.
  2188. if (strpos($function, '#') !== false)
  2189. $function = str_replace('#', '', $function);
  2190. $enabled = strstr($function, ']') === false;
  2191. $function = str_replace(']', '', $function);
  2192. if (strpos($function, '::') !== false)
  2193. {
  2194. $function = explode('::', $function);
  2195. $function = $function[1];
  2196. }
  2197. $exploded = explode(':', $function);
  2198. $hook_exists = !empty($hook_status[$hook][$exploded[0]]['exists']);
  2199. $file_name = isset($hook_status[$hook][$exploded[0]]['in_file']) ? $hook_status[$hook][$exploded[0]]['in_file'] : ((substr($hook, -8) === '_include') ? 'zzzzzzzzz' : 'zzzzzzzza');
  2200. $sort[] = $$sort_options[0];
  2201. $temp_data[] = array(
  2202. 'id' => 'hookid_' . $id++,
  2203. 'hook_name' => $hook,
  2204. 'function_name' => $function,
  2205. 'real_function' => $exploded[0],
  2206. 'included_file' => isset($exploded[1]) ? strtr(trim($exploded[1]), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir, '$themedir' => $settings['theme_dir'])) : '',
  2207. 'file_name' => (isset($hook_status[$hook][$exploded[0]]['in_file']) ? $hook_status[$hook][$exploded[0]]['in_file'] : ''),
  2208. 'instance' => (isset($hook_status[$hook][$exploded[0]]['instance']) ? $hook_status[$hook][$exploded[0]]['instance'] : ''),
  2209. 'hook_exists' => $hook_exists,
  2210. 'status' => $hook_exists ? ($enabled ? 'allow' : 'moderate') : 'deny',
  2211. 'img_text' => $txt['hooks_' . ($hook_exists ? ($enabled ? 'active' : 'disabled') : 'missing')],
  2212. 'enabled' => $enabled,
  2213. 'can_be_disabled' => !isset($hook_status[$hook][$function]['enabled']),
  2214. );
  2215. }
  2216. }
  2217. }
  2218. array_multisort($sort, $sort_options[1], $temp_data);
  2219. $counter = 0;
  2220. $start++;
  2221. foreach ($temp_data as $data)
  2222. {
  2223. if (++$counter < $start)
  2224. continue;
  2225. elseif ($counter == $start + $per_page)
  2226. break;
  2227. $hooks_data[] = $data;
  2228. }
  2229. return $hooks_data;
  2230. }
  2231. /**
  2232. * Simply returns the total count of integration hooks
  2233. * Used by the integration hooks list function (list_integration_hooks)
  2234. *
  2235. * @global type $context
  2236. * @return int
  2237. */
  2238. function get_integration_hooks_count()
  2239. {
  2240. global $context;
  2241. $hooks = get_integration_hooks();
  2242. $hooks_count = 0;
  2243. $context['filter'] = false;
  2244. if (isset($_GET['filter']))
  2245. $context['filter'] = $_GET['filter'];
  2246. foreach ($hooks as $hook => $functions)
  2247. {
  2248. if (empty($context['filter']) || (!empty($context['filter']) && $context['filter'] == $hook))
  2249. $hooks_count += count($functions);
  2250. }
  2251. return $hooks_count;
  2252. }
  2253. /**
  2254. * Parses modSettings to create integration hook array
  2255. *
  2256. * @staticvar type $integration_hooks
  2257. * @return type
  2258. */
  2259. function get_integration_hooks()
  2260. {
  2261. global $modSettings;
  2262. static $integration_hooks;
  2263. if (!isset($integration_hooks))
  2264. {
  2265. $integration_hooks = array();
  2266. foreach ($modSettings as $key => $value)
  2267. {
  2268. if (!empty($value) && substr($key, 0, 10) === 'integrate_')
  2269. $integration_hooks[$key] = explode(',', $value);
  2270. }
  2271. }
  2272. return $integration_hooks;
  2273. }
  2274. ?>