ScheduledTasks.php 47 KB

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