ScheduledTasks.php 47 KB

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