1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
<?php
class Scheduler
{
public static function updateSchedule($locationid, $action, $options, $openingTimes) {
if ($openingTimes == '') {
self::deleteSchedule($locationid, $action);
return false;
}
$nextexec = self::calcNextexec($action, $options, $openingTimes);
$json_options = json_encode($options);
self::upsert($locationid, $action, $nextexec, $json_options);
return true;
}
public static function deleteSchedule($locationid, $action) {
Database::exec("DELETE FROM `reboot_scheduler`
WHERE locationid = :lid AND action = :act", array(
'lid' => $locationid,
'act' => $action
));
}
private static function calcNextexec($action, $options, $openingTimes) {
$openingTimes = json_decode($openingTimes, true);
$now = time(); $times = [];
foreach ($openingTimes as $row) {
// Fetch hour and minutes of opening / closing time.
$hourmin = explode(':', ($action == 'wol' ? $row['openingtime'] : $row['closingtime']));
// Calculate time based on offset.
$min = ($action == 'wol' ? $hourmin[0] * 60 + $hourmin[1] - $options['wol-offset'] : $hourmin[0] * 60 + $hourmin[1] + $options['sd-offset']);
// Calculate opening / closing time of each day.
foreach ($row['days'] as $day) {
$next = strtotime(date('Y-m-d H:i', strtotime($day . ' ' . $min . ' minutes')));
if ($next < $now) {
$times[] = strtotime(date('Y-m-d H:i', strtotime('next '.$day . ' ' . $min . ' minutes')));
} else {
$times[] = $next;
}
}
}
// Iterate over days, use timestamp with smallest difference to now.
$res = 0; $smallestDiff = 0;
foreach ($times as $time) {
$diff = $time - $now;
if ($res == 0 || $diff < $smallestDiff) {
$smallestDiff = $diff;
$res = $time;
}
}
return $res;
}
private static function upsert($locationid, $action, $nextexec, $options) {
$schedule = Database::queryFirst("SELECT locationid, action
FROM `reboot_scheduler`
WHERE locationid = :lid AND action = :act", array(
'lid' => $locationid,
'act' => $action
));
if ($schedule === false) {
Database::exec("INSERT INTO `reboot_scheduler` (locationid, action, nextexecution, options)
VALUES (:lid, :act, :next, :opt)", array(
'lid' => $locationid,
'act' => $action,
'next' => $nextexec,
'opt' => $options
));
} else {
Database::exec("UPDATE `reboot_scheduler`
SET nextexecution = :next, options = :opt
WHERE locationid = :lid AND action = :act", array(
'next' => $nextexec,
'opt' => $options,
'lid' => $locationid,
'act' => $action
));
}
return true;
}
}
|