ScheduledTasks.php 47 KB

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