ScheduledTasks.php 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611
  1. <?php
  2. /**
  3. * This file is automatically called and handles all manner of scheduled things.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2011 Simple Machines
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.1 Alpha 1
  13. */
  14. if (!defined('SMF'))
  15. die('Hacking attempt...');
  16. // This function works out what to do!
  17. function AutoTask()
  18. {
  19. global $time_start, $modSettings, $smcFunc;
  20. // Special case for doing the mail queue.
  21. if (isset($_GET['scheduled']) && $_GET['scheduled'] == 'mailq')
  22. ReduceMailQueue();
  23. else
  24. {
  25. // Select the next task to do.
  26. $request = $smcFunc['db_query']('', '
  27. SELECT id_task, task, next_time, time_offset, time_regularity, time_unit
  28. FROM {db_prefix}scheduled_tasks
  29. WHERE disabled = {int:not_disabled}
  30. AND next_time <= {int:current_time}
  31. ORDER BY next_time ASC
  32. LIMIT 1',
  33. array(
  34. 'not_disabled' => 0,
  35. 'current_time' => time(),
  36. )
  37. );
  38. if ($smcFunc['db_num_rows']($request) != 0)
  39. {
  40. // The two important things really...
  41. $row = $smcFunc['db_fetch_assoc']($request);
  42. // When should this next be run?
  43. $next_time = next_time($row['time_regularity'], $row['time_unit'], $row['time_offset']);
  44. // How long in seconds it the gap?
  45. $duration = $row['time_regularity'];
  46. if ($row['time_unit'] == 'm')
  47. $duration *= 60;
  48. elseif ($row['time_unit'] == 'h')
  49. $duration *= 3600;
  50. elseif ($row['time_unit'] == 'd')
  51. $duration *= 86400;
  52. elseif ($row['time_unit'] == 'w')
  53. $duration *= 604800;
  54. // If we were really late running this task actually skip the next one.
  55. if (time() + ($duration / 2) > $next_time)
  56. $next_time += $duration;
  57. // Update it now, so no others run this!
  58. $smcFunc['db_query']('', '
  59. UPDATE {db_prefix}scheduled_tasks
  60. SET next_time = {int:next_time}
  61. WHERE id_task = {int:id_task}
  62. AND next_time = {int:current_next_time}',
  63. array(
  64. 'next_time' => $next_time,
  65. 'id_task' => $row['id_task'],
  66. 'current_next_time' => $row['next_time'],
  67. )
  68. );
  69. $affected_rows = $smcFunc['db_affected_rows']();
  70. // The function must exist or we are wasting our time, plus do some timestamp checking, and database check!
  71. if (function_exists('scheduled_' . $row['task']) && (!isset($_GET['ts']) || $_GET['ts'] == $row['next_time']) && $affected_rows)
  72. {
  73. ignore_user_abort(true);
  74. // Do the task...
  75. $completed = call_user_func('scheduled_' . $row['task']);
  76. // Log that we did it ;)
  77. if ($completed)
  78. {
  79. $total_time = round(array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)), 3);
  80. $smcFunc['db_insert']('',
  81. '{db_prefix}log_scheduled_tasks',
  82. array(
  83. 'id_task' => 'int', 'time_run' => 'int', 'time_taken' => 'float',
  84. ),
  85. array(
  86. $row['id_task'], time(), (int) $total_time,
  87. ),
  88. array()
  89. );
  90. }
  91. }
  92. }
  93. $smcFunc['db_free_result']($request);
  94. // Get the next timestamp right.
  95. $request = $smcFunc['db_query']('', '
  96. SELECT next_time
  97. FROM {db_prefix}scheduled_tasks
  98. WHERE disabled = {int:not_disabled}
  99. ORDER BY next_time ASC
  100. LIMIT 1',
  101. array(
  102. 'not_disabled' => 0,
  103. )
  104. );
  105. // No new task scheduled yet?
  106. if ($smcFunc['db_num_rows']($request) === 0)
  107. $nextEvent = time() + 86400;
  108. else
  109. list ($nextEvent) = $smcFunc['db_fetch_row']($request);
  110. $smcFunc['db_free_result']($request);
  111. updateSettings(array('next_task_time' => $nextEvent));
  112. }
  113. // Shall we return?
  114. if (!isset($_GET['scheduled']))
  115. return true;
  116. // Finally, send some stuff...
  117. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  118. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  119. header('Content-Type: image/gif');
  120. die("\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x21\xF9\x04\x01\x00\x00\x00\x00\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3B");
  121. }
  122. // Function to sending out approval notices to moderators etc.
  123. function scheduled_approval_notification()
  124. {
  125. global $scripturl, $modSettings, $mbname, $txt, $sourcedir, $smcFunc;
  126. // Grab all the items awaiting approval and sort type then board - clear up any things that are no longer relevant.
  127. $request = $smcFunc['db_query']('', '
  128. SELECT aq.id_msg, aq.id_attach, aq.id_event, m.id_topic, m.id_board, m.subject, t.id_first_msg,
  129. b.id_profile
  130. FROM {db_prefix}approval_queue AS aq
  131. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = aq.id_msg)
  132. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
  133. INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)',
  134. array(
  135. )
  136. );
  137. $notices = array();
  138. $profiles = array();
  139. while ($row = $smcFunc['db_fetch_assoc']($request))
  140. {
  141. // If this is no longer around we'll ignore it.
  142. if (empty($row['id_topic']))
  143. continue;
  144. // What type is it?
  145. if ($row['id_first_msg'] && $row['id_first_msg'] == $row['id_msg'])
  146. $type = 'topic';
  147. elseif ($row['id_attach'])
  148. $type = 'attach';
  149. else
  150. $type = 'msg';
  151. // Add it to the array otherwise.
  152. $notices[$row['id_board']][$type][] = array(
  153. 'subject' => $row['subject'],
  154. 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
  155. );
  156. // Store the profile for a bit later.
  157. $profiles[$row['id_board']] = $row['id_profile'];
  158. }
  159. $smcFunc['db_free_result']($request);
  160. // Delete it all!
  161. $smcFunc['db_query']('', '
  162. DELETE FROM {db_prefix}approval_queue',
  163. array(
  164. )
  165. );
  166. // If nothing quit now.
  167. if (empty($notices))
  168. return true;
  169. // Now we need to think about finding out *who* can approve - this is hard!
  170. // First off, get all the groups with this permission and sort by board.
  171. $request = $smcFunc['db_query']('', '
  172. SELECT id_group, id_profile, add_deny
  173. FROM {db_prefix}board_permissions
  174. WHERE permission = {string:approve_posts}
  175. AND id_profile IN ({array_int:profile_list})',
  176. array(
  177. 'profile_list' => $profiles,
  178. 'approve_posts' => 'approve_posts',
  179. )
  180. );
  181. $perms = array();
  182. $addGroups = array(1);
  183. while ($row = $smcFunc['db_fetch_assoc']($request))
  184. {
  185. // Sorry guys, but we have to ignore guests AND members - it would be too many otherwise.
  186. if ($row['id_group'] < 2)
  187. continue;
  188. $perms[$row['id_profile']][$row['add_deny'] ? 'add' : 'deny'][] = $row['id_group'];
  189. // Anyone who can access has to be considered.
  190. if ($row['add_deny'])
  191. $addGroups[] = $row['id_group'];
  192. }
  193. $smcFunc['db_free_result']($request);
  194. // Grab the moderators if they have permission!
  195. $mods = array();
  196. $members = array();
  197. if (in_array(2, $addGroups))
  198. {
  199. $request = $smcFunc['db_query']('', '
  200. SELECT id_member, id_board
  201. FROM {db_prefix}moderators',
  202. array(
  203. )
  204. );
  205. while ($row = $smcFunc['db_fetch_assoc']($request))
  206. {
  207. $mods[$row['id_member']][$row['id_board']] = true;
  208. // Make sure they get included in the big loop.
  209. $members[] = $row['id_member'];
  210. }
  211. $smcFunc['db_free_result']($request);
  212. }
  213. // Come along one and all... until we reject you ;)
  214. $request = $smcFunc['db_query']('', '
  215. SELECT id_member, real_name, email_address, lngfile, id_group, additional_groups, mod_prefs
  216. FROM {db_prefix}members
  217. WHERE id_group IN ({array_int:additional_group_list})
  218. OR FIND_IN_SET({raw:additional_group_list_implode}, additional_groups) != 0' . (empty($members) ? '' : '
  219. OR id_member IN ({array_int:member_list})') . '
  220. ORDER BY lngfile',
  221. array(
  222. 'additional_group_list' => $addGroups,
  223. 'member_list' => $members,
  224. 'additional_group_list_implode' => implode(', additional_groups) != 0 OR FIND_IN_SET(', $addGroups),
  225. )
  226. );
  227. $members = array();
  228. while ($row = $smcFunc['db_fetch_assoc']($request))
  229. {
  230. // Check whether they are interested.
  231. if (!empty($row['mod_prefs']))
  232. {
  233. list(,, $pref_binary) = explode('|', $row['mod_prefs']);
  234. if (!($pref_binary & 4))
  235. continue;
  236. }
  237. $members[$row['id_member']] = array(
  238. 'id' => $row['id_member'],
  239. 'groups' => array_merge(explode(',', $row['additional_groups']), array($row['id_group'])),
  240. 'language' => $row['lngfile'],
  241. 'email' => $row['email_address'],
  242. 'name' => $row['real_name'],
  243. );
  244. }
  245. $smcFunc['db_free_result']($request);
  246. // Get the mailing stuff.
  247. require_once($sourcedir . '/Subs-Post.php');
  248. // Need the below for loadLanguage to work!
  249. loadEssentialThemeData();
  250. // Finally, loop through each member, work out what they can do, and send it.
  251. foreach ($members as $id => $member)
  252. {
  253. $emailbody = '';
  254. // Load the language file as required.
  255. if (empty($current_language) || $current_language != $member['language'])
  256. $current_language = loadLanguage('EmailTemplates', $member['language'], false);
  257. // Loop through each notice...
  258. foreach ($notices as $board => $notice)
  259. {
  260. $access = false;
  261. // Can they mod in this board?
  262. if (isset($mods[$id][$board]))
  263. $access = true;
  264. // Do the group check...
  265. if (!$access && isset($perms[$profiles[$board]]['add']))
  266. {
  267. // They can access?!
  268. if (array_intersect($perms[$profiles[$board]]['add'], $member['groups']))
  269. $access = true;
  270. // If they have deny rights don't consider them!
  271. if (isset($perms[$profiles[$board]]['deny']))
  272. if (array_intersect($perms[$profiles[$board]]['deny'], $member['groups']))
  273. $access = false;
  274. }
  275. // Finally, fix it for admins!
  276. if (in_array(1, $member['groups']))
  277. $access = true;
  278. // If they can't access it then give it a break!
  279. if (!$access)
  280. continue;
  281. foreach ($notice as $type => $items)
  282. {
  283. // Build up the top of this section.
  284. $emailbody .= $txt['scheduled_approval_email_' . $type] . "\n" .
  285. '------------------------------------------------------' . "\n";
  286. foreach ($items as $item)
  287. $emailbody .= $item['subject'] . ' - ' . $item['href'] . "\n";
  288. $emailbody .= "\n";
  289. }
  290. }
  291. if ($emailbody == '')
  292. continue;
  293. $replacements = array(
  294. 'REALNAME' => $member['name'],
  295. 'BODY' => $emailbody,
  296. );
  297. $emaildata = loadEmailTemplate('scheduled_approval', $replacements, $current_language);
  298. // Send the actual email.
  299. sendmail($member['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 2);
  300. }
  301. // All went well!
  302. return true;
  303. }
  304. // Do some daily cleaning up.
  305. function scheduled_daily_maintenance()
  306. {
  307. global $smcFunc, $modSettings, $sourcedir, $db_type;
  308. // First clean out the cache.
  309. clean_cache();
  310. // If warning decrement is enabled and we have people who have not had a new warning in 24 hours, lower their warning level.
  311. list (, , $modSettings['warning_decrement']) = explode(',', $modSettings['warning_settings']);
  312. if ($modSettings['warning_decrement'])
  313. {
  314. // Find every member who has a warning level...
  315. $request = $smcFunc['db_query']('', '
  316. SELECT id_member, warning
  317. FROM {db_prefix}members
  318. WHERE warning > {int:no_warning}',
  319. array(
  320. 'no_warning' => 0,
  321. )
  322. );
  323. $members = array();
  324. while ($row = $smcFunc['db_fetch_assoc']($request))
  325. $members[$row['id_member']] = $row['warning'];
  326. $smcFunc['db_free_result']($request);
  327. // Have some members to check?
  328. if (!empty($members))
  329. {
  330. // Find out when they were last warned.
  331. $request = $smcFunc['db_query']('', '
  332. SELECT id_recipient, MAX(log_time) AS last_warning
  333. FROM {db_prefix}log_comments
  334. WHERE id_recipient IN ({array_int:member_list})
  335. AND comment_type = {string:warning}
  336. GROUP BY id_recipient',
  337. array(
  338. 'member_list' => array_keys($members),
  339. 'warning' => 'warning',
  340. )
  341. );
  342. $member_changes = array();
  343. while ($row = $smcFunc['db_fetch_assoc']($request))
  344. {
  345. // More than 24 hours ago?
  346. if ($row['last_warning'] <= time() - 86400)
  347. $member_changes[] = array(
  348. 'id' => $row['id_recipient'],
  349. 'warning' => $members[$row['id_recipient']] >= $modSettings['warning_decrement'] ? $members[$row['id_recipient']] - $modSettings['warning_decrement'] : 0,
  350. );
  351. }
  352. $smcFunc['db_free_result']($request);
  353. // Have some members to change?
  354. if (!empty($member_changes))
  355. foreach ($member_changes as $change)
  356. $smcFunc['db_query']('', '
  357. UPDATE {db_prefix}members
  358. SET warning = {int:warning}
  359. WHERE id_member = {int:id_member}',
  360. array(
  361. 'warning' => $change['warning'],
  362. 'id_member' => $change['id'],
  363. )
  364. );
  365. }
  366. }
  367. // Do any spider stuff.
  368. if (!empty($modSettings['spider_mode']) && $modSettings['spider_mode'] > 1)
  369. {
  370. require_once($sourcedir . '/ManageSearchEngines.php');
  371. consolidateSpiderStats();
  372. }
  373. // Check the database version - for some buggy MySQL version.
  374. $server_version = $smcFunc['db_server_info']();
  375. if ($db_type == 'mysql' && in_array(substr($server_version, 0, 6), array('5.0.50', '5.0.51')))
  376. updateSettings(array('db_mysql_group_by_fix' => '1'));
  377. elseif (!empty($modSettings['db_mysql_group_by_fix']))
  378. $smcFunc['db_query']('', '
  379. DELETE FROM {db_prefix}settings
  380. WHERE variable = {string:mysql_fix}',
  381. array(
  382. 'mysql_fix' => 'db_mysql_group_by_fix',
  383. )
  384. );
  385. // Regenerate the Diffie-Hellman keys if OpenID is enabled.
  386. if (!empty($modSettings['enableOpenID']))
  387. {
  388. require_once($sourcedir . '/Subs-OpenID.php');
  389. smf_openID_setup_DH(true);
  390. }
  391. elseif (!empty($modSettings['dh_keys']))
  392. $smcFunc['db_query']('', '
  393. DELETE FROM {db_prefix}settings
  394. WHERE variable = {string:dh_keys}',
  395. array(
  396. 'dh_keys' => 'dh_keys',
  397. )
  398. );
  399. // Clean up some old login history information.
  400. $smcFunc['db_query']('', '
  401. DELETE FROM {db_prefix}member_logins
  402. WHERE time > {int:oldLogins}',
  403. array(
  404. 'oldLogins' => !empty($modSettings['loginHistoryDays']) ? 60 * 60 * $modSettings['loginHistoryDays'] : 108000,
  405. ));
  406. // Log we've done it...
  407. return true;
  408. }
  409. // Auto optimize the database?
  410. function scheduled_auto_optimize()
  411. {
  412. global $modSettings, $smcFunc, $db_prefix, $db_type;
  413. // By default do it now!
  414. $delay = false;
  415. // As a kind of hack, if the server load is too great delay, but only by a bit!
  416. if (!empty($modSettings['load_average']) && !empty($modSettings['loadavg_auto_opt']) && $modSettings['load_average'] >= $modSettings['loadavg_auto_opt'])
  417. $delay = true;
  418. // Otherwise are we restricting the number of people online for this?
  419. if (!empty($modSettings['autoOptMaxOnline']))
  420. {
  421. $request = $smcFunc['db_query']('', '
  422. SELECT COUNT(*)
  423. FROM {db_prefix}log_online',
  424. array(
  425. )
  426. );
  427. list ($dont_do_it) = $smcFunc['db_fetch_row']($request);
  428. $smcFunc['db_free_result']($request);
  429. if ($dont_do_it > $modSettings['autoOptMaxOnline'])
  430. $delay = true;
  431. }
  432. // If we are gonna delay, do so now!
  433. if ($delay)
  434. return false;
  435. db_extend();
  436. // Get all the tables.
  437. $tables = $smcFunc['db_list_tables'](false, $db_prefix . '%');
  438. // Actually do the optimisation.
  439. if ($db_type == 'sqlite')
  440. $smcFunc['db_optimize_table']($table[0]);
  441. else
  442. foreach ($tables as $table)
  443. $smcFunc['db_optimize_table']($table);
  444. // Return for the log...
  445. return true;
  446. }
  447. // Send out a daily email of all subscribed topics.
  448. function scheduled_daily_digest()
  449. {
  450. global $is_weekly, $txt, $mbname, $scripturl, $sourcedir, $smcFunc, $context, $modSettings;
  451. // We'll want this...
  452. require_once($sourcedir . '/Subs-Post.php');
  453. loadEssentialThemeData();
  454. $is_weekly = !empty($is_weekly) ? 1 : 0;
  455. // Right - get all the notification data FIRST.
  456. $request = $smcFunc['db_query']('', '
  457. SELECT ln.id_topic, COALESCE(t.id_board, ln.id_board) AS id_board, mem.email_address, mem.member_name, mem.notify_types,
  458. mem.lngfile, mem.id_member
  459. FROM {db_prefix}log_notify AS ln
  460. INNER JOIN {db_prefix}members AS mem ON (mem.id_member = ln.id_member)
  461. LEFT JOIN {db_prefix}topics AS t ON (ln.id_topic != {int:empty_topic} AND t.id_topic = ln.id_topic)
  462. WHERE mem.notify_regularity = {int:notify_regularity}
  463. AND mem.is_activated = {int:is_activated}',
  464. array(
  465. 'empty_topic' => 0,
  466. 'notify_regularity' => $is_weekly ? '3' : '2',
  467. 'is_activated' => 1,
  468. )
  469. );
  470. $members = array();
  471. $langs = array();
  472. $notify = array();
  473. while ($row = $smcFunc['db_fetch_assoc']($request))
  474. {
  475. if (!isset($members[$row['id_member']]))
  476. {
  477. $members[$row['id_member']] = array(
  478. 'email' => $row['email_address'],
  479. 'name' => $row['member_name'],
  480. 'id' => $row['id_member'],
  481. 'notifyMod' => $row['notify_types'] < 3 ? true : false,
  482. 'lang' => $row['lngfile'],
  483. );
  484. $langs[$row['lngfile']] = $row['lngfile'];
  485. }
  486. // Store this useful data!
  487. $boards[$row['id_board']] = $row['id_board'];
  488. if ($row['id_topic'])
  489. $notify['topics'][$row['id_topic']][] = $row['id_member'];
  490. else
  491. $notify['boards'][$row['id_board']][] = $row['id_member'];
  492. }
  493. $smcFunc['db_free_result']($request);
  494. if (empty($boards))
  495. return true;
  496. // Just get the board names.
  497. $request = $smcFunc['db_query']('', '
  498. SELECT id_board, name
  499. FROM {db_prefix}boards
  500. WHERE id_board IN ({array_int:board_list})',
  501. array(
  502. 'board_list' => $boards,
  503. )
  504. );
  505. $boards = array();
  506. while ($row = $smcFunc['db_fetch_assoc']($request))
  507. $boards[$row['id_board']] = $row['name'];
  508. $smcFunc['db_free_result']($request);
  509. if (empty($boards))
  510. return true;
  511. // Get the actual topics...
  512. $request = $smcFunc['db_query']('', '
  513. SELECT ld.note_type, t.id_topic, t.id_board, t.id_member_started, m.id_msg, m.subject,
  514. b.name AS board_name
  515. FROM {db_prefix}log_digest AS ld
  516. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ld.id_topic
  517. AND t.id_board IN ({array_int:board_list}))
  518. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
  519. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
  520. WHERE ' . ($is_weekly ? 'ld.daily != {int:daily_value}' : 'ld.daily IN (0, 2)'),
  521. array(
  522. 'board_list' => array_keys($boards),
  523. 'daily_value' => 2,
  524. )
  525. );
  526. $types = array();
  527. while ($row = $smcFunc['db_fetch_assoc']($request))
  528. {
  529. if (!isset($types[$row['note_type']][$row['id_board']]))
  530. $types[$row['note_type']][$row['id_board']] = array(
  531. 'lines' => array(),
  532. 'name' => $row['board_name'],
  533. 'id' => $row['id_board'],
  534. );
  535. if ($row['note_type'] == 'reply')
  536. {
  537. if (isset($types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]))
  538. $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]['count']++;
  539. else
  540. $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']] = array(
  541. 'id' => $row['id_topic'],
  542. 'subject' => un_htmlspecialchars($row['subject']),
  543. 'count' => 1,
  544. );
  545. }
  546. elseif ($row['note_type'] == 'topic')
  547. {
  548. if (!isset($types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]))
  549. $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']] = array(
  550. 'id' => $row['id_topic'],
  551. 'subject' => un_htmlspecialchars($row['subject']),
  552. );
  553. }
  554. else
  555. {
  556. if (!isset($types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]))
  557. $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']] = array(
  558. 'id' => $row['id_topic'],
  559. 'subject' => un_htmlspecialchars($row['subject']),
  560. 'starter' => $row['id_member_started'],
  561. );
  562. }
  563. $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]['members'] = array();
  564. if (!empty($notify['topics'][$row['id_topic']]))
  565. $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]['members'] = array_merge($types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]['members'], $notify['topics'][$row['id_topic']]);
  566. if (!empty($notify['boards'][$row['id_board']]))
  567. $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]['members'] = array_merge($types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]['members'], $notify['boards'][$row['id_board']]);
  568. }
  569. $smcFunc['db_free_result']($request);
  570. if (empty($types))
  571. return true;
  572. // Let's load all the languages into a cache thingy.
  573. $langtxt = array();
  574. foreach ($langs as $lang)
  575. {
  576. loadLanguage('Post', $lang);
  577. loadLanguage('index', $lang);
  578. loadLanguage('EmailTemplates', $lang);
  579. $langtxt[$lang] = array(
  580. 'subject' => $txt['digest_subject_' . ($is_weekly ? 'weekly' : 'daily')],
  581. 'char_set' => $txt['lang_character_set'],
  582. 'intro' => sprintf($txt['digest_intro_' . ($is_weekly ? 'weekly' : 'daily')], $mbname),
  583. 'new_topics' => $txt['digest_new_topics'],
  584. 'topic_lines' => $txt['digest_new_topics_line'],
  585. 'new_replies' => $txt['digest_new_replies'],
  586. 'mod_actions' => $txt['digest_mod_actions'],
  587. 'replies_one' => $txt['digest_new_replies_one'],
  588. 'replies_many' => $txt['digest_new_replies_many'],
  589. 'sticky' => $txt['digest_mod_act_sticky'],
  590. 'lock' => $txt['digest_mod_act_lock'],
  591. 'unlock' => $txt['digest_mod_act_unlock'],
  592. 'remove' => $txt['digest_mod_act_remove'],
  593. 'move' => $txt['digest_mod_act_move'],
  594. 'merge' => $txt['digest_mod_act_merge'],
  595. 'split' => $txt['digest_mod_act_split'],
  596. 'bye' => $txt['regards_team'],
  597. );
  598. }
  599. // Right - send out the silly things - this will take quite some space!
  600. $emails = array();
  601. foreach ($members as $mid => $member)
  602. {
  603. // Right character set!
  604. $context['character_set'] = empty($modSettings['global_character_set']) ? $langtxt[$lang]['char_set'] : $modSettings['global_character_set'];
  605. // Do the start stuff!
  606. $email = array(
  607. 'subject' => $mbname . ' - ' . $langtxt[$lang]['subject'],
  608. 'body' => $member['name'] . ',' . "\n\n" . $langtxt[$lang]['intro'] . "\n" . $scripturl . '?action=profile;area=notification;u=' . $member['id'] . "\n",
  609. 'email' => $member['email'],
  610. );
  611. // All new topics?
  612. if (isset($types['topic']))
  613. {
  614. $titled = false;
  615. foreach ($types['topic'] as $id => $board)
  616. foreach ($board['lines'] as $topic)
  617. if (in_array($mid, $topic['members']))
  618. {
  619. if (!$titled)
  620. {
  621. $email['body'] .= "\n" . $langtxt[$lang]['new_topics'] . ':' . "\n" . '-----------------------------------------------';
  622. $titled = true;
  623. }
  624. $email['body'] .= "\n" . sprintf($langtxt[$lang]['topic_lines'], $topic['subject'], $board['name']);
  625. }
  626. if ($titled)
  627. $email['body'] .= "\n";
  628. }
  629. // What about replies?
  630. if (isset($types['reply']))
  631. {
  632. $titled = false;
  633. foreach ($types['reply'] as $id => $board)
  634. foreach ($board['lines'] as $topic)
  635. if (in_array($mid, $topic['members']))
  636. {
  637. if (!$titled)
  638. {
  639. $email['body'] .= "\n" . $langtxt[$lang]['new_replies'] . ':' . "\n" . '-----------------------------------------------';
  640. $titled = true;
  641. }
  642. $email['body'] .= "\n" . ($topic['count'] == 1 ? sprintf($langtxt[$lang]['replies_one'], $topic['subject']) : sprintf($langtxt[$lang]['replies_many'], $topic['count'], $topic['subject']));
  643. }
  644. if ($titled)
  645. $email['body'] .= "\n";
  646. }
  647. // Finally, moderation actions!
  648. $titled = false;
  649. foreach ($types as $note_type => $type)
  650. {
  651. if ($note_type == 'topic' || $note_type == 'reply')
  652. continue;
  653. foreach ($type as $id => $board)
  654. foreach ($board['lines'] as $topic)
  655. if (in_array($mid, $topic['members']))
  656. {
  657. if (!$titled)
  658. {
  659. $email['body'] .= "\n" . $langtxt[$lang]['mod_actions'] . ':' . "\n" . '-----------------------------------------------';
  660. $titled = true;
  661. }
  662. $email['body'] .= "\n" . sprintf($langtxt[$lang][$note_type], $topic['subject']);
  663. }
  664. }
  665. if ($titled)
  666. $email['body'] .= "\n";
  667. // Then just say our goodbyes!
  668. $email['body'] .= "\n\n" . $txt['regards_team'];
  669. // Send it - low priority!
  670. sendmail($email['email'], $email['subject'], $email['body'], null, null, false, 4);
  671. }
  672. // Clean up...
  673. if ($is_weekly)
  674. {
  675. $smcFunc['db_query']('', '
  676. DELETE FROM {db_prefix}log_digest
  677. WHERE daily != {int:not_daily}',
  678. array(
  679. 'not_daily' => 0,
  680. )
  681. );
  682. $smcFunc['db_query']('', '
  683. UPDATE {db_prefix}log_digest
  684. SET daily = {int:daily_value}
  685. WHERE daily = {int:not_daily}',
  686. array(
  687. 'daily_value' => 2,
  688. 'not_daily' => 0,
  689. )
  690. );
  691. }
  692. else
  693. {
  694. // Clear any only weekly ones, and stop us from sending daily again.
  695. $smcFunc['db_query']('', '
  696. DELETE FROM {db_prefix}log_digest
  697. WHERE daily = {int:daily_value}',
  698. array(
  699. 'daily_value' => 2,
  700. )
  701. );
  702. $smcFunc['db_query']('', '
  703. UPDATE {db_prefix}log_digest
  704. SET daily = {int:both_value}
  705. WHERE daily = {int:no_value}',
  706. array(
  707. 'both_value' => 1,
  708. 'no_value' => 0,
  709. )
  710. );
  711. }
  712. // Just in case the member changes their settings mark this as sent.
  713. $members = array_keys($members);
  714. $smcFunc['db_query']('', '
  715. UPDATE {db_prefix}log_notify
  716. SET sent = {int:is_sent}
  717. WHERE id_member IN ({array_int:member_list})',
  718. array(
  719. 'member_list' => $members,
  720. 'is_sent' => 1,
  721. )
  722. );
  723. // Log we've done it...
  724. return true;
  725. }
  726. // Like the daily stuff - just seven times less regular ;)
  727. function scheduled_weekly_digest()
  728. {
  729. global $is_weekly;
  730. // We just pass through to the daily function - avoid duplication!
  731. $is_weekly = true;
  732. return scheduled_daily_digest();
  733. }
  734. // Send a bunch of emails from the mail queue.
  735. function ReduceMailQueue($number = false, $override_limit = false, $force_send = false)
  736. {
  737. global $modSettings, $smcFunc, $sourcedir;
  738. // Are we intending another script to be sending out the queue?
  739. if (!empty($modSettings['mail_queue_use_cron']) && empty($force_send))
  740. return false;
  741. // By default send 5 at once.
  742. if (!$number)
  743. $number = empty($modSettings['mail_quantity']) ? 5 : $modSettings['mail_quantity'];
  744. // If we came with a timestamp, and that doesn't match the next event, then someone else has beaten us.
  745. if (isset($_GET['ts']) && $_GET['ts'] != $modSettings['mail_next_send'] && empty($force_send))
  746. return false;
  747. // By default move the next sending on by 10 seconds, and require an affected row.
  748. if (!$override_limit)
  749. {
  750. $delay = !empty($modSettings['mail_queue_delay']) ? $modSettings['mail_queue_delay'] : (!empty($modSettings['mail_limit']) && $modSettings['mail_limit'] < 5 ? 10 : 5);
  751. $smcFunc['db_query']('', '
  752. UPDATE {db_prefix}settings
  753. SET value = {string:next_mail_send}
  754. WHERE variable = {string:mail_next_send}
  755. AND value = {string:last_send}',
  756. array(
  757. 'next_mail_send' => time() + $delay,
  758. 'mail_next_send' => 'mail_next_send',
  759. 'last_send' => $modSettings['mail_next_send'],
  760. )
  761. );
  762. if ($smcFunc['db_affected_rows']() == 0)
  763. return false;
  764. $modSettings['mail_next_send'] = time() + $delay;
  765. }
  766. // If we're not overriding how many are we allow to send?
  767. if (!$override_limit && !empty($modSettings['mail_limit']))
  768. {
  769. list ($mt, $mn) = @explode('|', $modSettings['mail_recent']);
  770. // Nothing worth noting...
  771. if (empty($mn) || $mt < time() - 60)
  772. {
  773. $mt = time();
  774. $mn = $number;
  775. }
  776. // Otherwise we have a few more we can spend?
  777. elseif ($mn < $modSettings['mail_limit'])
  778. {
  779. $mn += $number;
  780. }
  781. // No more I'm afraid, return!
  782. else
  783. return false;
  784. // Reflect that we're about to send some, do it now to be safe.
  785. updateSettings(array('mail_recent' => $mt . '|' . $mn));
  786. }
  787. // Now we know how many we're sending, let's send them.
  788. $request = $smcFunc['db_query']('', '
  789. SELECT /*!40001 SQL_NO_CACHE */ id_mail, recipient, body, subject, headers, send_html
  790. FROM {db_prefix}mail_queue
  791. ORDER BY priority ASC, id_mail ASC
  792. LIMIT ' . $number,
  793. array(
  794. )
  795. );
  796. $ids = array();
  797. $emails = array();
  798. while ($row = $smcFunc['db_fetch_assoc']($request))
  799. {
  800. // We want to delete these from the database ASAP, so just get the data and go.
  801. $ids[] = $row['id_mail'];
  802. $emails[] = array(
  803. 'to' => $row['recipient'],
  804. 'body' => $row['body'],
  805. 'subject' => $row['subject'],
  806. 'headers' => $row['headers'],
  807. 'send_html' => $row['send_html'],
  808. );
  809. }
  810. $smcFunc['db_free_result']($request);
  811. // Delete, delete, delete!!!
  812. if (!empty($ids))
  813. $smcFunc['db_query']('', '
  814. DELETE FROM {db_prefix}mail_queue
  815. WHERE id_mail IN ({array_int:mail_list})',
  816. array(
  817. 'mail_list' => $ids,
  818. )
  819. );
  820. // Don't believe we have any left?
  821. if (count($ids) < $number)
  822. {
  823. // Only update the setting if no-one else has beaten us to it.
  824. $smcFunc['db_query']('', '
  825. UPDATE {db_prefix}settings
  826. SET value = {string:no_send}
  827. WHERE variable = {string:mail_next_send}
  828. AND value = {string:last_mail_send}',
  829. array(
  830. 'no_send' => '0',
  831. 'mail_next_send' => 'mail_next_send',
  832. 'last_mail_send' => $modSettings['mail_next_send'],
  833. )
  834. );
  835. }
  836. if (empty($ids))
  837. return false;
  838. if (!empty($modSettings['mail_type']) && $modSettings['smtp_host'] != '')
  839. require_once($sourcedir . '/Subs-Post.php');
  840. // Send each email, yea!
  841. $failed_emails = array();
  842. foreach ($emails as $key => $email)
  843. {
  844. if (empty($modSettings['mail_type']) || $modSettings['smtp_host'] == '')
  845. {
  846. $email['subject'] = strtr($email['subject'], array("\r" => '', "\n" => ''));
  847. if (!empty($modSettings['mail_strip_carriage']))
  848. {
  849. $email['body'] = strtr($email['body'], array("\r" => ''));
  850. $email['headers'] = strtr($email['headers'], array("\r" => ''));
  851. }
  852. // No point logging a specific error here, as we have no language. PHP error is helpful anyway...
  853. $result = mail(strtr($email['to'], array("\r" => '', "\n" => '')), $email['subject'], $email['body'], $email['headers']);
  854. // Try to stop a timeout, this would be bad...
  855. @set_time_limit(300);
  856. if (function_exists('apache_reset_timeout'))
  857. @apache_reset_timeout();
  858. }
  859. else
  860. $result = smtp_mail(array($email['to']), $email['subject'], $email['body'], $email['send_html'] ? $email['headers'] : 'Mime-Version: 1.0' . "\r\n" . $email['headers']);
  861. // Hopefully it sent?
  862. if (!$result)
  863. $failed_emails[] = array($email['to'], $email['body'], $email['subject'], $email['headers'], $email['send_html']);
  864. }
  865. // Any emails that didn't send?
  866. if (!empty($failed_emails))
  867. {
  868. // Update the failed attempts check.
  869. $smcFunc['db_insert']('replace',
  870. '{db_prefix}settings',
  871. array('variable' => 'string', 'value' => 'string'),
  872. array('mail_failed_attempts', empty($modSettings['mail_failed_attempts']) ? 1 : ++$modSettings['mail_failed_attempts']),
  873. array('variable')
  874. );
  875. // If we have failed to many times, tell mail to wait a bit and try again.
  876. if ($modSettings['mail_failed_attempts'] > 5)
  877. $smcFunc['db_query']('', '
  878. UPDATE {db_prefix}settings
  879. SET value = {string:mail_next_send}
  880. WHERE variable = {string:next_mail_send}
  881. AND value = {string:last_send}',
  882. array(
  883. 'next_mail_send' => time() + 60,
  884. 'mail_next_send' => 'mail_next_send',
  885. 'last_send' => $modSettings['mail_next_send'],
  886. ));
  887. // Add our email back to the queue, manually.
  888. $smcFunc['db_insert']('insert',
  889. '{db_prefix}mail_queue',
  890. array('recipient' => 'string', 'body' => 'string', 'subject' => 'string', 'headers' => 'string', 'send_html' => 'string'),
  891. $failed_emails,
  892. array('id_mail')
  893. );
  894. return false;
  895. }
  896. // We where unable to send the email, clear our failed attempts.
  897. elseif (!empty($modSettings['mail_failed_attempts']))
  898. $smcFunc['db_query']('', '
  899. UPDATE {db_prefix}settings
  900. SET value = {string:zero}
  901. WHERE variable = {string:mail_failed_attempts}',
  902. array(
  903. 'zero' => '0',
  904. 'mail_failed_attempts' => 'mail_failed_attempts',
  905. ));
  906. // Had something to send...
  907. return true;
  908. }
  909. // Calculate the next time the passed tasks should be triggered.
  910. function CalculateNextTrigger($tasks = array(), $forceUpdate = false)
  911. {
  912. global $modSettings, $smcFunc;
  913. $task_query = '';
  914. if (!is_array($tasks))
  915. $tasks = array($tasks);
  916. // Actually have something passed?
  917. if (!empty($tasks))
  918. {
  919. if (!isset($tasks[0]) || is_numeric($tasks[0]))
  920. $task_query = ' AND id_task IN ({array_int:tasks})';
  921. else
  922. $task_query = ' AND task IN ({array_string:tasks})';
  923. }
  924. $nextTaskTime = empty($tasks) ? time() + 86400 : $modSettings['next_task_time'];
  925. // Get the critical info for the tasks.
  926. $request = $smcFunc['db_query']('', '
  927. SELECT id_task, next_time, time_offset, time_regularity, time_unit
  928. FROM {db_prefix}scheduled_tasks
  929. WHERE disabled = {int:no_disabled}
  930. ' . $task_query,
  931. array(
  932. 'no_disabled' => 0,
  933. 'tasks' => $tasks,
  934. )
  935. );
  936. $tasks = array();
  937. while ($row = $smcFunc['db_fetch_assoc']($request))
  938. {
  939. $next_time = next_time($row['time_regularity'], $row['time_unit'], $row['time_offset']);
  940. // Only bother moving the task if it's out of place or we're forcing it!
  941. if ($forceUpdate || $next_time < $row['next_time'] || $row['next_time'] < time())
  942. $tasks[$row['id_task']] = $next_time;
  943. else
  944. $next_time = $row['next_time'];
  945. // If this is sooner than the current next task, make this the next task.
  946. if ($next_time < $nextTaskTime)
  947. $nextTaskTime = $next_time;
  948. }
  949. $smcFunc['db_free_result']($request);
  950. // Now make the changes!
  951. foreach ($tasks as $id => $time)
  952. $smcFunc['db_query']('', '
  953. UPDATE {db_prefix}scheduled_tasks
  954. SET next_time = {int:next_time}
  955. WHERE id_task = {int:id_task}',
  956. array(
  957. 'next_time' => $time,
  958. 'id_task' => $id,
  959. )
  960. );
  961. // If the next task is now different update.
  962. if ($modSettings['next_task_time'] != $nextTaskTime)
  963. updateSettings(array('next_task_time' => $nextTaskTime));
  964. }
  965. // Simply returns a time stamp of the next instance of these time parameters.
  966. function next_time($regularity, $unit, $offset)
  967. {
  968. // Just in case!
  969. if ($regularity == 0)
  970. $regularity = 2;
  971. $curHour = date('H', time());
  972. $curMin = date('i', time());
  973. $next_time = 9999999999;
  974. // If the unit is minutes only check regularity in minutes.
  975. if ($unit == 'm')
  976. {
  977. $off = date('i', $offset);
  978. // If it's now just pretend it ain't,
  979. if ($off == $curMin)
  980. $next_time = time() + $regularity;
  981. else
  982. {
  983. // Make sure that the offset is always in the past.
  984. $off = $off > $curMin ? $off - 60 : $off;
  985. while ($off <= $curMin)
  986. $off += $regularity;
  987. // Now we know when the time should be!
  988. $next_time = time() + 60 * ($off - $curMin);
  989. }
  990. }
  991. // Otherwise, work out what the offset would be with todays date.
  992. else
  993. {
  994. $next_time = mktime(date('H', $offset), date('i', $offset), 0, date('m'), date('d'), date('Y'));
  995. // Make the time offset in the past!
  996. if ($next_time > time())
  997. {
  998. $next_time -= 86400;
  999. }
  1000. // Default we'll jump in hours.
  1001. $applyOffset = 3600;
  1002. // 24 hours = 1 day.
  1003. if ($unit == 'd')
  1004. $applyOffset = 86400;
  1005. // Otherwise a week.
  1006. if ($unit == 'w')
  1007. $applyOffset = 604800;
  1008. $applyOffset *= $regularity;
  1009. // Just add on the offset.
  1010. while ($next_time <= time())
  1011. {
  1012. $next_time += $applyOffset;
  1013. }
  1014. }
  1015. return $next_time;
  1016. }
  1017. // This loads the bare minimum data to allow us to load language files!
  1018. function loadEssentialThemeData()
  1019. {
  1020. global $settings, $modSettings, $smcFunc, $mbname, $context, $sourcedir;
  1021. // Get all the default theme variables.
  1022. $result = $smcFunc['db_query']('', '
  1023. SELECT id_theme, variable, value
  1024. FROM {db_prefix}themes
  1025. WHERE id_member = {int:no_member}
  1026. AND id_theme IN (1, {int:theme_guests})',
  1027. array(
  1028. 'no_member' => 0,
  1029. 'theme_guests' => $modSettings['theme_guests'],
  1030. )
  1031. );
  1032. while ($row = $smcFunc['db_fetch_assoc']($result))
  1033. {
  1034. $settings[$row['variable']] = $row['value'];
  1035. // Is this the default theme?
  1036. if (in_array($row['variable'], array('theme_dir', 'theme_url', 'images_url')) && $row['id_theme'] == '1')
  1037. $settings['default_' . $row['variable']] = $row['value'];
  1038. }
  1039. $smcFunc['db_free_result']($result);
  1040. // Check we have some directories setup.
  1041. if (empty($settings['template_dirs']))
  1042. {
  1043. $settings['template_dirs'] = array($settings['theme_dir']);
  1044. // Based on theme (if there is one).
  1045. if (!empty($settings['base_theme_dir']))
  1046. $settings['template_dirs'][] = $settings['base_theme_dir'];
  1047. // Lastly the default theme.
  1048. if ($settings['theme_dir'] != $settings['default_theme_dir'])
  1049. $settings['template_dirs'][] = $settings['default_theme_dir'];
  1050. }
  1051. // Assume we want this.
  1052. $context['forum_name'] = $mbname;
  1053. // Check loadLanguage actually exists!
  1054. if (!function_exists('loadLanguage'))
  1055. {
  1056. require_once($sourcedir . '/Load.php');
  1057. require_once($sourcedir . '/Subs.php');
  1058. }
  1059. loadLanguage('index+Modifications');
  1060. }
  1061. function scheduled_fetchSMfiles()
  1062. {
  1063. global $sourcedir, $txt, $language, $settings, $forum_version, $modSettings, $smcFunc;
  1064. // What files do we want to get
  1065. $request = $smcFunc['db_query']('', '
  1066. SELECT id_file, filename, path, parameters
  1067. FROM {db_prefix}admin_info_files',
  1068. array(
  1069. )
  1070. );
  1071. $js_files = array();
  1072. while ($row = $smcFunc['db_fetch_assoc']($request))
  1073. {
  1074. $js_files[$row['id_file']] = array(
  1075. 'filename' => $row['filename'],
  1076. 'path' => $row['path'],
  1077. 'parameters' => sprintf($row['parameters'], $language, urlencode($modSettings['time_format']), urlencode($forum_version)),
  1078. );
  1079. }
  1080. $smcFunc['db_free_result']($request);
  1081. // We're gonna need fetch_web_data() to pull this off.
  1082. require_once($sourcedir . '/Subs-Package.php');
  1083. // Just in case we run into a problem.
  1084. loadEssentialThemeData();
  1085. loadLanguage('Errors', $language, false);
  1086. foreach ($js_files as $ID_FILE => $file)
  1087. {
  1088. // Create the url
  1089. $server = empty($file['path']) || strpos($file['path'], 'http://') !== 0 ? 'http://www.simplemachines.org' : '';
  1090. $url = $server . (!empty($file['path']) ? $file['path'] : $file['path']) . $file['filename'] . (!empty($file['parameters']) ? '?' . $file['parameters'] : '');
  1091. // Get the file
  1092. $file_data = fetch_web_data($url);
  1093. // If we got an error - give up - the site might be down.
  1094. if ($file_data === false)
  1095. {
  1096. log_error(sprintf($txt['st_cannot_retrieve_file'], $url));
  1097. return false;
  1098. }
  1099. // Save the file to the database.
  1100. $smcFunc['db_query']('substring', '
  1101. UPDATE {db_prefix}admin_info_files
  1102. SET data = SUBSTRING({string:file_data}, 1, 65534)
  1103. WHERE id_file = {int:id_file}',
  1104. array(
  1105. 'id_file' => $ID_FILE,
  1106. 'file_data' => $file_data,
  1107. )
  1108. );
  1109. }
  1110. return true;
  1111. }
  1112. function scheduled_birthdayemails()
  1113. {
  1114. global $modSettings, $sourcedir, $mbname, $txt, $smcFunc, $birthdayEmails;
  1115. // Need this in order to load the language files.
  1116. loadEssentialThemeData();
  1117. // Going to need this to send the emails.
  1118. require_once($sourcedir . '/Subs-Post.php');
  1119. $greeting = isset($modSettings['birthday_email']) ? $modSettings['birthday_email'] : 'happy_birthday';
  1120. // Get the month and day of today.
  1121. $month = date('n'); // Month without leading zeros.
  1122. $day = date('j'); // Day without leading zeros.
  1123. // So who are the lucky ones? Don't include those who are banned and those who don't want them.
  1124. $result = $smcFunc['db_query']('', '
  1125. SELECT id_member, real_name, lngfile, email_address
  1126. FROM {db_prefix}members
  1127. WHERE is_activated < 10
  1128. AND MONTH(birthdate) = {int:month}
  1129. AND DAYOFMONTH(birthdate) = {int:day}
  1130. AND notify_announcements = {int:notify_announcements}
  1131. AND YEAR(birthdate) > {int:year}',
  1132. array(
  1133. 'notify_announcements' => 1,
  1134. 'year' => 1,
  1135. 'month' => $month,
  1136. 'day' => $day,
  1137. )
  1138. );
  1139. // Group them by languages.
  1140. $birthdays = array();
  1141. while ($row = $smcFunc['db_fetch_assoc']($result))
  1142. {
  1143. if (!isset($birthdays[$row['lngfile']]))
  1144. $birthdays[$row['lngfile']] = array();
  1145. $birthdays[$row['lngfile']][$row['id_member']] = array(
  1146. 'name' => $row['real_name'],
  1147. 'email' => $row['email_address']
  1148. );
  1149. }
  1150. $smcFunc['db_free_result']($result);
  1151. // Send out the greetings!
  1152. foreach ($birthdays as $lang => $recps)
  1153. {
  1154. // We need to do some shuffling to make this work properly.
  1155. loadLanguage('EmailTemplates', $lang);
  1156. $txt['emails']['happy_birthday'] = $birthdayEmails[$greeting];
  1157. foreach ($recps as $recp)
  1158. {
  1159. $replacements = array(
  1160. 'REALNAME' => $recp['name'],
  1161. );
  1162. $emaildata = loadEmailTemplate('happy_birthday', $replacements, $lang, false);
  1163. sendmail($recp['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 4);
  1164. // Try to stop a timeout, this would be bad...
  1165. @set_time_limit(300);
  1166. if (function_exists('apache_reset_timeout'))
  1167. @apache_reset_timeout();
  1168. }
  1169. }
  1170. // Flush the mail queue, just in case.
  1171. AddMailQueue(true);
  1172. return true;
  1173. }
  1174. function scheduled_weekly_maintenance()
  1175. {
  1176. global $modSettings, $smcFunc;
  1177. // Delete some settings that needn't be set if they are otherwise empty.
  1178. $emptySettings = array(
  1179. 'warning_mute', 'warning_moderate', 'warning_watch', 'warning_show', 'disableCustomPerPage', 'spider_mode', 'spider_group',
  1180. 'paid_currency_code', 'paid_currency_symbol', 'paid_email_to', 'paid_email', 'paid_enabled', 'paypal_email',
  1181. 'search_enable_captcha', 'search_floodcontrol_time', 'show_spider_online',
  1182. );
  1183. $smcFunc['db_query']('', '
  1184. DELETE FROM {db_prefix}settings
  1185. WHERE variable IN ({array_string:setting_list})
  1186. AND (value = {string:zero_value} OR value = {string:blank_value})',
  1187. array(
  1188. 'zero_value' => '0',
  1189. 'blank_value' => '',
  1190. 'setting_list' => $emptySettings,
  1191. )
  1192. );
  1193. // Some settings we never want to keep - they are just there for temporary purposes.
  1194. $deleteAnywaySettings = array(
  1195. 'attachment_full_notified',
  1196. );
  1197. $smcFunc['db_query']('', '
  1198. DELETE FROM {db_prefix}settings
  1199. WHERE variable IN ({array_string:setting_list})',
  1200. array(
  1201. 'setting_list' => $deleteAnywaySettings,
  1202. )
  1203. );
  1204. // Ok should we prune the logs?
  1205. if (!empty($modSettings['pruningOptions']))
  1206. {
  1207. if (!empty($modSettings['pruningOptions']) && strpos($modSettings['pruningOptions'], ',') !== false)
  1208. list ($modSettings['pruneErrorLog'], $modSettings['pruneModLog'], $modSettings['pruneBanLog'], $modSettings['pruneReportLog'], $modSettings['pruneScheduledTaskLog'], $modSettings['pruneSpiderHitLog']) = explode(',', $modSettings['pruningOptions']);
  1209. if (!empty($modSettings['pruneErrorLog']))
  1210. {
  1211. // Figure out when our cutoff time is. 1 day = 86400 seconds.
  1212. $t = time() - $modSettings['pruneErrorLog'] * 86400;
  1213. $smcFunc['db_query']('', '
  1214. DELETE FROM {db_prefix}log_errors
  1215. WHERE log_time < {int:log_time}',
  1216. array(
  1217. 'log_time' => $t,
  1218. )
  1219. );
  1220. }
  1221. if (!empty($modSettings['pruneModLog']))
  1222. {
  1223. // Figure out when our cutoff time is. 1 day = 86400 seconds.
  1224. $t = time() - $modSettings['pruneModLog'] * 86400;
  1225. $smcFunc['db_query']('', '
  1226. DELETE FROM {db_prefix}log_actions
  1227. WHERE log_time < {int:log_time}
  1228. AND id_log = {int:moderation_log}',
  1229. array(
  1230. 'log_time' => $t,
  1231. 'moderation_log' => 1,
  1232. )
  1233. );
  1234. }
  1235. if (!empty($modSettings['pruneBanLog']))
  1236. {
  1237. // Figure out when our cutoff time is. 1 day = 86400 seconds.
  1238. $t = time() - $modSettings['pruneBanLog'] * 86400;
  1239. $smcFunc['db_query']('', '
  1240. DELETE FROM {db_prefix}log_banned
  1241. WHERE log_time < {int:log_time}',
  1242. array(
  1243. 'log_time' => $t,
  1244. )
  1245. );
  1246. }
  1247. if (!empty($modSettings['pruneReportLog']))
  1248. {
  1249. // Figure out when our cutoff time is. 1 day = 86400 seconds.
  1250. $t = time() - $modSettings['pruneReportLog'] * 86400;
  1251. // This one is more complex then the other logs. First we need to figure out which reports are too old.
  1252. $reports = array();
  1253. $result = $smcFunc['db_query']('', '
  1254. SELECT id_report
  1255. FROM {db_prefix}log_reported
  1256. WHERE time_started < {int:time_started}',
  1257. array(
  1258. 'time_started' => $t,
  1259. )
  1260. );
  1261. while ($row = $smcFunc['db_fetch_row']($result))
  1262. $reports[] = $row[0];
  1263. $smcFunc['db_free_result']($result);
  1264. if (!empty($reports))
  1265. {
  1266. // Now delete the reports...
  1267. $smcFunc['db_query']('', '
  1268. DELETE FROM {db_prefix}log_reported
  1269. WHERE id_report IN ({array_int:report_list})',
  1270. array(
  1271. 'report_list' => $reports,
  1272. )
  1273. );
  1274. // And delete the comments for those reports...
  1275. $smcFunc['db_query']('', '
  1276. DELETE FROM {db_prefix}log_reported_comments
  1277. WHERE id_report IN ({array_int:report_list})',
  1278. array(
  1279. 'report_list' => $reports,
  1280. )
  1281. );
  1282. }
  1283. }
  1284. if (!empty($modSettings['pruneScheduledTaskLog']))
  1285. {
  1286. // Figure out when our cutoff time is. 1 day = 86400 seconds.
  1287. $t = time() - $modSettings['pruneScheduledTaskLog'] * 86400;
  1288. $smcFunc['db_query']('', '
  1289. DELETE FROM {db_prefix}log_scheduled_tasks
  1290. WHERE time_run < {int:time_run}',
  1291. array(
  1292. 'time_run' => $t,
  1293. )
  1294. );
  1295. }
  1296. if (!empty($modSettings['pruneSpiderHitLog']))
  1297. {
  1298. // Figure out when our cutoff time is. 1 day = 86400 seconds.
  1299. $t = time() - $modSettings['pruneSpiderHitLog'] * 86400;
  1300. $smcFunc['db_query']('', '
  1301. DELETE FROM {db_prefix}log_spider_hits
  1302. WHERE log_time < {int:log_time}',
  1303. array(
  1304. 'log_time' => $t,
  1305. )
  1306. );
  1307. }
  1308. }
  1309. // Get rid of any paid subscriptions that were never actioned.
  1310. $smcFunc['db_query']('', '
  1311. DELETE FROM {db_prefix}log_subscribed
  1312. WHERE end_time = {int:no_end_time}
  1313. AND status = {int:not_active}
  1314. AND start_time < {int:start_time}
  1315. AND payments_pending < {int:payments_pending}',
  1316. array(
  1317. 'no_end_time' => 0,
  1318. 'not_active' => 0,
  1319. 'start_time' => time() - 60,
  1320. 'payments_pending' => 1,
  1321. )
  1322. );
  1323. // Some OS's don't seem to clean out their sessions.
  1324. $smcFunc['db_query']('', '
  1325. DELETE FROM {db_prefix}sessions
  1326. WHERE last_update < {int:last_update}',
  1327. array(
  1328. 'last_update' => time() - 86400,
  1329. )
  1330. );
  1331. return true;
  1332. }
  1333. // Perform the standard checks on expiring/near expiring subscriptions.
  1334. function scheduled_paid_subscriptions()
  1335. {
  1336. global $txt, $sourcedir, $scripturl, $smcFunc, $modSettings, $language;
  1337. // Start off by checking for removed subscriptions.
  1338. $request = $smcFunc['db_query']('', '
  1339. SELECT id_subscribe, id_member
  1340. FROM {db_prefix}log_subscribed
  1341. WHERE status = {int:is_active}
  1342. AND end_time < {int:time_now}',
  1343. array(
  1344. 'is_active' => 1,
  1345. 'time_now' => time(),
  1346. )
  1347. );
  1348. while ($row = $smcFunc['db_fetch_assoc']($request))
  1349. {
  1350. require_once($sourcedir . '/ManagePaid.php');
  1351. removeSubscription($row['id_subscribe'], $row['id_member']);
  1352. }
  1353. $smcFunc['db_free_result']($request);
  1354. // Get all those about to expire that have not had a reminder sent.
  1355. $request = $smcFunc['db_query']('', '
  1356. SELECT ls.id_sublog, m.id_member, m.member_name, m.email_address, m.lngfile, s.name, ls.end_time
  1357. FROM {db_prefix}log_subscribed AS ls
  1358. INNER JOIN {db_prefix}subscriptions AS s ON (s.id_subscribe = ls.id_subscribe)
  1359. INNER JOIN {db_prefix}members AS m ON (m.id_member = ls.id_member)
  1360. WHERE ls.status = {int:is_active}
  1361. AND ls.reminder_sent = {int:reminder_sent}
  1362. AND s.reminder > {int:reminder_wanted}
  1363. AND ls.end_time < ({int:time_now} + s.reminder * 86400)',
  1364. array(
  1365. 'is_active' => 1,
  1366. 'reminder_sent' => 0,
  1367. 'reminder_wanted' => 0,
  1368. 'time_now' => time(),
  1369. )
  1370. );
  1371. $subs_reminded = array();
  1372. while ($row = $smcFunc['db_fetch_assoc']($request))
  1373. {
  1374. // If this is the first one load the important bits.
  1375. if (empty($subs_reminded))
  1376. {
  1377. require_once($sourcedir . '/Subs-Post.php');
  1378. // Need the below for loadLanguage to work!
  1379. loadEssentialThemeData();
  1380. }
  1381. $subs_reminded[] = $row['id_sublog'];
  1382. $replacements = array(
  1383. 'PROFILE_LINK' => $scripturl . '?action=profile;area=subscriptions;u=' . $row['id_member'],
  1384. 'REALNAME' => $row['member_name'],
  1385. 'SUBSCRIPTION' => $row['name'],
  1386. 'END_DATE' => strip_tags(timeformat($row['end_time'])),
  1387. );
  1388. $emaildata = loadEmailTemplate('paid_subscription_reminder', $replacements, empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile']);
  1389. // Send the actual email.
  1390. sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'], null, null, false, 2);
  1391. }
  1392. $smcFunc['db_free_result']($request);
  1393. // Mark the reminder as sent.
  1394. if (!empty($subs_reminded))
  1395. $smcFunc['db_query']('', '
  1396. UPDATE {db_prefix}log_subscribed
  1397. SET reminder_sent = {int:reminder_sent}
  1398. WHERE id_sublog IN ({array_int:subscription_list})',
  1399. array(
  1400. 'subscription_list' => $subs_reminded,
  1401. 'reminder_sent' => 1,
  1402. )
  1403. );
  1404. return true;
  1405. }
  1406. ?>