ScheduledTasks.php 47 KB

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