comparison forum/Sources/ScheduledTasks.php @ 76:e3e11437ecea website

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