ManageMaintenance.php 85 KB

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