ScheduledTasks.php 47 KB

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