PluginProbe ʕ •ᴥ•ʔ
WP STAGING – WordPress Backups, Restore, Migration & Clone / 4.11.0
WP STAGING – WordPress Backups, Restore, Migration & Clone v4.11.0
4.11.0 4.10.0 4.9.5 4.9.4 4.9.3 4.9.2 4.9.1 4.9.0 4.8.1 trunk 3.0.0 3.0.1 3.0.2 3.0.3 3.0.4 3.0.5 3.0.6 3.1.0 3.1.1 3.1.2 3.1.3 3.1.4 3.10.0 3.2.0 3.3.1 3.3.2 3.3.3 3.4.1 3.4.3 3.5.0 3.6.0 3.7.1 3.8.0 3.8.1 3.8.2 3.8.3 3.8.4 3.8.5 3.8.6 3.8.7 3.9.0 3.9.1 3.9.2 3.9.3 3.9.4 4.0.0 4.1.0 4.1.1 4.1.2 4.1.3 4.1.4 4.2.0 4.2.1 4.3.0 4.3.1 4.3.2 4.4.0 4.5.0 4.6.0 4.7.0 4.7.1 4.7.2 4.7.3 4.8.0
wp-staging / Framework / BackgroundProcessing / Queue.php
wp-staging / Framework / BackgroundProcessing Last commit date
Exceptions 1 day ago Job 1 day ago Action.php 1 day ago BackgroundProcessingServiceProvider.php 1 day ago Demo.php 1 day ago FeatureDetection.php 1 day ago Queue.php 1 day ago QueueActionAware.php 1 day ago QueueProcessor.php 1 day ago WithQueueAwareness.php 1 day ago
Queue.php
1586 lines
1 <?php
2
3
4
5
6
7
8
9
10
11 namespace WPStaging\Framework\BackgroundProcessing;
12
13 use DateTimeImmutable;
14 use Exception;
15 use WPStaging\Core\Utils\Logger;
16 use WPStaging\Core\WPStaging;
17 use WPStaging\Framework\Adapter\Database as DatabaseAdapter;
18 use WPStaging\Framework\Adapter\Database\InterfaceDatabaseClient as Database;
19 use WPStaging\Framework\Adapter\PhpAdapter;
20 use WPStaging\Framework\BackgroundProcessing\Exceptions\QueueException;
21 use WPStaging\Framework\Traits\BenchmarkTrait;
22
23 use function WPStaging\functions\debug_log;
24
25
26
27
28
29
30 class Queue
31 {
32 use WithQueueAwareness;
33
34 use BenchmarkTrait;
35
36
37
38
39
40
41 const TABLE_NOT_EXIST = -1;
42 const TABLE_EXISTS = 0;
43 const TABLE_CREATED = 1;
44
45
46
47
48
49 const STATUS_READY = 'ready';
50 const STATUS_PROCESSING = 'processing';
51 const STATUS_COMPLETED = 'completed';
52 const STATUS_FAILED = 'failed';
53 const STATUS_ANY = 'any';
54 const STATUS_CANCELED = 'canceled';
55
56
57 const OPTION_HTTP_AUTH_CREDENTIALS = 'wpstg_background_http_auth_credentials';
58
59
60
61
62 const QUEUE_TABLE_NAME = 'wpstg_queue';
63
64
65
66
67
68
69 const QUEUE_TABLE_VERSION_KEY = 'wpstg_queue_table_version';
70
71
72
73
74
75 const QUEUE_TABLE_STRUCTURE_VERSION_KEY = 'wpstg_queue_table_structure_version';
76
77
78
79
80
81
82 const QUEUE_TABLE_STRUCTURE_VERSION = '1.0.0';
83
84
85 const STALLED_ACTIONS_BREAKPOINT_IN_MINS = 15;
86
87
88 const SET_UPDATED_AT_TO_NOW = true;
89
90
91
92
93
94
95 protected $featureDetection;
96
97
98
99
100
101
102
103
104
105 private $tableState;
106
107
108
109
110
111
112 private $logger;
113
114
115
116
117
118
119 private $defaultHydrateStatuses = [self::STATUS_READY];
120
121
122
123
124
125
126 private $actionCaches = [];
127
128
129
130
131
132
133
134 private $database;
135
136
137
138
139
140
141 private $unlocker;
142
143
144 private $phpAdapter;
145
146
147
148
149
150
151
152
153 public function __construct($database = null)
154 {
155 $services = WPStaging::getInstance()->getContainer();
156 $this->database = $database ?: $services->make(DatabaseAdapter::class)->getClient();
157 $this->logger = $services->make('logger');
158 $this->featureDetection = $services->make(FeatureDetection::class);
159 $this->phpAdapter = $services->make(PhpAdapter::class);
160 }
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181 public function enqueueAction($action, array $args = [], $jobId = 'default', $priority = 0)
182 {
183
184 $this->featureDetection->isAjaxAvailable(true);
185
186
187 $actionObject = new Action(0, $action, $args, $jobId, $priority);
188
189 if (!$this->tableExists()) {
190
191 $this->checkTable(true);
192 }
193
194 if (static::TABLE_NOT_EXIST === $this->checkTable()) {
195
196 return false;
197 }
198
199 $assignments = [
200 'action' => $actionObject->action,
201 'jobId' => (string)$actionObject->jobId,
202 'status' => self::STATUS_READY,
203 'priority' => (int)$actionObject->priority,
204 'args' => $actionObject->args,
205 'updated_at' => current_time('mysql'),
206 ];
207
208 $assignmentsList = $this->buildAssignmentsList($assignments);
209
210 $tableName = self::getTableName();
211 $query = "INSERT INTO {$tableName} SET {$assignmentsList}";
212
213 $result = $this->database->query($query);
214
215 if ($result === false) {
216 \WPStaging\functions\debug_log(json_encode([
217 'root' => 'Error while trying insert Action information.',
218 'class' => get_class($this),
219 'query' => $query,
220 'error' => $this->database->error(),
221 ]));
222
223 return false;
224 }
225
226 $id = $this->database->insertId();
227
228 if (empty($id)) {
229 \WPStaging\functions\debug_log(json_encode([
230 'root' => 'Error while trying to fetch last inserted Action ID.',
231 'class' => get_class($this),
232 'query' => $query,
233 'error' => $this->database->error(),
234 ]));
235
236 return false;
237 }
238
239 $actionObject = $actionObject->alter(['id' => $id, 'status' => self::STATUS_READY]);
240 $this->actionCaches[$id] = $actionObject->toArray();
241
242 set_site_transient(
243 BackgroundProcessingServiceProvider::TRANSIENT_QUEUE_HAS_WORK,
244 1,
245 BackgroundProcessingServiceProvider::QUEUE_HAS_WORK_TTL
246 );
247
248 if (!has_action('shutdown', [$this, 'maybeFireAjaxAction'])) {
249 add_action('shutdown', [$this, 'maybeFireAjaxAction']);
250 }
251
252 return (int)$id;
253 }
254
255
256
257
258
259
260
261
262
263
264
265
266 public function checkTable($force = false)
267 {
268 if (!$force && $this->tableState !== null) {
269 return $this->tableState;
270 }
271
272 $this->tableState = self::TABLE_NOT_EXIST;
273
274 $currentTableVersion = $this->getCurrentTableVersion();
275
276
277 if (version_compare($currentTableVersion, $this->getLatestTableVersion(), '<') || !$this->tableExists()) {
278 $tableState = $this->updateTable();
279
280 if ($tableState === self::TABLE_EXISTS) {
281
282 $this->tableState = self::TABLE_EXISTS;
283
284 return self::TABLE_CREATED;
285 }
286 }
287
288 $this->tableState = $this->tableExists() ? self::TABLE_EXISTS : self::TABLE_NOT_EXIST;
289
290 return $this->tableState;
291 }
292
293
294
295
296
297
298 protected function getCurrentTableVersion()
299 {
300 return get_option(self::QUEUE_TABLE_STRUCTURE_VERSION_KEY, '0.0.0');
301 }
302
303
304
305
306
307
308 protected function getLatestTableVersion()
309 {
310 return self::QUEUE_TABLE_STRUCTURE_VERSION;
311 }
312
313
314
315
316
317
318
319
320
321
322 private function updateTable()
323 {
324 $tableSql = $this->getCreateTableSql();
325
326 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
327
328 $dbdeltaQueries = [];
329
330 $this->addUpgradeQueries($dbdeltaQueries);
331
332
333 $collectDbdeltaQueries = static function ($queries) use (&$dbdeltaQueries, &$collectDbdeltaQueries) {
334
335 remove_filter('dbdelta_queries', $collectDbdeltaQueries);
336 $dbdeltaQueries = array_merge($queries, $dbdeltaQueries);
337
338
339 return [];
340 };
341
342 add_filter('dbdelta_queries', $collectDbdeltaQueries);
343 dbDelta($tableSql, false);
344
345
346 if ($this->database->query('START TRANSACTION') === false) {
347 return self::TABLE_NOT_EXIST;
348 }
349
350 foreach ($dbdeltaQueries as $query) {
351 if ($this->database->query($query) === false) {
352 debug_log('Queue Table Upgrade Error: ' . $this->database->error());
353 $this->database->query('ROLLBACK');
354 return self::TABLE_NOT_EXIST;
355 }
356 }
357
358 if ($this->database->query('COMMIT') === false) {
359 return self::TABLE_NOT_EXIST;
360 }
361
362 $this->updateTableVersionOption($this->getLatestTableVersion());
363
364 return self::TABLE_EXISTS;
365 }
366
367
368
369
370
371
372
373 public static function getTableName()
374 {
375 global $wpdb;
376
377 return $wpdb->prefix . self::QUEUE_TABLE_NAME;
378 }
379
380
381
382
383
384
385
386
387
388
389
390 private function updateTableVersionOption($tableVersion)
391 {
392 update_option(self::QUEUE_TABLE_STRUCTURE_VERSION_KEY, $tableVersion);
393 }
394
395
396
397
398
399
400 public function tableExists()
401 {
402 $tableName = self::getTableName();
403 $result = $this->database->query("SHOW TABLES LIKE '{$tableName}'");
404
405 if ($result === false) {
406 return false;
407 }
408
409 $value = $this->database->fetchRow($result);
410
411 return $value === [$tableName];
412 }
413
414
415
416
417
418
419
420
421
422
423 public function getActionField($actionId, $field)
424 {
425 if (empty($this->actionCaches[$actionId])) {
426
427 $this->hydrateActionCaches([$actionId]);
428 }
429
430 return isset($this->actionCaches[$actionId][$field]) ?
431 $this->actionCaches[$actionId][$field]
432 : null;
433 }
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451 private function hydrateActionCaches(array $actionIds = [])
452 {
453 $tableState = $this->checkTable();
454
455 if ($tableState === self::TABLE_CREATED || $tableState === false) {
456
457 return;
458 }
459
460 $queueTable = self::getTableName();
461
462
463
464
465
466
467
468
469 $offset = 0;
470 $limit = 100;
471 $inputActionIdsCount = count($actionIds);
472 $totalResultsCount = 0;
473
474 do {
475 $offsetAndLimit = sprintf('%d, %d', $offset, $limit);
476
477 if ($inputActionIdsCount > 0) {
478 $ids = implode(',', array_filter(array_map('absint', $actionIds)));
479 $query = "SELECT * FROM {$queueTable} q JOIN {$queueTable} q1 ON q.status = q1.status WHERE q1.id IN ({$ids}) LIMIT {$offsetAndLimit}";
480 } else {
481 $stati = implode(',', array_map(function ($status) {
482 return "'{$this->database->escape($status)}'";
483 }, $this->defaultHydrateStatuses));
484 $query = "SELECT * FROM {$queueTable} WHERE status IN ({$stati}) LIMIT {$offsetAndLimit}";
485 }
486
487 $result = $this->database->query($query);
488
489 if ($result === false) {
490 \WPStaging\functions\debug_log(json_encode([
491 'root' => 'Error while trying to fetch Actions information.',
492 'class' => get_class($this),
493 'query' => $query,
494 'error' => $this->database->error(),
495 ]));
496
497
498 return;
499 }
500
501 $preparedActions = [];
502 while ($actionRow = $this->database->fetchAssoc($result)) {
503 $totalResultsCount++;
504 $preparedActions[$actionRow['id']] = $this->convertDbRowToData($actionRow);
505 }
506
507 $found = $inputActionIdsCount === count(array_diff_key($preparedActions, array_flip($actionIds)));
508
509 if (!isset($foundRows)) {
510 $foundRows = max(0, (int)$this->database->foundRows());
511 }
512
513 $offset += $limit;
514 } while (!$found && $totalResultsCount < $foundRows);
515
516 $this->actionCaches = array_replace($this->actionCaches, $preparedActions);
517 }
518
519
520
521
522
523
524
525
526
527
528 private function convertDbRowToData(array $actionRow)
529 {
530 return Action::fromDbRow($actionRow)->toArray();
531 }
532
533
534
535
536
537
538
539
540
541
542 public function getNextAvailable()
543 {
544 if ($this->checkTable() !== self::TABLE_EXISTS) {
545
546 debug_log('Queue getNextAvailable: Table does not exist for getting the next available.', 'debug', false);
547 return null;
548 }
549
550 $processing = self::STATUS_PROCESSING;
551 $ready = self::STATUS_READY;
552 $tableName = self::getTableName();
553 $now = current_time('mysql');
554
555 $this->unlockQueueTable();
556
557 $this->database->query("LOCK TABLE `$tableName` WRITE");
558
559 if ($this->count($processing) > 0) {
560 debug_log('Queue getNextAvailable: There is an action already in process. Stop!', 'debug', false);
561 $this->database->query("UNLOCK TABLES");
562 return null;
563 }
564
565 $claimIdQuery = "SELECT id FROM {$tableName}
566 WHERE status = '{$ready}'
567 ORDER BY priority, action, jobId ASC LIMIT 1";
568 $claimedId = $this->database->query($claimIdQuery);
569
570 if (!$claimedId) {
571
572 debug_log('Queue getNextAvailable returns null because claimed Id was empty. This query failed: ' . $claimIdQuery, 'debug', false);
573 $this->database->query("UNLOCK TABLES");
574 return null;
575 }
576
577 $claimedId = $this->database->fetchAssoc($claimedId);
578
579 if (!is_array($claimedId) || !array_key_exists('id', $claimedId)) {
580 debug_log('Queue getNextAvailable returns null because claimedID query does not return an array or "id" does not exist. This query failed: ' . $claimIdQuery, 'debug', false);
581 $this->database->query("UNLOCK TABLES");
582 return null;
583 }
584
585 $claimedActionId = $claimedId['id'];
586
587
588
589
590
591
592 $claimQuery = "UPDATE {$tableName}
593 SET status='{$processing}', claimed_at='{$now}'
594 WHERE id=$claimedActionId;";
595 $claimed = $this->database->query($claimQuery);
596 $this->database->query("UNLOCK TABLES");
597
598 if (!$claimed) {
599
600 debug_log('Queue getNextAvailable returns null the process could not lock the row. This query failed: ' . $claimQuery, 'debug', false);
601 return null;
602 }
603
604
605 unset($this->actionCaches[$claimedActionId]);
606 $actionObject = $this->getAction($claimedActionId);
607
608 if ($actionObject instanceof Action) {
609 $this->actionCaches[$claimedActionId] = $actionObject->toArray();
610 }
611
612 return $actionObject;
613 }
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629 public function count($status = null, $jobId = null)
630 {
631 if (!$this->tableExists()) {
632 return 0;
633 }
634
635 $tableName = self::getTableName();
636
637 $jobClause = '';
638 if (isset($jobId)) {
639 $jobIdsInterval = $this->escapeInterval((array)$jobId);
640 $jobClause = "AND jobId IN ({$jobIdsInterval})";
641 }
642
643 if (empty($status) || $status === Queue::STATUS_ANY) {
644 $countQuery = "SELECT COUNT(id) FROM {$tableName} WHERE 1=1 {$jobClause}";
645 } else {
646 $statuses = $this->escapeInterval((array)$status);
647 $countQuery = "SELECT COUNT(id) FROM {$tableName} WHERE status IN ({$statuses}) {$jobClause}";
648 }
649
650 $countResult = $this->database->query($countQuery);
651
652 if ($countResult === false) {
653 $error = $this->database->error();
654
655 if (!empty($error)) {
656 \WPStaging\functions\debug_log(json_encode([
657 'root' => 'Error while trying to count Actions.',
658 'class' => get_class($this),
659 'query' => $countQuery,
660 'error' => $error,
661 ]));
662 }
663
664
665 return 0;
666 }
667
668 $count = $this->database->fetchRow($countResult);
669
670 return (array_sum((array)$count));
671 }
672
673
674
675
676 public function getLastUpdatedAtTimestamp()
677 {
678 if (!$this->tableExists()) {
679 return 0;
680 }
681
682 $tableName = self::getTableName();
683 $ready = self::STATUS_READY;
684 $proc = self::STATUS_PROCESSING;
685
686 $query = "SELECT MAX(updated_at) FROM {$tableName} WHERE status IN ('{$ready}','{$proc}')";
687 $result = $this->database->query($query);
688
689 if ($result === false) {
690 return 0;
691 }
692
693 $row = $this->database->fetchRow($result);
694 if (empty($row)) {
695 return 0;
696 }
697
698 $value = is_array($row) ? reset($row) : $row;
699 if (empty($value)) {
700 return 0;
701 }
702
703
704
705 $timezone = function_exists('wp_timezone') ? wp_timezone() : new \DateTimeZone('UTC');
706 try {
707 $parsed = new \DateTimeImmutable((string)$value, $timezone);
708 return $parsed->getTimestamp();
709 } catch (\Exception $e) {
710 return 0;
711 }
712 }
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732 public function updateActionStatus($action, $newStatus, $unsafely = false)
733 {
734 $actionId = absint($action instanceof Action ? $action->id : (int)$action);
735 $tableName = self::getTableName();
736 $status = $this->database->escape($newStatus);
737 $now = current_time('mysql');
738
739 $this->unlockQueueTable();
740
741 if ($status !== self::STATUS_PROCESSING) {
742
743 $statusUpdateQuery = "UPDATE {$tableName} SET status='{$status}', claimed_at=NULL, updated_at='{$now}' WHERE id={$actionId}";
744 } else {
745 if (!$unsafely) {
746
747 throw new QueueException('Marking actions as Processing should only be done using the getNextAvailable method!');
748 }
749
750
751 $statusUpdateQuery = "UPDATE {$tableName} SET status='{$status}', claimed_at='{$now}', updated_at='{$now}' WHERE id={$actionId} ";
752 }
753
754 $updated = $this->database->query($statusUpdateQuery);
755
756 if (!$updated && $this->reconnectDatabase()) {
757 $updated = $this->database->query($statusUpdateQuery);
758 }
759
760 if (!$updated) {
761 \WPStaging\functions\debug_log(json_encode([
762 'root' => 'Error while trying to update Action status.',
763 'class' => get_class($this),
764 'query' => $statusUpdateQuery,
765 'error' => $this->database->error(),
766 ]));
767
768 return false;
769 }
770
771
772 unset($this->actionCaches[$actionId]);
773
774 return $actionId;
775 }
776
777
778
779
780
781
782 private function getCreateTableSql()
783 {
784 global $wpdb;
785 $collate = $wpdb->collate;
786 $queueTable = self::getTableName();
787 $tableSql = "CREATE TABLE IF NOT EXISTS {$queueTable} (
788 id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
789 action VARCHAR(1000) NOT NULL,
790 jobId VARCHAR(1000) DEFAULT NULL,
791 status CHAR(20) NOT NULL DEFAULT 'ready',
792 priority BIGINT(20) NOT NULL DEFAULT 0,
793 args LONGTEXT DEFAULT NULL,
794 custom LONGTEXT DEFAULT NULL,
795 claimed_at DATETIME DEFAULT NULL,
796 updated_at DATETIME DEFAULT NULL,
797 PRIMARY KEY (id)
798 )";
799
800 if (!empty($collate)) {
801 $tableSql .= " COLLATE {$collate}";
802 }
803
804 return $tableSql;
805 }
806
807
808
809
810
811
812
813
814
815 public function dropTable()
816 {
817 $tableName = self::getTableName();
818 $query = "DROP TABLE IF EXISTS {$tableName}";
819 $this->database->query($query);
820 $this->tableState = self::TABLE_NOT_EXIST;
821
822 return !$this->tableExists();
823 }
824
825
826
827
828
829
830
831 public function lastError()
832 {
833 if ($this->database === null) {
834 return '';
835 }
836
837 return (string)$this->database->error();
838 }
839
840
841
842
843
844
845
846
847
848
849 private function fetchActionRow($actionId)
850 {
851 $actionId = absint($actionId);
852
853 if (empty($actionId)) {
854 return null;
855 }
856
857 $tableName = self::getTableName();
858 $fetchQuery = "SELECT * FROM {$tableName} WHERE id={$actionId}";
859 $fetchResult = $this->database->query($fetchQuery);
860
861 if ($fetchResult === false) {
862
863 return null;
864 }
865
866 $row = $this->database->fetchAssoc($fetchResult);
867
868 return is_array($row) ? $row : null;
869 }
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885 public function getAction($actionId, $force = false)
886 {
887 debug_log('Queue getAction is trying to get action ID ' . $actionId, 'debug', false);
888 if ($force || empty($this->actionCaches[$actionId])) {
889 $row = $this->fetchActionRow($actionId);
890
891 debug_log(wp_json_encode($row), 'debug', false);
892
893 if ($row !== null) {
894 $this->actionCaches[$actionId] = $row;
895 }
896 }
897
898 return isset($this->actionCaches[$actionId]) ?
899 Action::fromDbRow($this->actionCaches[$actionId])
900 : null;
901 }
902
903
904
905
906
907
908
909
910
911
912
913 public function getSupportedActionStatuses()
914 {
915 return [
916 self::STATUS_PROCESSING,
917 self::STATUS_READY,
918 self::STATUS_COMPLETED,
919 ];
920 }
921
922
923
924
925
926
927
928
929
930 public function getDanglingBreakpointDate()
931 {
932 return $this->getBreakpointDate(HOUR_IN_SECONDS);
933 }
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952 public function markDanglingAs(string $newStatus, $breakpointDate = null, bool $updateUpdatedAt = false): int
953 {
954 if (static::TABLE_NOT_EXIST === $this->checkTable()) {
955 debug_log('Queue markDanglingAs: The table does not exist so there is nothing to update.', 'debug', false);
956 return 0;
957 }
958
959 $this->unlockQueueTable();
960
961 $tableName = self::getTableName();
962 $newStatus = $this->database->escape($newStatus);
963 $danglingBreakpoint = empty($breakpointDate) ? $this->getDanglingBreakpointDate()->format('Y-m-d H:i:s') : $breakpointDate->format('Y-m-d H:i:s');
964 $now = current_time('mysql');
965 $updatedAtQuery = $updateUpdatedAt ? ", updated_at='{$now}'" : '';
966 $markQuery = "UPDATE {$tableName}
967 SET status='{$newStatus}', claimed_at=NULL{$updatedAtQuery}
968 WHERE claimed_at IS NOT NULL
969 AND claimed_at < '{$danglingBreakpoint}'";
970 $markResult = $this->database->query($markQuery);
971
972 if ($markResult === false) {
973 \WPStaging\functions\debug_log(json_encode([
974 'root' => 'Error while trying to mark dangling Actions.',
975 'class' => get_class($this),
976 'query' => $markQuery,
977 'error' => $this->database->error(),
978 ]));
979
980 return 0;
981 }
982
983 if (isset($this->database->link->affected_rows)) {
984 $marked = $this->database->link->affected_rows;
985 } else {
986 $marked = 0;
987 }
988
989 debug_log("Marked $marked actions as dangling.", 'debug', false);
990
991 return (int)$marked;
992 }
993
994
995
996
997
998
999
1000
1001
1002 public function maybeFireAjaxAction()
1003 {
1004
1005 if (!$this->count(self::STATUS_READY)) {
1006 return false;
1007 }
1008
1009
1010 return $this->fireAjaxAction();
1011 }
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021 private function escapeInterval(array $values)
1022 {
1023 return implode(',', array_map(function ($value) {
1024 return "'" . $this->database->escape($value) . "'";
1025 }, (array)$values));
1026 }
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038 public function cancelJob($jobId)
1039 {
1040 if (static::TABLE_NOT_EXIST === $this->checkTable()) {
1041 debug_log('Queue cancelJob: The table does not exist so there is nothing to cancel.', 'info', false);
1042 return 0;
1043 }
1044
1045 $this->unlockQueueTable();
1046
1047 $tableName = self::getTableName();
1048 $newStatus = self::STATUS_CANCELED;
1049 $jobIds = (array)$jobId;
1050 $jobIdsInterval = $this->escapeInterval($jobIds);
1051 $now = current_time('mysql');
1052 $cancelQuery = "UPDATE {$tableName}
1053 SET status='{$newStatus}', updated_at='{$now}'
1054 WHERE jobId in ({$jobIdsInterval})
1055 AND status NOT IN ('" . self::STATUS_COMPLETED . "', '" . self::STATUS_CANCELED . "', '" . self::STATUS_FAILED . "')";
1056 $cancelResult = $this->database->query($cancelQuery);
1057
1058 if ($cancelResult === false) {
1059 \WPStaging\functions\debug_log(json_encode([
1060 'root' => 'Error while trying to cancel Actions.',
1061 'class' => get_class($this),
1062 'query' => $cancelQuery,
1063 'error' => $this->database->error(),
1064 ]));
1065
1066 return 0;
1067 }
1068
1069 if (isset($this->database->link->affected_rows)) {
1070 $canceled = $this->database->link->affected_rows;
1071 } else {
1072 $canceled = 0;
1073 }
1074
1075 $this->invalidateActionCachesByJobId($jobIds);
1076
1077 return (int)$canceled;
1078 }
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088 private function invalidateActionCachesByJobId(array $jobIds)
1089 {
1090 array_walk($this->actionCaches, static function (&$cachedAction) use ($jobIds) {
1091 if (!empty($cachedAction['jobId']) && in_array($cachedAction['jobId'], $jobIds, true)) {
1092 $cachedAction = null;
1093 }
1094 });
1095 }
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116 public function updateActionFields($action, array $updates, $unsafely = false)
1117 {
1118 if (!$unsafely) {
1119
1120 throw new QueueException(
1121 'Updating Action fields has the potential of disrupting the Queue functions.'
1122 );
1123 }
1124
1125 if (isset($updates['id'])) {
1126
1127 throw new QueueException(
1128 'Updating an Action ID is never allowed.'
1129 );
1130 }
1131
1132 $actionId = absint($action instanceof Action ? $action->id : (int)$action);
1133 $tableName = self::getTableName();
1134
1135 $assignmentsList = $this->buildAssignmentsList($updates);
1136 $statusUpdateQuery = "UPDATE {$tableName} SET {$assignmentsList} WHERE id={$actionId}";
1137
1138 $this->unlockQueueTable();
1139
1140 $updated = $this->database->query($statusUpdateQuery);
1141
1142 if (!$updated && $this->reconnectDatabase()) {
1143 $updated = $this->database->query($statusUpdateQuery);
1144 }
1145
1146 if ($updated === false) {
1147 \WPStaging\functions\debug_log(json_encode([
1148 'root' => 'Error while trying to update Action field.',
1149 'class' => get_class($this),
1150 'query' => $statusUpdateQuery,
1151 'error' => $this->database->error(),
1152 ]));
1153
1154 return false;
1155 }
1156
1157
1158 unset($this->actionCaches[$actionId]);
1159
1160 return $actionId;
1161 }
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171 private function buildAssignmentsList(array $assignments)
1172 {
1173 $assignmentList = [];
1174
1175 array_walk($assignments, function ($value, $key) use (&$assignmentList) {
1176 if ($value === '') {
1177
1178 return;
1179 }
1180
1181 $escapedKey = $this->database->escape($key);
1182
1183 if ($key === 'priority') {
1184
1185 $escapedValue = (int)$value;
1186 $assignmentList[] = "{$escapedKey}={$escapedValue}";
1187 } elseif ($key === 'args' || $key === 'custom') {
1188 global $wpdb;
1189 $assignmentList[] = $wpdb->prepare("{$escapedKey}=%s", maybe_serialize($value));
1190 } else {
1191 $escapedValue = $this->database->escape($value);
1192 $assignmentList[] = "{$escapedKey}='{$escapedValue}'";
1193 }
1194 });
1195
1196 return implode(', ', $assignmentList);
1197 }
1198
1199
1200
1201
1202
1203
1204
1205
1206 public function getCleanupBreakpointDate(): DateTimeImmutable
1207 {
1208 return $this->getBreakpointDate(WEEK_IN_SECONDS);
1209 }
1210
1211
1212
1213
1214
1215
1216
1217
1218 public function getStalledBreakpointDate(): DateTimeImmutable
1219 {
1220 return $this->getBreakpointDate(self::STALLED_ACTIONS_BREAKPOINT_IN_MINS * MINUTE_IN_SECONDS);
1221 }
1222
1223
1224
1225
1226
1227
1228
1229 public function cleanup()
1230 {
1231 if (static::TABLE_NOT_EXIST === $this->checkTable()) {
1232 debug_log('Queue Cleanup: The table does not exist so there is nothing to update.', 'info', false);
1233 return 0;
1234 }
1235
1236 $tableName = self::getTableName();
1237 $cleanupBreakpoint = $this->getCleanupBreakpointDate()->format('Y-m-d H:i:s');
1238 $cleanableStati = $this->escapeInterval([
1239 self::STATUS_READY,
1240 self::STATUS_COMPLETED,
1241 self::STATUS_FAILED,
1242 self::STATUS_CANCELED,
1243 ]);
1244 $cleanupQuery = "DELETE FROM {$tableName}
1245 WHERE updated_at < '{$cleanupBreakpoint}'
1246 AND status in ({$cleanableStati})";
1247 $cleanupResult = $this->database->query($cleanupQuery);
1248
1249 if ($cleanupResult === false) {
1250 \WPStaging\functions\debug_log(json_encode([
1251 'root' => 'Error while trying to cleanup Actions.',
1252 'class' => get_class($this),
1253 'query' => $cleanupQuery,
1254 'error' => $this->database->error(),
1255 ]));
1256
1257 return 0;
1258 }
1259
1260 if (isset($this->database->link->affected_rows)) {
1261 $removed = $this->database->link->affected_rows;
1262 } else {
1263 $removed = 0;
1264 }
1265
1266 debug_log("Removed $removed actions that were last updated before $cleanupBreakpoint.", 'info', false);
1267
1268 return $removed;
1269 }
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279 public function countActionsByScheduleId($scheduleId, $statuses = [])
1280 {
1281 if (static::TABLE_NOT_EXIST === $this->checkTable()) {
1282 debug_log('Count actions by ScheduleId: The table does not exist so there is nothing to do.', 'info', false);
1283 return 0;
1284 }
1285
1286 $tableName = self::getTableName();
1287
1288 $countQuery = "SELECT COUNT(*) as actions_count FROM {$tableName}
1289 WHERE {$this->getWhereConditionByScheduleIdAndStatus($scheduleId, $statuses)};";
1290
1291 $countResult = $this->database->query($countQuery);
1292
1293 if ($countResult === false) {
1294 debug_log(json_encode([
1295 'root' => 'Error while trying to count Actions for the scheduleId: "' . $scheduleId . '".',
1296 'class' => get_class($this),
1297 'query' => $countQuery,
1298 'error' => $this->database->error(),
1299 ]));
1300
1301 return false;
1302 }
1303
1304 if ($this->database->numRows($countResult) === 0) {
1305 return 0;
1306 }
1307
1308 $count = $this->database->fetchAssoc($countResult);
1309
1310 return (int)$count['actions_count'];
1311 }
1312
1313
1314
1315
1316
1317
1318 public function cleanupActionsByScheduleId($scheduleId, $statuses = [])
1319 {
1320 if (static::TABLE_NOT_EXIST === $this->checkTable()) {
1321 debug_log('Actions Cleanup by ScheduleId: The table does not exist so there is nothing to update.', 'info', false);
1322 return 0;
1323 }
1324
1325 $tableName = self::getTableName();
1326
1327 $this->startBenchmark();
1328 $cleanupQuery = "DELETE FROM {$tableName} WHERE {$this->getWhereConditionByScheduleIdAndStatus($scheduleId, $statuses)};";
1329 $cleanupResult = $this->database->query($cleanupQuery);
1330 $this->finishBenchmark('cleanupActionsByScheduleId clean up query . ' . $cleanupQuery);
1331
1332 if ($cleanupResult === false) {
1333 debug_log(json_encode([
1334 'root' => 'Error while trying to cleanup Actions for the scheduleId: "' . $scheduleId . '".',
1335 'class' => get_class($this),
1336 'query' => $cleanupQuery,
1337 'error' => $this->database->error(),
1338 ]));
1339
1340 return false;
1341 }
1342
1343 if (isset($this->database->link->affected_rows)) {
1344 $removed = $this->database->link->affected_rows;
1345 } else {
1346 $removed = 0;
1347 }
1348
1349 debug_log("Removed $removed actions for the scheduleId: '$scheduleId'.", 'info', false);
1350
1351 return $removed;
1352 }
1353
1354
1355
1356
1357
1358 public function purgeQueueTable()
1359 {
1360 if (static::TABLE_NOT_EXIST === $this->checkTable()) {
1361 debug_log('Queue Cleanup: The table does not exist so there is nothing to update.', 'info', false);
1362 return false;
1363 }
1364
1365 $tableName = self::getTableName();
1366
1367 $cleanupQuery = "TRUNCATE {$tableName}";
1368 $cleanupResult = $this->database->query($cleanupQuery);
1369
1370 if ($cleanupResult === false) {
1371 \WPStaging\functions\debug_log(json_encode([
1372 'root' => 'Error while trying to cleanup Actions.',
1373 'class' => get_class($this),
1374 'query' => $cleanupQuery,
1375 'error' => $this->database->error(),
1376 ]));
1377
1378 return false;
1379 }
1380
1381 if (isset($this->database->link->affected_rows)) {
1382 $removed = $this->database->link->affected_rows;
1383 } else {
1384 $removed = 0;
1385 }
1386
1387 debug_log("Removed $removed actions from the queue during cleanup.", 'info', false);
1388
1389 return $removed;
1390 }
1391
1392
1393
1394
1395
1396
1397
1398 public function getLatestUpdatedAction($jobId)
1399 {
1400 if (!is_string($jobId) || $this->tableState === self::TABLE_NOT_EXIST) {
1401 return null;
1402 }
1403
1404 $tableName = self::getTableName();
1405 $escapedJobId = $this->database->escape(trim($jobId));
1406 $query = "SELECT id FROM $tableName WHERE jobId = '$escapedJobId' ORDER BY updated_at DESC, id DESC LIMIT 1";
1407
1408 $result = $this->database->query($query);
1409
1410 if ($result === false) {
1411 error_log(json_encode([
1412 'root' => 'Error while trying to fetch latest updated Action.',
1413 'class' => get_class($this),
1414 'query' => $query,
1415 'error' => $this->database->error(),
1416 'jobId' => $jobId,
1417 ]));
1418
1419
1420 return null;
1421 }
1422
1423 $row = $this->database->fetchAssoc($result);
1424
1425 if (!isset($row['id'])) {
1426
1427 return null;
1428 }
1429
1430 return $this->getAction($row['id']);
1431 }
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442 public function setUnlocker($unlocker)
1443 {
1444 $this->unlocker = $unlocker;
1445
1446 return $this;
1447 }
1448
1449
1450
1451
1452 public function maybeAddResponseColumnToTable(): bool
1453 {
1454 $tablename = self::getTableName();
1455
1456 $query = "SHOW COLUMNS FROM {$tablename} LIKE 'response'";
1457 $result = $this->database->query($query);
1458
1459
1460 if ($result === true) {
1461 return true;
1462 }
1463
1464 return $this->database->query($this->getQueryToAddResponseColumnToTable($tablename));
1465 }
1466
1467
1468
1469
1470
1471 protected function getQueryToAddResponseColumnToTable(string $tablename): string
1472 {
1473 return "ALTER TABLE `{$tablename}` ADD COLUMN `response` LONGTEXT DEFAULT NULL AFTER `args`";
1474 }
1475
1476
1477
1478
1479 protected function addUpgradeQueries(&$dbdeltaQueries)
1480 {
1481 $tablename = self::getTableName();
1482 $currentTableVersion = $this->getCurrentTableVersion();
1483
1484 $this->maybeAddUpgradeTableQueryForResponseField($tablename, $currentTableVersion, $dbdeltaQueries);
1485 }
1486
1487
1488
1489
1490
1491
1492
1493 protected function maybeAddUpgradeTableQueryForResponseField(string $tablename, string $version, array &$dbdeltaQueries)
1494 {
1495
1496 $deprecatedTableVersionOption = get_option(self::QUEUE_TABLE_VERSION_KEY, false);
1497
1498
1499 if (version_compare($version, '1.0.0', '<') && $deprecatedTableVersionOption === false) {
1500 $dbdeltaQueries[] = $this->getQueryToAddResponseColumnToTable($tablename);
1501 return;
1502 }
1503
1504
1505 delete_option(self::QUEUE_TABLE_VERSION_KEY);
1506 if (version_compare($deprecatedTableVersionOption, '4.9.1', '<')) {
1507 $dbdeltaQueries[] = $this->getQueryToAddResponseColumnToTable($tablename);
1508 }
1509 }
1510
1511
1512
1513
1514
1515
1516
1517 private function unlockQueueTable()
1518 {
1519 if (!$this->phpAdapter->isCallable($this->unlocker)) {
1520 return;
1521 }
1522
1523 call_user_func($this->unlocker);
1524 }
1525
1526
1527
1528
1529
1530
1531
1532 private function getWhereConditionByScheduleIdAndStatus($scheduleId, $statuses = [])
1533 {
1534 $scheduleIdSerializedRow = 's:10:"scheduleId";s:' . strlen((string)$scheduleId) . ':"' . $scheduleId . '";';
1535 $whereCondition = "args LIKE '%$scheduleIdSerializedRow%'";
1536 if (empty($statuses)) {
1537 return $whereCondition;
1538 }
1539
1540 $statuses = array_map(function ($status) {
1541 return "'" . $this->database->escape($status) . "'";
1542 }, $statuses);
1543
1544 $whereCondition .= " AND status IN (" . implode(',', $statuses) . ")";
1545
1546 return $whereCondition;
1547 }
1548
1549
1550
1551
1552 private function reconnectDatabase(): bool
1553 {
1554 if (stripos($this->database->error(), 'MySQL server has gone away') !== false) {
1555 $this->database = WPStaging::make(DatabaseAdapter::class)->getClient();
1556 return true;
1557 }
1558
1559 return false;
1560 }
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570 private function getBreakpointDate($interval): DateTimeImmutable
1571 {
1572 try {
1573 $breakpointDate = new DateTimeImmutable(date('Y-m-d H:i:s'));
1574 $breakpointDate = $breakpointDate->setTimestamp($breakpointDate->getTimestamp() - $interval);
1575 } catch (Exception $e) {
1576
1577
1578
1579
1580 $breakpointDate = new DateTimeImmutable('2020-01-01 00:00:00');
1581 }
1582
1583 return $breakpointDate;
1584 }
1585 }
1586