ScheduledTasks.php 47 KB

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