ScheduledTasks.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  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. /**
  1440. * Check for un-posted attachments is something we can do once in a while :P
  1441. * This function uses opendir cycling through all the attachments
  1442. */
  1443. function scheduled_remove_temp_attachments()
  1444. {
  1445. global $modSettings;
  1446. // We need to know where this thing is going.
  1447. if (!empty($modSettings['currentAttachmentUploadDir']))
  1448. {
  1449. if (!is_array($modSettings['attachmentUploadDir']))
  1450. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1451. // Just use the current path for temp files.
  1452. $attach_dirs = $modSettings['attachmentUploadDir'];
  1453. }
  1454. else
  1455. {
  1456. $attach_dirs = array($modSettings['attachmentUploadDir']);
  1457. }
  1458. foreach ($attach_dirs as $attach_dir)
  1459. {
  1460. $dir = @opendir($attach_dir) or fatal_lang_error('cant_access_upload_path', 'critical');
  1461. while ($file = readdir($dir))
  1462. {
  1463. if ($file == '.' || $file == '..')
  1464. continue;
  1465. if (strpos($file, 'post_tmp_') !== false)
  1466. {
  1467. // Temp file is more than 5 hours old!
  1468. if (filemtime($attach_dir . '/' . $file) < time() - 18000)
  1469. @unlink($attach_dir . '/' . $file);
  1470. }
  1471. }
  1472. closedir($dir);
  1473. }
  1474. }
  1475. /**
  1476. * Check for move topic notices that have past their best by date
  1477. */
  1478. function scheduled_remove_topic_redirect()
  1479. {
  1480. global $smcFunc, $sourcedir;
  1481. // init
  1482. $topics = array();
  1483. // We will need this for lanaguage files
  1484. loadEssentialThemeData();
  1485. // Find all of the old MOVE topic notices that were set to expire
  1486. $request = $smcFunc['db_query']('', '
  1487. SELECT id_topic
  1488. FROM {db_prefix}topics
  1489. WHERE redirect_expires <= {int:redirect_expires}
  1490. AND redirect_expires <> 0',
  1491. array(
  1492. 'redirect_expires' => time(),
  1493. )
  1494. );
  1495. while ($row = $smcFunc['db_fetch_row']($request))
  1496. $topics[] = $row[0];
  1497. $smcFunc['db_free_result']($request);
  1498. // Zap, your gone
  1499. if (count($topics) > 0)
  1500. {
  1501. require_once($sourcedir . '/RemoveTopic.php');
  1502. removeTopics($topics, false, true);
  1503. }
  1504. return true;
  1505. }
  1506. /**
  1507. * Check for old drafts and remove them
  1508. */
  1509. function scheduled_remove_old_drafts()
  1510. {
  1511. global $smcFunc, $sourcedir, $modSettings;
  1512. if (empty($modSettings['drafts_keep_days']))
  1513. return true;
  1514. // init
  1515. $drafts= array();
  1516. // We need this for lanaguage items
  1517. loadEssentialThemeData();
  1518. // Find all of the old drafts
  1519. $request = $smcFunc['db_query']('', '
  1520. SELECT id_draft
  1521. FROM {db_prefix}user_drafts
  1522. WHERE poster_time <= {int:poster_time_old}',
  1523. array(
  1524. 'poster_time_old' => time() - (86400 * $modSettings['drafts_keep_days']),
  1525. )
  1526. );
  1527. while ($row = $smcFunc['db_fetch_row']($request))
  1528. $drafts[] = (int) $row[0];
  1529. $smcFunc['db_free_result']($request);
  1530. // If we have old one, remove them
  1531. if (count($drafts) > 0)
  1532. {
  1533. require_once($sourcedir . '/Drafts.php');
  1534. DeleteDraft($drafts, false);
  1535. }
  1536. return true;
  1537. }
  1538. ?>