Test Failed
Push — ravinderk-feature/upgrdae-auto... ( 94c904 )
by Ravinder
07:51
created

Give_Background_Updater::lock_process()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 28
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 12
nc 4
nop 0
dl 0
loc 28
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * Background Updater
4
 *
5
 * Uses https://github.com/A5hleyRich/wp-background-processing to handle DB
6
 * updates in the background.
7
 *
8
 * @class    Give_Background_Updater
9
 * @version  2.0.0
10
 * @package  Give/Classes
11
 * @category Class
12
 * @author   WordImpress
13
 */
14
if ( ! defined( 'ABSPATH' ) ) {
15
	exit;
16
}
17
18
/**
19
 * Give_Background_Updater Class.
20
 */
21
class Give_Background_Updater extends WP_Background_Process {
22
23
	/**
24
	 * @var string
25
	 */
26
	protected $action = 'give_db_updater';
27
28
	/**
29
	 * Dispatch updater.
30
	 *
31
	 * Updater will still run via cron job if this fails for any reason.
32
	 */
33
	public function dispatch() {
34
		/* @var WP_Background_Process $dispatched */
35
		parent::dispatch();
36
	}
37
38
39
	/**
40
	 * Get all batches.
41
	 *
42
	 * @since  2.0
43
	 * @access public
44
	 * @return stdClass
45
	 */
46
	public function get_all_batch() {
47
		return parent::get_batch();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (get_batch() instead of get_all_batch()). Are you sure this is correct? If so, you might want to change this to $this->get_batch().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
48
	}
49
50
	/**
51
	 * Lock process
52
	 *
53
	 * Lock the process so that multiple instances can't run simultaneously.
54
	 * Override if applicable, but the duration should be greater than that
55
	 * defined in the time_exceeded() method.
56
	 *
57
	 *
58
	 * @since 2.0.3
59
	 */
60
	protected function lock_process() {
61
		// Check if admin want to pause upgrade.
62
		if( get_option('give_pause_upgrade') ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
63
			self::flush_cache();
64
65
			delete_option( 'give_paused_batches' );
66
67
			Give_Updates::get_instance()->__pause_db_update( true );
68
			delete_option('give_pause_upgrade');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
69
70
			/**
71
			 * Fire action when pause db updates
72
			 *
73
			 * @since 2.0.1
74
			 */
75
			do_action( 'give_pause_db_upgrade', Give_Updates::get_instance() );
76
77
			wp_die();
78
		}
79
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
80
81
		$this->start_time = time(); // Set start time of current process.
82
83
		$lock_duration = ( property_exists( $this, 'queue_lock_time' ) ) ? $this->queue_lock_time : 60; // 1 minute
84
		$lock_duration = apply_filters( $this->identifier . '_queue_lock_time', $lock_duration );
85
86
		set_site_transient( $this->identifier . '_process_lock', microtime(), $lock_duration );
87
	}
88
89
	/**
90
	 * Handle cron healthcheck
91
	 *
92
	 * Restart the background process if not already running
93
	 * and data exists in the queue.
94
	 */
95
	public function handle_cron_healthcheck() {
96
		if ( $this->is_process_running() || $this->is_paused_process()  ) {
97
			// Background process already running.
98
			return;
99
		}
100
101
		if ( $this->is_queue_empty() ) {
102
			// No data to process.
103
			$this->clear_scheduled_event();
104
105
			return;
106
		}
107
108
		$this->handle();
109
	}
110
111
	/**
112
	 * Schedule fallback event.
113
	 */
114
	protected function schedule_event() {
115
		if ( ! wp_next_scheduled( $this->cron_hook_identifier ) && ! $this->is_paused_process() ) {
116
			wp_schedule_event( time() + 10, $this->cron_interval_identifier, $this->cron_hook_identifier );
117
		}
118
	}
119
120
	/**
121
	 * Task
122
	 *
123
	 * Override this method to perform any actions required on each
124
	 * queue item. Return the modified item for further processing
125
	 * in the next pass through. Or, return false to remove the
126
	 * item from the queue.
127
	 *
128
	 * @param array $update Update info
129
	 *
130
	 * @return mixed
131
	 */
132
	protected function task( $update ) {
133
		// Pause upgrade immediately if admin pausing upgrades.
134
		if( $this->is_paused_process() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
135
			wp_die();
136
		}
137
138
		if ( empty( $update ) ) {
139
			return false;
140
		}
141
142
		// Delete cache.
143
		self::flush_cache();
144
145
		/* @var  Give_Updates $give_updates */
146
		$give_updates  = Give_Updates::get_instance();
147
		$resume_update = get_option(
148
			'give_doing_upgrade',
149
0 ignored issues
show
Coding Style introduced by
There should be no empty lines in a multi-line function call.
Loading history...
150
			// Default update.
151
			array(
152
				'update_info'      => $update,
153
				'step'             => 1,
154
				'update'           => 1,
155
				'heading'          => sprintf( 'Update %s of {update_count}', 1 ),
156
				'percentage'       => $give_updates->percentage,
157
				'total_percentage' => 0,
158
			)
159
		);
160
161
		// Continuously skip update if previous update does not complete yet.
162
		if (
163
			$resume_update['update_info']['id'] !== $update['id'] &&
164
			! give_has_upgrade_completed( $resume_update['update_info']['id'] )
165
		) {
166
			return $update;
167
		}
168
169
		// Set params.
170
		$resume_update['update_info'] = $update;
171
		$give_updates->step           = absint( $resume_update['step'] );
172
		$give_updates->update         = absint( $resume_update['update'] );
173
		$is_parent_update_completed   = $give_updates->is_parent_updates_completed( $update );
174
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
175
176
		// Skip update if dependency update does not complete yet.
177
		if ( empty( $is_parent_update_completed ) ) {
178
			// @todo: set error when you have only one update with invalid dependency
179
			if ( ! is_null( $is_parent_update_completed ) ) {
180
				return $update;
181
			}
182
183
			return false;
184
		}
185
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
186
187
		// Pause upgrade immediately if found following:
188
		// 1. Running update number greater then total update count
189
		// 2. Processing percentage greater then 100%
190
		if( (
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
191
			101 < $resume_update['total_percentage'] ) ||
192
		    ( $give_updates->get_total_db_update_count() < $resume_update['update'] ) ||
193
		    ! in_array( $resume_update['update_info']['id'], $give_updates->get_update_ids() )
194
		) {
195
			if( ! $this->is_paused_process() ){
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
196
				$give_updates->__pause_db_update(true);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
197
			}
198
199
			update_option( 'give_upgrade_error', 1 );
200
201
			$log_data = 'Update Task' . "\n";
202
			$log_data .= "Total update count: {$give_updates->get_total_db_update_count()}\n";
203
			$log_data .= 'Update IDs: ' . print_r( $give_updates->get_update_ids() , true );
0 ignored issues
show
introduced by
The use of function print_r() is discouraged
Loading history...
204
205
			Give()->logs->add( 'Update Error', $log_data, 0, 'update' );
206
207
			wp_die();
208
		}
209
210
		// Disable cache.
211
		Give_Cache::disable();
212
213
		try{
214
			// Run update.
215
			if ( is_array( $update['callback'] ) ) {
216
				$update['callback'][0]->$update['callback'][1]();
217
			} else {
218
				$update['callback']();
219
			}
220
		} catch ( Exception $e ){
221
222
			if( ! $this->is_paused_process() ){
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
223
				$give_updates->__pause_db_update(true);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
224
			}
225
226
			$log_data = 'Update Task' . "\n";
227
			$log_data .= print_r( $resume_update, true ) . "\n\n";
0 ignored issues
show
introduced by
The use of function print_r() is discouraged
Loading history...
228
			$log_data .= "Error\n {$e->getMessage()}";
229
230
			Give()->logs->add( 'Update Error', $log_data, 0, 'update' );
231
			update_option( 'give_upgrade_error', 1 );
232
233
			wp_die();
234
		}
235
236
		// Set update info.
237
		$doing_upgrade_args = array(
238
			'update_info'      => $update,
239
			'step'             => ++ $give_updates->step,
240
			'update'           => $give_updates->update,
241
			'heading'          => sprintf( 'Update %s of %s', $give_updates->update, get_option( 'give_db_update_count' ) ),
242
			'percentage'       => $give_updates->percentage,
243
			'total_percentage' => $give_updates->get_db_update_processing_percentage(),
244
		);
245
246
		// Cache upgrade.
247
		update_option( 'give_doing_upgrade', $doing_upgrade_args );
248
249
		// Enable cache.
250
		Give_Cache::enable();
251
252
		// Check if current update completed or not.
253
		if ( give_has_upgrade_completed( $update['id'] ) ) {
254
			return false;
255
		}
256
257
		return $update;
258
	}
259
260
	/**
261
	 * Complete
262
	 *
263
	 * Override if applicable, but ensure that the below actions are
264
	 * performed, or, call parent::complete().
265
	 */
266
	protected function complete() {
267
		if ( $this->is_paused_process() ) {
268
			return false;
269
		}
270
271
		parent::complete();
272
273
		delete_option( 'give_upgrade_error' );
274
		delete_option( 'give_db_update_count' );
275
		delete_option( 'give_doing_upgrade' );
276
		add_option( 'give_show_db_upgrade_complete_notice', 1, '', 'no' );
277
278
		// Flush cache.
279
		Give_Cache::get_instance()->flush_cache();
280
281
		if ( $cache_keys = Give_Cache::get_options_like( '' ) ) {
282
			Give_Cache::delete( $cache_keys );
283
		}
284
	}
285
286
	/**
287
	 * Get memory limit
288
	 *
289
	 * @return int
290
	 */
291
	protected function get_memory_limit() {
292
		if ( function_exists( 'ini_get' ) ) {
293
			$memory_limit = ini_get( 'memory_limit' );
294
		} else {
295
			// Sensible default.
296
			$memory_limit = '128M';
297
		}
298
299
		if ( ! $memory_limit || '-1' === $memory_limit ) {
300
			// Unlimited, set to 32GB.
301
			$memory_limit = '32000M';
302
		}
303
304
		return intval( $memory_limit ) * 1024 * 1024;
305
	}
306
307
	/**
308
	 * Maybe process queue
309
	 *
310
	 * Checks whether data exists within the queue and that
311
	 * the process is not already running.
312
	 */
313
	public function maybe_handle() {
314
		// Don't lock up other requests while processing
315
		session_write_close();
0 ignored issues
show
introduced by
The use of PHP session function session_write_close() is prohibited.
Loading history...
316
317
		if ( $this->is_process_running() || $this->is_paused_process() ) {
318
			// Background process already running.
319
			wp_die();
320
		}
321
322
		if ( $this->is_queue_empty() ) {
323
			// No data to process.
324
			wp_die();
325
		}
326
327
		check_ajax_referer( $this->identifier, 'nonce' );
328
329
		$this->handle();
330
331
		wp_die();
332
	}
333
334
335
	/**
336
	 * Check if backgound upgrade paused or not.
337
	 *
338
	 * @since 2.0
339
	 * @access public
340
	 * @return bool
341
	 */
342
	public function is_paused_process(){
343
		// Delete cache.
344
		wp_cache_delete( 'give_paused_batches', 'options' );
345
346
		$paused_batches = get_option('give_paused_batches');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
347
348
		return ! empty( $paused_batches );
349
	}
350
351
352
	/**
353
	 * Get identifier
354
	 *
355
	 * @since  2.0
356
	 * @access public
357
	 * @return mixed|string
358
	 */
359
	public function get_identifier() {
360
		return $this->identifier;
361
	}
362
363
	/**
364
	 * Get cron identifier
365
	 *
366
	 * @since  2.0
367
	 * @access public
368
	 * @return mixed|string
369
	 */
370
	public function get_cron_identifier() {
371
		return $this->cron_hook_identifier;
372
	}
373
374
375
	/**
376
	 * Flush background update related cache to prevent task to go to stalled state.
377
	 *
378
	 * @since 2.0.3
379
	 */
380
	public static function flush_cache() {
381
382
		$options = array(
383
			'give_completed_upgrades',
384
			'give_doing_upgrade',
385
			'give_paused_batches',
386
			'give_upgrade_error',
387
			'give_db_update_count',
388
			'give_doing_upgrade',
389
			'give_show_db_upgrade_complete_notice',
390
		);
391
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
392
393
		foreach ( $options as $option ) {
394
			wp_cache_delete( $option, 'options' );
395
		}
396
	}
397
}
398