/
manager_sql.php
406 lines (349 loc) · 11.3 KB
/
manager_sql.php
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
<?php
/**
* Cronjob Addon.
*
* @author gharlan[at]web[dot]de Gregor Harlan
*
* @package redaxo\cronjob
*/
class rex_cronjob_manager_sql
{
/** @var rex_sql */
private $sql;
/** @var rex_cronjob_manager|null */
private $manager;
private function __construct(?rex_cronjob_manager $manager = null)
{
$this->sql = rex_sql::factory();
// $this->sql->setDebug();
$this->manager = $manager;
}
/**
* @return self
*/
public static function factory(?rex_cronjob_manager $manager = null)
{
return new self($manager);
}
/**
* @return rex_cronjob_manager
*/
public function getManager()
{
if (!is_object($this->manager)) {
$this->manager = rex_cronjob_manager::factory();
}
return $this->manager;
}
/**
* @return bool
*/
public function hasManager()
{
return is_object($this->manager);
}
/**
* @param string $message
* @return void
*/
public function setMessage($message)
{
$this->getManager()->setMessage($message);
}
/**
* @return string
*/
public function getMessage()
{
return $this->getManager()->getMessage();
}
/**
* @return bool
*/
public function hasMessage()
{
return $this->getManager()->hasMessage();
}
/**
* @param int $id
*
* @throws rex_exception
* @return string
*/
public function getName($id)
{
$this->sql->setQuery('
SELECT name
FROM ' . rex::getTable('cronjob') . '
WHERE id = ?
LIMIT 1
', [$id]);
if (1 == $this->sql->getRows()) {
return $this->sql->getValue('name');
}
throw new rex_exception(sprintf('No cronjob found with id %s', $id));
}
/**
* @param int $id
* @return bool
*/
public function setStatus($id, $status)
{
$this->sql->setTable(rex::getTable('cronjob'));
$this->sql->setWhere(['id' => $id]);
$this->sql->setValue('status', $status);
$this->sql->addGlobalUpdateFields();
try {
$this->sql->update();
$success = true;
} catch (rex_sql_exception) {
$success = false;
}
$this->saveNextTime();
return $success;
}
/**
* @param int $id
* @return bool
*/
public function setExecutionStart($id, $reset = false)
{
$this->sql->setTable(rex::getTable('cronjob'));
$this->sql->setWhere(['id' => $id]);
$this->sql->setDateTimeValue('execution_start', $reset ? 0 : time());
try {
$this->sql->update();
return true;
} catch (rex_sql_exception) {
return false;
}
}
/**
* @param int $id
* @return bool
*/
public function delete($id)
{
$this->sql->setTable(rex::getTable('cronjob'));
$this->sql->setWhere(['id' => $id]);
try {
$this->sql->delete();
$success = true;
} catch (rex_sql_exception) {
$success = false;
}
$this->saveNextTime();
return $success;
}
/**
* @param callable(string,bool,string):void|null $callback Callback is called after every job execution (params: job name, success status, message)
* @return void
*/
public function check(?callable $callback = null)
{
$env = rex_cronjob_manager::getCurrentEnvironment();
$script = 'script' === $env;
$sql = rex_sql::factory();
// $sql->setDebug();
$query = '
SELECT id, name, type, parameters, `interval`, execution_moment
FROM ' . rex::getTable('cronjob') . '
WHERE status = 1
AND execution_start < ?
AND environment LIKE ?
AND nexttime <= ?
ORDER BY nexttime ASC, execution_moment DESC, name ASC
';
if ($script) {
$minExecutionStartDiff = 6 * 60 * 60;
} else {
$query .= ' LIMIT 1';
$minExecutionStartDiff = 2 * ((int) ini_get('max_execution_time') ?: 60 * 60);
}
$jobs = $sql->getArray($query, [rex_sql::datetime(time() - $minExecutionStartDiff), '%|' . $env . '|%', rex_sql::datetime()]);
if (!$jobs) {
$this->saveNextTime();
return;
}
ignore_user_abort(true);
register_shutdown_function(function () use (&$jobs): void {
foreach ($jobs as $job) {
if (isset($job['finished'])) {
continue;
}
if (!isset($job['started'])) {
$this->setExecutionStart($job['id'], true);
continue;
}
/** @psalm-taint-escape callable */ // It is intended that the class name is coming from database
$type = $job['type'];
$manager = $this->getManager();
$manager->setCronjob(rex_cronjob::factory($type));
$manager->log(false, 0 != connection_status() ? 'Timeout' : 'Unknown error');
$this->setNextTime($job['id'], $job['interval'], true);
}
$this->saveNextTime();
});
foreach ($jobs as $job) {
$this->setExecutionStart($job['id']);
}
if ($script || 1 == $jobs[0]['execution_moment']) {
foreach ($jobs as &$job) {
$job['started'] = true;
$success = $this->tryExecuteJob($job, true, true);
if ($callback) {
$callback($job['name'], $success, $this->getMessage());
}
$job['finished'] = true;
}
return;
}
rex_extension::register('RESPONSE_SHUTDOWN', function () use (&$jobs, $callback) {
$jobs[0]['started'] = true;
$success = $this->tryExecuteJob($jobs[0], true, true);
if ($callback) {
$callback($jobs[0]['name'], $success, $this->getMessage());
}
$jobs[0]['finished'] = true;
});
}
/**
* @param int $id
* @param bool $log
* @return bool
*/
public function tryExecute($id, $log = true)
{
$sql = rex_sql::factory();
$jobs = $sql->getArray('
SELECT id, name, type, parameters, `interval`
FROM ' . rex::getTable('cronjob') . '
WHERE id = ? AND environment LIKE ?
LIMIT 1
', [$id, '%|' . rex_cronjob_manager::getCurrentEnvironment() . '|%']);
if (!$jobs) {
$this->getManager()->setMessage('Cronjob not found in database');
$this->saveNextTime();
return false;
}
return $this->tryExecuteJob($jobs[0], $log);
}
/**
* @param array{id: int, interval: string, name: string, parameters: ?string, type: class-string<rex_cronjob>} $job
* @param bool $log
* @param bool $resetExecutionStart
* @return bool
*/
private function tryExecuteJob(array $job, $log = true, $resetExecutionStart = false)
{
$params = $job['parameters'] ? json_decode($job['parameters'], true) : [];
/** @psalm-taint-escape callable */ // It is intended that the class name is coming from database
$type = $job['type'];
$cronjob = rex_cronjob::factory($type);
$this->setNextTime($job['id'], $job['interval'], $resetExecutionStart);
return $this->getManager()->tryExecute($cronjob, $job['name'], $params, $log, $job['id']);
}
/**
* @param int $id
* @param string $interval
* @param bool $resetExecutionStart
*
* @return bool
*/
public function setNextTime($id, $interval, $resetExecutionStart = false)
{
$nexttime = self::calculateNextTime(json_decode($interval, true));
$nexttime = $nexttime ? rex_sql::datetime($nexttime) : null;
$add = $resetExecutionStart ? ', execution_start = 0' : '';
try {
$this->sql->setQuery('
UPDATE ' . rex::getTable('cronjob') . '
SET nexttime = ?' . $add . '
WHERE id = ?
', [$nexttime, $id]);
$success = true;
} catch (rex_sql_exception) {
$success = false;
}
$this->saveNextTime();
return $success;
}
/**
* @return int|null
*/
public function getMinNextTime()
{
$this->sql->setQuery('
SELECT MIN(nexttime) AS nexttime
FROM ' . rex::getTable('cronjob') . '
WHERE status = 1
');
if (1 == $this->sql->getRows()) {
return (int) $this->sql->getDateTimeValue('nexttime');
}
return null;
}
/**
* @param int|null $nexttime
* @return true
*/
public function saveNextTime($nexttime = null)
{
if (null === $nexttime) {
$nexttime = $this->getMinNextTime();
}
if (null === $nexttime) {
$nexttime = 0;
} else {
$nexttime = max(1, $nexttime);
}
rex_config::set('cronjob', 'nexttime', $nexttime);
return true;
}
/**
* @return int|null
*/
public static function calculateNextTime(array $interval)
{
if (empty($interval['minutes']) || empty($interval['hours']) || empty($interval['days']) || empty($interval['weekdays']) || empty($interval['months'])) {
return null;
}
$date = new DateTime('+5 min');
$date->setTime((int) $date->format('G'), (int) floor((int) $date->format('i') / 5) * 5, 0);
$isValid = static function ($value, $current) {
return 'all' === $value || in_array($current, $value);
};
$validateTime = static function () use ($interval, $date, $isValid) {
while (!$isValid($interval['hours'], $date->format('G'))) {
$date->modify('+1 hour');
$date->setTime((int) $date->format('G'), 0, 0);
}
while (!$isValid($interval['minutes'], (int) $date->format('i'))) {
$date->modify('+5 min');
while (!$isValid($interval['hours'], $date->format('G'))) {
$date->modify('+1 hour');
$date->setTime((int) $date->format('G'), 0, 0);
}
}
};
$validateTime();
if (
!$isValid($interval['days'], $date->format('j')) ||
!$isValid($interval['weekdays'], $date->format('w')) ||
!$isValid($interval['months'], $date->format('n'))
) {
$date->setTime(0, 0, 0);
$validateTime();
while (!$isValid($interval['months'], $date->format('n'))) {
$date->modify('first day of next month');
}
while (!$isValid($interval['days'], $date->format('j')) || !$isValid($interval['weekdays'], $date->format('w'))) {
$date->modify('+1 day');
while (!$isValid($interval['months'], $date->format('n'))) {
$date->modify('first day of next month');
}
}
}
return $date->getTimestamp();
}
}