PluginProbe ʕ •ᴥ•ʔ
Robin Image Optimizer – Unlimited Image Optimization, WebP & AVIF / trunk
Robin Image Optimizer – Unlimited Image Optimization, WebP & AVIF vtrunk
2.0.5 trunk 1.3.7 1.4.0 1.4.1 1.4.2 1.4.6 1.5.0 1.5.3 1.5.6 1.5.8 1.6.5 1.6.6 1.6.9 1.7.0 1.7.4 1.8.1 1.8.2 1.9.0 2.0.0 2.0.1 2.0.2 2.0.3 2.0.4
robin-image-optimizer / libs / factory / processing / includes / classes / wp-background-process.php
robin-image-optimizer / libs / factory / processing / includes / classes Last commit date
wp-async-request.php 5 months ago wp-background-process.php 5 months ago
wp-background-process.php
565 lines
1 <?php
2
3 namespace WBCR\Factory_Processing_759;
4
5 /**
6 * WP Background Process
7 *
8 * @package WP-Background-Processing
9 */
10
11 /**
12 * Abstract WP_Background_Process class.
13 *
14 * @abstract
15 * @extends WP_Async_Request
16 */
17 abstract class WP_Background_Process extends WP_Async_Request {
18
19 /**
20 * Action
21 *
22 * (default value: 'background_process')
23 *
24 * @var string
25 * @access protected
26 */
27 protected $action = 'background_process';
28
29 /**
30 * Start time of current process.
31 *
32 * (default value: 0)
33 *
34 * @var int
35 * @access protected
36 */
37 protected $start_time = 0;
38
39 /**
40 * Cron_hook_identifier
41 *
42 * @var mixed
43 * @access protected
44 */
45 protected $cron_hook_identifier;
46
47 /**
48 * Cron_interval_identifier
49 *
50 * @var mixed
51 * @access protected
52 */
53 protected $cron_interval_identifier;
54
55 /**
56 * Initiate new background process
57 */
58 public function __construct() {
59 parent::__construct();
60
61 $this->cron_hook_identifier = $this->identifier . '_cron';
62 $this->cron_interval_identifier = $this->identifier . '_cron_interval';
63
64 add_action( $this->cron_hook_identifier, [ $this, 'handle_cron_healthcheck' ] );
65 add_filter( 'cron_schedules', [ $this, 'schedule_cron_healthcheck' ] );
66 }
67
68 /**
69 * Dispatch
70 *
71 * @access public
72 * @return array|\WP_Error
73 */
74 public function dispatch() {
75 // Schedule the cron healthcheck.
76 $this->schedule_event();
77
78 // Perform remote post.
79 return parent::dispatch();
80 }
81
82 /**
83 * Push to queue
84 *
85 * @param mixed $data Data.
86 *
87 * @return $this
88 */
89 public function push_to_queue( $data ) {
90 $this->data[] = $data;
91
92 return $this;
93 }
94
95 /**
96 * Count of queue
97 *
98 * @return int
99 */
100 public function count_queue() {
101 return count( $this->data );
102 }
103
104 /**
105 * Save queue
106 *
107 * @return $this
108 */
109 public function save() {
110 $key = $this->generate_key();
111
112 if ( ! empty( $this->data ) ) {
113 update_site_option( $key, $this->data );
114 }
115
116 return $this;
117 }
118
119 /**
120 * Update queue
121 *
122 * @param string $key Key.
123 * @param array $data Data.
124 *
125 * @return $this
126 */
127 public function update( $key, $data ) {
128 if ( ! empty( $data ) ) {
129 update_site_option( $key, $data );
130 }
131
132 return $this;
133 }
134
135 /**
136 * Delete queue
137 *
138 * @param string $key Key.
139 *
140 * @return $this
141 */
142 public function delete( $key ) {
143 delete_site_option( $key );
144
145 return $this;
146 }
147
148 /**
149 * Stop queue
150 *
151 * @param string $key Key.
152 *
153 * @return $this
154 */
155 public function stop( $key ) {
156 $batch = get_site_option( $key );
157 $batch2[] = array_shift( $batch );
158
159 update_site_option( $key, $batch2 );
160
161 return $this;
162 }
163
164 /**
165 * Generate key
166 *
167 * Generates a unique key based on microtime. Queue items are
168 * given a unique key so that they can be merged upon save.
169 *
170 * @param int $length Length.
171 *
172 * @return string
173 */
174 protected function generate_key( $length = 64 ) {
175 $unique = md5( microtime() . rand() );
176 $prepend = $this->identifier . '_batch_';
177
178 return substr( $prepend . $unique, 0, $length );
179 }
180
181 /**
182 * Maybe process queue
183 *
184 * Checks whether data exists within the queue and that
185 * the process is not already running.
186 */
187 public function maybe_handle() {
188 // Don't lock up other requests while processing
189 session_write_close();
190
191 if ( $this->is_process_running() ) {
192 // Background process already running.
193 wp_die();
194 }
195
196 if ( $this->is_queue_empty() ) {
197 // No data to process.
198 wp_die();
199 }
200
201 check_ajax_referer( $this->identifier, 'nonce' );
202
203 $this->handle();
204
205 wp_die();
206 }
207
208 /**
209 * Is queue empty
210 *
211 * @return bool
212 */
213 protected function is_queue_empty() {
214 global $wpdb;
215
216 $table = $wpdb->options;
217 $column = 'option_name';
218
219 if ( is_multisite() ) {
220 $table = $wpdb->sitemeta;
221 $column = 'meta_key';
222 }
223
224 $key = $wpdb->esc_like( $this->identifier . '_batch_' ) . '%';
225
226 $count = $wpdb->get_var(
227 $wpdb->prepare(
228 "
229 SELECT COUNT(*)
230 FROM {$table}
231 WHERE {$column} LIKE %s
232 ",
233 $key
234 )
235 );
236
237 return ( $count > 0 ) ? false : true;
238 }
239
240 /**
241 * Is process running
242 *
243 * Check whether the current process is already running
244 * in a background process.
245 */
246 protected function is_process_running() {
247 if ( get_site_transient( $this->identifier . '_process_lock' ) ) {
248 // Process already running.
249 return true;
250 }
251
252 return false;
253 }
254
255 /**
256 * Lock process
257 *
258 * Lock the process so that multiple instances can't run simultaneously.
259 * Override if applicable, but the duration should be greater than that
260 * defined in the time_exceeded() method.
261 */
262 protected function lock_process() {
263 $this->start_time = time(); // Set start time of current process.
264
265 $lock_duration = ( property_exists( $this, 'queue_lock_time' ) ) ? $this->queue_lock_time : 60; // 1 minute
266 $lock_duration = apply_filters( $this->identifier . '_queue_lock_time', $lock_duration );
267
268 set_site_transient( $this->identifier . '_process_lock', microtime(), $lock_duration );
269 }
270
271 /**
272 * Unlock process
273 *
274 * Unlock the process so that other instances can spawn.
275 *
276 * @return $this
277 */
278 protected function unlock_process() {
279 delete_site_transient( $this->identifier . '_process_lock' );
280
281 return $this;
282 }
283
284 /**
285 * Get batch
286 *
287 * @return \stdClass Return the first batch from the queue
288 */
289 protected function get_batch() {
290 global $wpdb;
291
292 $table = $wpdb->options;
293 $column = 'option_name';
294 $key_column = 'option_id';
295 $value_column = 'option_value';
296
297 if ( is_multisite() ) {
298 $table = $wpdb->sitemeta;
299 $column = 'meta_key';
300 $key_column = 'meta_id';
301 $value_column = 'meta_value';
302 }
303
304 $key = $wpdb->esc_like( $this->identifier . '_batch_' ) . '%';
305
306 $query = $wpdb->get_row(
307 $wpdb->prepare(
308 "
309 SELECT *
310 FROM {$table}
311 WHERE {$column} LIKE %s
312 ORDER BY {$key_column} ASC
313 LIMIT 1
314 ",
315 $key
316 )
317 );
318
319 $batch = new \stdClass();
320 $batch->key = $query->$column;
321 $batch->data = maybe_unserialize( $query->$value_column );
322
323 return $batch;
324 }
325
326 /**
327 * Handle
328 *
329 * Pass each queue item to the task handler, while remaining
330 * within server memory and time limit constraints.
331 */
332 protected function handle() {
333 $this->handle_before();
334
335 $this->lock_process();
336 do {
337 $batch = $this->get_batch();
338
339 foreach ( $batch->data as $key => $value ) {
340 $task = $this->task( $value );
341
342 if ( false !== $task ) {
343 $batch->data[ $key ] = $task;
344 } else {
345 unset( $batch->data[ $key ] );
346 }
347
348 if ( $this->time_exceeded() || $this->memory_exceeded() ) {
349 // Batch limits reached.
350 break;
351 }
352 }
353
354 // Update or delete current batch.
355 if ( ! empty( $batch->data ) ) {
356 if ( ! $this->is_queue_empty() ) {
357 $this->update( $batch->key, $batch->data );
358 }
359 } else {
360 $this->delete( $batch->key );
361 }
362 } while ( ! $this->time_exceeded() && ! $this->memory_exceeded() && ! $this->is_queue_empty() );
363 $this->unlock_process();
364
365 $this->handle_after();
366
367 // Start next batch or complete process.
368 if ( ! $this->is_queue_empty() ) {
369 $this->dispatch();
370 } else {
371 $this->complete();
372 $this->handle_after_complete();
373 }
374
375 wp_die();
376 }
377
378 /**
379 * Fire before start handle the tasks
380 */
381 protected function handle_before() {
382 }
383
384 /**
385 * Fire after end handle the tasks
386 */
387 protected function handle_after() {
388 }
389
390 /**
391 * Fire after complete handle
392 */
393 protected function handle_after_complete() {
394 }
395
396 /**
397 * Memory exceeded
398 *
399 * Ensures the batch process never exceeds 90%
400 * of the maximum WordPress memory.
401 *
402 * @return bool
403 */
404 protected function memory_exceeded() {
405 $memory_limit = $this->get_memory_limit() * 0.9; // 90% of max memory
406 $current_memory = memory_get_usage( true );
407 $return = false;
408
409 if ( $current_memory >= $memory_limit ) {
410 $return = true;
411 }
412
413 return apply_filters( $this->identifier . '_memory_exceeded', $return );
414 }
415
416 /**
417 * Get memory limit
418 *
419 * @return int
420 */
421 protected function get_memory_limit() {
422 if ( function_exists( 'ini_get' ) ) {
423 $memory_limit = ini_get( 'memory_limit' );
424 } else {
425 // Sensible default.
426 $memory_limit = '128M';
427 }
428
429 if ( ! $memory_limit || - 1 === intval( $memory_limit ) ) {
430 // Unlimited, set to 32GB.
431 $memory_limit = '32000M';
432 }
433
434 return wp_convert_hr_to_bytes( $memory_limit );
435 }
436
437 /**
438 * Time exceeded.
439 *
440 * Ensures the batch never exceeds a sensible time limit.
441 * A timeout limit of 30s is common on shared hosting.
442 *
443 * @return bool
444 */
445 protected function time_exceeded() {
446 $finish = $this->start_time + apply_filters( $this->identifier . '_default_time_limit', 20 ); // 20 seconds
447 $return = false;
448
449 if ( time() >= $finish ) {
450 $return = true;
451 }
452
453 return apply_filters( $this->identifier . '_time_exceeded', $return );
454 }
455
456 /**
457 * Complete.
458 *
459 * Override if applicable, but ensure that the below actions are
460 * performed, or, call parent::complete().
461 */
462 protected function complete() {
463 // Unschedule the cron healthcheck.
464 $this->clear_scheduled_event();
465 }
466
467 /**
468 * Schedule cron healthcheck
469 *
470 * @access public
471 *
472 * @param mixed $schedules Schedules.
473 *
474 * @return mixed
475 */
476 public function schedule_cron_healthcheck( $schedules ) {
477 $interval = apply_filters( $this->identifier . '_cron_interval', 5 );
478
479 if ( property_exists( $this, 'cron_interval' ) ) {
480 $interval = apply_filters( $this->identifier . '_cron_interval', $this->cron_interval );
481 }
482
483 // Adds every 5 minutes to the existing schedules.
484 $schedules[ $this->identifier . '_cron_interval' ] = [
485 'interval' => MINUTE_IN_SECONDS * $interval,
486 // translators: %d is the number of minutes
487 'display' => sprintf( __( 'Every %d Minutes', 'robin-image-optimizer' ), $interval ),
488 ];
489
490 return $schedules;
491 }
492
493 /**
494 * Handle cron healthcheck
495 *
496 * Restart the background process if not already running
497 * and data exists in the queue.
498 */
499 public function handle_cron_healthcheck() {
500 if ( $this->is_process_running() ) {
501 // Background process already running.
502 exit;
503 }
504
505 if ( $this->is_queue_empty() ) {
506 // No data to process.
507 $this->clear_scheduled_event();
508 exit;
509 }
510
511 $this->handle();
512
513 exit;
514 }
515
516 /**
517 * Schedule event
518 */
519 protected function schedule_event() {
520 if ( ! wp_next_scheduled( $this->cron_hook_identifier ) ) {
521 wp_schedule_event( time(), $this->cron_interval_identifier, $this->cron_hook_identifier );
522 }
523 }
524
525 /**
526 * Clear scheduled event
527 */
528 protected function clear_scheduled_event() {
529 $timestamp = wp_next_scheduled( $this->cron_hook_identifier );
530
531 if ( $timestamp ) {
532 wp_unschedule_event( $timestamp, $this->cron_hook_identifier );
533 }
534 }
535
536 /**
537 * Cancel Process
538 *
539 * Stop processing queue items, clear cronjob and delete batch.
540 */
541 public function cancel_process() {
542 if ( ! $this->is_queue_empty() ) {
543 $batch = $this->get_batch();
544
545 $this->delete( $batch->key );
546
547 wp_clear_scheduled_hook( $this->cron_hook_identifier );
548 }
549 }
550
551 /**
552 * Task
553 *
554 * Override this method to perform any actions required on each
555 * queue item. Return the modified item for further processing
556 * in the next pass through. Or, return false to remove the
557 * item from the queue.
558 *
559 * @param mixed $item Queue item to iterate over.
560 *
561 * @return mixed
562 */
563 abstract protected function task( $item );
564 }
565