Completed
Pull Request — master (#1637)
by Ravinder
16:50
created

upgrade-functions.php ➔ give_v187_upgrades()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 62
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 41
nc 8
nop 0
dl 0
loc 62
ccs 0
cts 0
cp 0
crap 42
rs 8.6652
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 26 and the first side effect is on line 16.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Upgrade Functions
4
 *
5
 * @package     Give
6
 * @subpackage  Admin/Upgrades
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 * @since       1.0
10
 *
11
 * NOTICE: When adding new upgrade notices, please be sure to put the action into the upgrades array during install: /includes/install.php @ Appox Line 156
12
 */
13
14
// Exit if accessed directly.
15
if ( ! defined( 'ABSPATH' ) ) {
16
	exit;
17
}
18
19
20
/**
21
 * Perform automatic database upgrades when necessary.
22
 *
23
 * @since 1.6
24
 * @return void
25
 */
26
function give_do_automatic_upgrades() {
27
	$did_upgrade  = false;
28
	$give_version = preg_replace( '/[^0-9.].*/', '', get_option( 'give_version' ) );
29
30
	if ( ! $give_version ) {
31
		// 1.0 is the first version to use this option so we must add it.
32
		$give_version = '1.0';
33
	}
34
35
	switch ( true ) {
36
37
		case version_compare( $give_version, '1.6', '<' ) :
38
			give_v16_upgrades();
39
			$did_upgrade = true;
40
41
		case version_compare( $give_version, '1.7', '<' ) :
42
			give_v17_upgrades();
43
			$did_upgrade = true;
44
45
		case version_compare( $give_version, '1.8', '<' ) :
46
			give_v18_upgrades();
47
			$did_upgrade = true;
48
49
		case version_compare( $give_version, '1.8.7', '<' ) :
50
			give_v187_upgrades();
51
			$did_upgrade = true;
52
	}
53
54
	if ( $did_upgrade ) {
55
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
56
	}
57
}
58
59
add_action( 'admin_init', 'give_do_automatic_upgrades' );
60
add_action( 'give_upgrades', 'give_do_automatic_upgrades' );
61
62
/**
63
 * Display Upgrade Notices
64
 *
65
 * @since 1.0
66
 * @return void
67
 */
68
function give_show_upgrade_notices() {
69
	// Don't show notices on the upgrades page.
70
	if ( isset( $_GET['page'] ) && $_GET['page'] == 'give-upgrades' ) {
71
		return;
72
	}
73
74
	$give_version = get_option( 'give_version' );
75
76
	if ( ! $give_version ) {
77
		// 1.0 is the first version to use this option so we must add it.
78
		$give_version = '1.0';
79
	}
80
81
	$give_version = preg_replace( '/[^0-9.].*/', '', $give_version );
82
83
	/*
84
	 *  NOTICE:
85
	 *
86
	 *  When adding new upgrade notices, please be sure to put the action into the upgrades array during install:
87
	 *  /includes/install.php @ Appox Line 156
88
	 *
89
	 */
90
91
	// v1.3.2 Upgrades
92
	if ( version_compare( $give_version, '1.3.2', '<' ) || ! give_has_upgrade_completed( 'upgrade_give_payment_customer_id' ) ) {
93
		printf(
94
			/* translators: %s: upgrade URL */
95
			'<div class="updated"><p>' . __( 'Give needs to upgrade the donor database, click <a href="%s">here</a> to start the upgrade.', 'give' ) . '</p></div>',
96
			esc_url( admin_url( 'index.php?page=give-upgrades&give-upgrade=upgrade_give_payment_customer_id' ) )
97
		);
98
	}
99
100
	// v1.3.4 Upgrades //ensure the user has gone through 1.3.4.
101
	if ( version_compare( $give_version, '1.3.4', '<' ) || ( ! give_has_upgrade_completed( 'upgrade_give_offline_status' ) && give_has_upgrade_completed( 'upgrade_give_payment_customer_id' ) ) ) {
102
		printf(
103
			/* translators: %s: upgrade URL */
104
			'<div class="updated"><p>' . __( 'Give needs to upgrade the donations database, click <a href="%s">here</a> to start the upgrade.', 'give' ) . '</p></div>',
105
			esc_url( admin_url( 'index.php?page=give-upgrades&give-upgrade=upgrade_give_offline_status' ) )
106
		);
107
	}
108
109
	// Check if we have a stalled upgrade.
110
	$resume_upgrade = give_maybe_resume_upgrade();
111
	if ( ! empty( $resume_upgrade ) ) {
112
		$resume_url = add_query_arg( $resume_upgrade, admin_url( 'index.php' ) );
113
		echo Give_Notices::notice_html(
114
			sprintf(
115
				__( 'Give needs to complete a database upgrade that was previously started, click <a href="%s">here</a> to resume the upgrade.', 'give' ),
116
				esc_url( $resume_url )
117 1
			)
118
		);
119
120
		return;
121 1
	}
122
123 1
	// v1.8 form metadata upgrades.
124
	if ( version_compare( $give_version, '1.8', '<' ) || ! give_has_upgrade_completed( 'v18_upgrades_form_metadata' ) ) {
125
		echo Give_Notices::notice_html(
126
			sprintf(
127
				esc_html__( 'Give needs to upgrade the form database, click %1$shere%2$s to start the upgrade.', 'give' ),
128
				'<a class="give-upgrade-link" href="' . esc_url( admin_url( 'index.php?page=give-upgrades&give-upgrade=give_v18_upgrades_form_metadata' ) ) . '">',
129
				'</a>'
130
			)
131
		);
132
	}
133
134
	// End 'Stepped' upgrade process notices.
135
	?>
136
	<script>
137
		jQuery(document).ready(function($){
138 1
			var $upgrade_links = $('.give-upgrade-link');
139
			if( $upgrade_links.length ) {
140
				$upgrade_links.on( 'click', function(e){
141
					e.preventDefault();
142 1
143 1
					if( ! window.confirm( '<?php _e( 'Please make sure to create a database backup before initiating the upgrade.', 'give' ); ?>' ) ) {
144
						return;
145
					}
146 1
147
					// Redirect to upgrdae link.
148 1
					window.location.assign( $(this).attr('href') );
149
				});
150
			}
151
		});
152
	</script>
153
	<?php
154
}
155
156
add_action( 'admin_notices', 'give_show_upgrade_notices' );
157
158
/**
159 1
 * Triggers all upgrade functions
160
 *
161 1
 * This function is usually triggered via AJAX
162
 *
163
 * @since 1.0
164
 * @return void
165 1
 */
166
function give_trigger_upgrades() {
167
168
	if ( ! current_user_can( 'manage_give_settings' ) ) {
169
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
170
			'response' => 403,
171
		) );
172
	}
173
174
	$give_version = get_option( 'give_version' );
175
176
	if ( ! $give_version ) {
177
		// 1.0 is the first version to use this option so we must add it.
178
		$give_version = '1.0';
179
		add_option( 'give_version', $give_version );
180
	}
181
182
	update_option( 'give_version', GIVE_VERSION );
183
	delete_option( 'give_doing_upgrade' );
184
185
	if ( DOING_AJAX ) {
186
		die( 'complete' );
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_trigger_upgrades() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
187
	} // End if().
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
188
}
189
190
add_action( 'wp_ajax_give_trigger_upgrades', 'give_trigger_upgrades' );
191
192
/**
193
 * Check if the upgrade routine has been run for a specific action
194
 *
195
 * @since  1.0
196
 *
197
 * @param  string $upgrade_action The upgrade action to check completion for
198
 *
199
 * @return bool                   If the action has been added to the completed actions array
200
 */
201
function give_has_upgrade_completed( $upgrade_action = '' ) {
202
203
	if ( empty( $upgrade_action ) ) {
204
		return false;
205
	}
206
207
	$completed_upgrades = give_get_completed_upgrades();
208
209
	return in_array( $upgrade_action, $completed_upgrades );
210
211
}
212
213
/**
214
 * For use when doing 'stepped' upgrade routines, to see if we need to start somewhere in the middle
215
 *
216
 * @since 1.8
217
 *
218
 * @return mixed   When nothing to resume returns false, otherwise starts the upgrade where it left off
219
 */
220
function give_maybe_resume_upgrade() {
221
	$doing_upgrade = get_option( 'give_doing_upgrade', false );
222
	if ( empty( $doing_upgrade ) ) {
223
		return false;
224
	}
225
226
	return $doing_upgrade;
227
}
228
229
/**
230
 * Adds an upgrade action to the completed upgrades array
231
 *
232
 * @since  1.0
233
 *
234
 * @param  string $upgrade_action The action to add to the completed upgrades array
235
 *
236
 * @return bool                   If the function was successfully added
237
 */
238
function give_set_upgrade_complete( $upgrade_action = '' ) {
239
240
	if ( empty( $upgrade_action ) ) {
241
		return false;
242
	}
243
244
	$completed_upgrades   = give_get_completed_upgrades();
245
	$completed_upgrades[] = $upgrade_action;
246
247
	// Remove any blanks, and only show uniques.
248
	$completed_upgrades = array_unique( array_values( $completed_upgrades ) );
249
250
	return update_option( 'give_completed_upgrades', $completed_upgrades );
251
}
252
253
/**
254
 * Get's the array of completed upgrade actions
255
 *
256
 * @since  1.0
257
 * @return array The array of completed upgrades
258
 */
259
function give_get_completed_upgrades() {
260
261
	$completed_upgrades = get_option( 'give_completed_upgrades' );
262
263
	if ( false === $completed_upgrades ) {
264
		$completed_upgrades = array();
265
	}
266
267
	return $completed_upgrades;
268
269
}
270
271
/**
272
 * Upgrades the
273
 *
274
 * Standardizes the discrepancies between two metakeys `_give_payment_customer_id` and `_give_payment_donor_id`
275
 *
276
 * @since      1.3.2
277
 */
278
function give_v132_upgrade_give_payment_customer_id() {
279
	global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
280
	if ( ! current_user_can( 'manage_give_settings' ) ) {
281
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
282
			'response' => 403,
283
		) );
284
	}
285
286
	ignore_user_abort( true );
287
288
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
289
		@set_time_limit( 0 );
290
	}
291
292
	// UPDATE DB METAKEYS.
293
	$sql   = "UPDATE $wpdb->postmeta SET meta_key = '_give_payment_customer_id' WHERE meta_key = '_give_payment_donor_id'";
294
	$query = $wpdb->query( $sql );
295
296
	update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
297
	give_set_upgrade_complete( 'upgrade_give_payment_customer_id' );
298
	delete_option( 'give_doing_upgrade' );
299
	wp_redirect( admin_url() );
300
	exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_v132_upgrade_give_payment_customer_id() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
301
302
}
303
304
add_action( 'give_upgrade_give_payment_customer_id', 'give_v132_upgrade_give_payment_customer_id' );
305
306
/**
307
 * Upgrades the Offline Status
308
 *
309
 * Reverses the issue where offline donations in "pending" status where inappropriately marked as abandoned
310
 *
311
 * @since      1.3.4
312
 */
313
function give_v134_upgrade_give_offline_status() {
314
315
	global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
316
317
	if ( ! current_user_can( 'manage_give_settings' ) ) {
318
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
319
			'response' => 403,
320
		) );
321
	}
322
323
	ignore_user_abort( true );
324
325
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
326
		@set_time_limit( 0 );
327
	}
328
329
	// Get abandoned offline payments.
330
	$select = "SELECT ID FROM $wpdb->posts p ";
331
	$join   = "LEFT JOIN $wpdb->postmeta m ON p.ID = m.post_id ";
332
	$where  = "WHERE p.post_type = 'give_payment' ";
333
	$where .= "AND ( p.post_status = 'abandoned' )";
334
	$where .= "AND ( m.meta_key = '_give_payment_gateway' AND m.meta_value = 'offline' )";
335
336
	$sql            = $select . $join . $where;
337
	$found_payments = $wpdb->get_col( $sql );
338
339
	foreach ( $found_payments as $payment ) {
340
341
		// Only change ones marked abandoned since our release last week because the admin may have marked some abandoned themselves.
342
		$modified_time = get_post_modified_time( 'U', false, $payment );
343
344
		// 1450124863 =  12/10/2015 20:42:25.
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
345
		if ( $modified_time >= 1450124863 ) {
346
347
			give_update_payment_status( $payment, 'pending' );
348
349
		}
350
	}
351
352
	update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
353
	give_set_upgrade_complete( 'upgrade_give_offline_status' );
354
	delete_option( 'give_doing_upgrade' );
355
	wp_redirect( admin_url() );
356
	exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_v134_upgrade_give_offline_status() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
357
358
}
359
360
add_action( 'give_upgrade_give_offline_status', 'give_v134_upgrade_give_offline_status' );
361
362
/**
363
 * Cleanup User Roles
364
 *
365
 * This upgrade routine removes unused roles and roles with typos
366
 *
367
 * @since      1.5.2
368
 */
369
function give_v152_cleanup_users() {
370
371
	$give_version = get_option( 'give_version' );
372
373
	if ( ! $give_version ) {
374
		// 1.0 is the first version to use this option so we must add it.
375
		$give_version = '1.0';
376
	}
377
378
	$give_version = preg_replace( '/[^0-9.].*/', '', $give_version );
379
380
	// v1.5.2 Upgrades
381
	if ( version_compare( $give_version, '1.5.2', '<' ) || ! give_has_upgrade_completed( 'upgrade_give_user_caps_cleanup' ) ) {
382
383
		// Delete all caps with "ss".
384
		// Also delete all unused "campaign" roles.
385
		$delete_caps = array(
386
			'delete_give_formss',
387
			'delete_others_give_formss',
388
			'delete_private_give_formss',
389
			'delete_published_give_formss',
390
			'read_private_forms',
391
			'edit_give_formss',
392
			'edit_others_give_formss',
393
			'edit_private_give_formss',
394
			'edit_published_give_formss',
395
			'publish_give_formss',
396
			'read_private_give_formss',
397
			'assign_give_campaigns_terms',
398
			'delete_give_campaigns',
399
			'delete_give_campaigns_terms',
400
			'delete_give_campaignss',
401
			'delete_others_give_campaignss',
402
			'delete_private_give_campaignss',
403
			'delete_published_give_campaignss',
404
			'edit_give_campaigns',
405
			'edit_give_campaigns_terms',
406
			'edit_give_campaignss',
407
			'edit_others_give_campaignss',
408
			'edit_private_give_campaignss',
409
			'edit_published_give_campaignss',
410
			'manage_give_campaigns_terms',
411
			'publish_give_campaignss',
412
			'read_give_campaigns',
413
			'read_private_give_campaignss',
414
			'view_give_campaigns_stats',
415
			'delete_give_paymentss',
416
			'delete_others_give_paymentss',
417
			'delete_private_give_paymentss',
418
			'delete_published_give_paymentss',
419
			'edit_give_paymentss',
420
			'edit_others_give_paymentss',
421
			'edit_private_give_paymentss',
422
			'edit_published_give_paymentss',
423
			'publish_give_paymentss',
424
			'read_private_give_paymentss',
425
		);
426
427
		global $wp_roles;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
428
		foreach ( $delete_caps as $cap ) {
429
			foreach ( array_keys( $wp_roles->roles ) as $role ) {
430
				$wp_roles->remove_cap( $role, $cap );
431
			}
432
		}
433
434
		// Create Give plugin roles.
435
		$roles = new Give_Roles();
436
		$roles->add_roles();
437
		$roles->add_caps();
438
439
		// The Update Ran.
440
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
441
		give_set_upgrade_complete( 'upgrade_give_user_caps_cleanup' );
442
		delete_option( 'give_doing_upgrade' );
443
444
	}// End if().
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
445
446
}
447
448
add_action( 'admin_init', 'give_v152_cleanup_users' );
449
450
/**
451
 * 1.6 Upgrade routine to create the customer meta table.
452
 *
453
 * @since  1.6
454
 * @return void
455
 */
456
function give_v16_upgrades() {
457
	@Give()->customers->create_table();
458
	@Give()->customer_meta->create_table();
459
}
460
461
/**
462
 * 1.7 Upgrades.
463
 *
464
 * a. Update license api data for plugin addons.
465
 * b. Cleanup user roles.
466
 *
467
 * @since  1.7
468
 * @return void
469
 */
470
function give_v17_upgrades() {
471
	// Upgrade license data.
472
	give_v17_upgrade_addon_license_data();
473
	give_v17_cleanup_roles();
474
}
475
476
/**
477
 * Upgrade license data
478
 *
479
 * @since 1.7
480
 */
481
function give_v17_upgrade_addon_license_data() {
482
	$give_options = give_get_settings();
483
484
	$api_url = 'https://givewp.com/give-sl-api/';
485
486
	// Get addons license key.
487
	$addons = array();
488
	foreach ( $give_options as $key => $value ) {
489
		if ( false !== strpos( $key, '_license_key' ) ) {
490
			$addons[ $key ] = $value;
491
		}
492
	}
493
494
	// Bailout: We do not have any addon license data to upgrade.
495
	if ( empty( $addons ) ) {
496
		return false;
497
	}
498
499
	foreach ( $addons as $key => $addon_license ) {
500
501
		// Get addon shortname.
502
		$shortname = str_replace( '_license_key', '', $key );
503
504
		// Addon license option name.
505
		$addon_license_option_name = $shortname . '_license_active';
506
507
		// bailout if license is empty.
508
		if ( empty( $addon_license ) ) {
509
			delete_option( $addon_license_option_name );
510
			continue;
511
		}
512
513
		// Get addon name.
514
		$addon_name       = array();
515
		$addon_name_parts = explode( '_', str_replace( 'give_', '', $shortname ) );
516
		foreach ( $addon_name_parts as $name_part ) {
517
518
			// Fix addon name
519
			switch ( $name_part ) {
520
				case 'authorizenet' :
521
					$name_part = 'authorize.net';
522
					break;
523
			}
524
525
			$addon_name[] = ucfirst( $name_part );
526
		}
527
528
		$addon_name = implode( ' ', $addon_name );
529
530
		// Data to send to the API
531
		$api_params = array(
532
			'edd_action' => 'activate_license', // never change from "edd_" to "give_"!
533
			'license'    => $addon_license,
534
			'item_name'  => urlencode( $addon_name ),
535
			'url'        => home_url(),
536
		);
537
538
		// Call the API.
539
		$response = wp_remote_post(
540
			$api_url,
541
			array(
542
				'timeout'   => 15,
543
				'sslverify' => false,
544
				'body'      => $api_params,
545
			)
546
		);
547
548
		// Make sure there are no errors.
549
		if ( is_wp_error( $response ) ) {
550
			delete_option( $addon_license_option_name );
551
			continue;
552
		}
553
554
		// Tell WordPress to look for updates.
555
		set_site_transient( 'update_plugins', null );
556
557
		// Decode license data.
558
		$license_data = json_decode( wp_remote_retrieve_body( $response ) );
559
		update_option( $addon_license_option_name, $license_data );
560
	}// End foreach().
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
561
}
562
563
564
/**
565
 * Cleanup User Roles.
566
 *
567
 * This upgrade routine removes unused roles and roles with typos.
568
 *
569
 * @since      1.7
570
 */
571
function give_v17_cleanup_roles() {
572
573
	// Delete all caps with "_give_forms_" and "_give_payments_"
574
	// These roles have no usage; the proper is singular.
575
	$delete_caps = array(
576
		'view_give_forms_stats',
577
		'delete_give_forms_terms',
578
		'assign_give_forms_terms',
579
		'edit_give_forms_terms',
580
		'manage_give_forms_terms',
581
		'view_give_payments_stats',
582
		'manage_give_payments_terms',
583
		'edit_give_payments_terms',
584
		'assign_give_payments_terms',
585
		'delete_give_payments_terms',
586
	);
587
588
	global $wp_roles;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
589
	foreach ( $delete_caps as $cap ) {
590
		foreach ( array_keys( $wp_roles->roles ) as $role ) {
591
			$wp_roles->remove_cap( $role, $cap );
592
		}
593
	}
594
595
	// Set roles again.
596
	$roles = new Give_Roles();
597
	$roles->add_roles();
598
	$roles->add_caps();
599
600
}
601
602
/**
603
 * 1.8 Upgrades.
604
 *
605
 * a. Upgrade checkbox settings to radio button settings.
606
 * a. Update form meta for new metabox settings.
607
 *
608
 * @since  1.8
609
 * @return void
610
 */
611
function give_v18_upgrades() {
612
	// Upgrade checkbox settings to radio button settings.
613
	give_v18_upgrades_core_setting();
614
}
615
616
/**
617
 * Upgrade core settings.
618
 *
619
 * @since  1.8
620
 * @return void
621
 */
622
function give_v18_upgrades_core_setting() {
623
	// Core settings which changes from checkbox to radio.
624
	$core_setting_names = array_merge(
625
		array_keys( give_v18_renamed_core_settings() ),
626
		array(
627
			'uninstall_on_delete',
628
			'scripts_footer',
629
			'test_mode',
630
			'email_access',
631
			'terms',
632
			'give_offline_donation_enable_billing_fields',
633
		)
634
	);
635
636
	// Bailout: If not any setting define.
637
	if ( $give_settings = get_option( 'give_settings' ) ) {
638
639
		$setting_changed = false;
640
641
		// Loop: check each setting field.
642
		foreach ( $core_setting_names as $setting_name ) {
643
			// New setting name.
644
			$new_setting_name = preg_replace( '/^(enable_|disable_)/', '', $setting_name );
645
646
			// Continue: If setting already set.
647
			if (
648
				array_key_exists( $new_setting_name, $give_settings )
649
				&& in_array( $give_settings[ $new_setting_name ], array( 'enabled', 'disabled' ) )
650
			) {
651
				continue;
652
			}
653
654
			// Set checkbox value to radio value.
655
			$give_settings[ $setting_name ] = ( ! empty( $give_settings[ $setting_name ] ) && 'on' === $give_settings[ $setting_name ] ? 'enabled' : 'disabled' );
656
657
			// @see https://github.com/WordImpress/Give/issues/1063
658
			if ( false !== strpos( $setting_name, 'disable_' ) ) {
659
660
				$give_settings[ $new_setting_name ] = ( give_is_setting_enabled( $give_settings[ $setting_name ] ) ? 'disabled' : 'enabled' );
661
			} elseif ( false !== strpos( $setting_name, 'enable_' ) ) {
662
663
				$give_settings[ $new_setting_name ] = ( give_is_setting_enabled( $give_settings[ $setting_name ] ) ? 'enabled' : 'disabled' );
664
			}
665
666
			// Tell bot to update core setting to db.
667
			if ( ! $setting_changed ) {
668
				$setting_changed = true;
669
			}
670
		}
671
672
		// Update setting only if they changed.
673
		if ( $setting_changed ) {
674
			update_option( 'give_settings', $give_settings );
675
		}
676
	}// End if().
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
677
678
	give_set_upgrade_complete( 'v18_upgrades_core_setting' );
679
}
680
681
/**
682
 * Upgrade form metadata for new metabox settings.
683
 *
684
 * @since  1.8
685
 * @return void
686
 */
687
function give_v18_upgrades_form_metadata() {
688
	if ( ! current_user_can( 'manage_give_settings' ) ) {
689
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
690
			'response' => 403,
691
		) );
692
	}
693
694
	ignore_user_abort( true );
695
696
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
697
		@set_time_limit( 0 );
698
	}
699
700
	$step = isset( $_GET['step'] ) ? absint( $_GET['step'] ) : 1;
701
702
	// form query
703
	$forms = new WP_Query( array(
704
			'paged'          => $step,
705
			'status'         => 'any',
706
			'order'          => 'ASC',
707
			'post_type'      => 'give_forms',
708
			'posts_per_page' => 20,
709
		)
710
	);
711
712
	if ( $forms->have_posts() ) {
713
		while ( $forms->have_posts() ) {
714
			$forms->the_post();
715
716
			// Form content.
717
			// Note in version 1.8 display content setting split into display content and content placement setting.
718
			// You can delete _give_content_option in future
719
			$show_content = get_post_meta( get_the_ID(), '_give_content_option', true );
720
			if ( $show_content && ! get_post_meta( get_the_ID(), '_give_display_content', true ) ) {
721
				$field_value = ( 'none' !== $show_content ? 'enabled' : 'disabled' );
722
				update_post_meta( get_the_ID(), '_give_display_content', $field_value );
723
724
				$field_value = ( 'none' !== $show_content ? $show_content : 'give_pre_form' );
725
				update_post_meta( get_the_ID(), '_give_content_placement', $field_value );
726
			}
727
728
			// "Disable" Guest Donation. Checkbox
729
			// See: https://github.com/WordImpress/Give/issues/1470
730
			$guest_donation = get_post_meta( get_the_ID(), '_give_logged_in_only', true );
731
			$guest_donation_newval = ( in_array( $guest_donation, array( 'yes', 'on' ) ) ? 'disabled' : 'enabled' );
732
			update_post_meta( get_the_ID(), '_give_logged_in_only', $guest_donation_newval );
733
734
			// Offline Donations
735
			// See: https://github.com/WordImpress/Give/issues/1579
736
			$offline_donation = get_post_meta( get_the_ID(), '_give_customize_offline_donations', true );
737
			if ( 'no' === $offline_donation ) {
738
				$offline_donation_newval = 'global';
739
			} elseif ( 'yes' === $offline_donation ) {
740
				$offline_donation_newval = 'enabled';
741
			} else {
742
				$offline_donation_newval = 'disabled';
743
			}
744
			update_post_meta( get_the_ID(), '_give_customize_offline_donations', $offline_donation_newval );
745
746
			// Convert yes/no setting field to enabled/disabled.
747
			$form_radio_settings = array(
748
				// Custom Amount.
749
				'_give_custom_amount',
750
751
				// Donation Gaol.
752
				'_give_goal_option',
753
754
				// Close Form.
755
				'_give_close_form_when_goal_achieved',
756
757
				// Term & conditions.
758
				'_give_terms_option',
759
760
				// Billing fields.
761
				'_give_offline_donation_enable_billing_fields_single',
762
			);
763
764
			foreach ( $form_radio_settings as $meta_key ) {
765
				// Get value.
766
				$field_value = get_post_meta( get_the_ID(), $meta_key, true );
767
768
				// Convert meta value only if it is in yes/no/none.
769
				if ( in_array( $field_value, array( 'yes', 'on', 'no', 'none' ) ) ) {
770
771
					$field_value = ( in_array( $field_value, array( 'yes', 'on' ) ) ? 'enabled' : 'disabled' );
772
					update_post_meta( get_the_ID(), $meta_key, $field_value );
773
				}
774
			}
775
		}// End while().
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
776
777
		wp_reset_postdata();
778
779
		// Forms found so upgrade them
780
		$step ++;
781
		$redirect = add_query_arg( array(
782
			'page'         => 'give-upgrades',
783
			'give-upgrade' => 'give_v18_upgrades_form_metadata',
784
			'step'         => $step,
785
		), admin_url( 'index.php' ) );
786
		wp_redirect( $redirect );
787
		exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_v18_upgrades_form_metadata() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
788
789
	} else {
790
		// No more forms found, finish up.
791
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
792
		delete_option( 'give_doing_upgrade' );
793
		give_set_upgrade_complete( 'v18_upgrades_form_metadata' );
794
795
		wp_redirect( admin_url() );
796
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_v18_upgrades_form_metadata() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
797
	}
798
}
799
800
add_action( 'give_give_v18_upgrades_form_metadata', 'give_v18_upgrades_form_metadata' );
801
802
/**
803
 * Get list of core setting renamed in version 1.8.
804
 *
805
 * @since  1.8
806
 * @return array
807
 */
808
function give_v18_renamed_core_settings() {
809
	return array(
810
		'disable_paypal_verification' => 'paypal_verification',
811
		'disable_css'                 => 'css',
812
		'disable_welcome'             => 'welcome',
813
		'disable_forms_singular'      => 'forms_singular',
814
		'disable_forms_archives'      => 'forms_archives',
815
		'disable_forms_excerpt'       => 'forms_excerpt',
816
		'disable_form_featured_img'   => 'form_featured_img',
817
		'disable_form_sidebar'        => 'form_sidebar',
818
		'disable_admin_notices'       => 'admin_notices',
819
		'disable_the_content_filter'  => 'the_content_filter',
820
		'enable_floatlabels'          => 'floatlabels',
821
		'enable_categories'           => 'categories',
822
		'enable_tags'                 => 'tags',
823
	);
824
}
825
826
827
/**
828
 * Upgrade core settings.
829
 *
830
 * @since  1.8.7
831
 * @return void
832
 */
833
function give_v187_upgrades(){
834
	global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
835
836
	/**
837
	 * Upgrade 1: Remove stat and cache transients.
838
	 */
839
	$cached_options = $wpdb->get_col(
840
		$wpdb->prepare(
841
			"SELECT * FROM {$wpdb->options} where (option_name LIKE '%%%s%%' OR option_name LIKE '%%%s%%')",
842
			array(
843
				'_transient_give_stats_',
844
				'give_cache',
845
				'_transient_give_add_ons_feed',
846
				'_transient__give_ajax_works'.
847
				'_transient_give_total_api_keys',
848
				'_transient_give_i18n_give_promo_hide',
849
				'_transient_give_contributors',
850
				'_transient_give_estimated_monthly_stats',
851
				'_transient_give_earnings_total',
852
				'_transient_give_i18n_give_',
853
				'_transient__give_installed',
854
				'_transient__give_activation_redirect',
855
				'_transient__give_hide_license_notices_shortly_',
856
				'give_income_total'
857
			)
858
		),
859
		1
860
	);
861
862
	// User related transients.
863
	$user_apikey_options = $wpdb->get_results(
864
		$wpdb->prepare(
865
			"SELECT user_id, meta_key
866
			FROM $wpdb->usermeta
867
			WHERE meta_value=%s",
868
			'give_user_public_key'
869
		),
870
		ARRAY_A
871
	);
872
873
	if( ! empty( $user_apikey_options ) ) {
874
		foreach ( $user_apikey_options as $user ) {
875
			$cached_options[] = '_transient_' . md5( 'give_api_user_' . $user['meta_key'] );
876
			$cached_options[] = '_transient_' . md5( 'give_api_user_public_key' . $user['user_id'] );
877
			$cached_options[] = '_transient_' . md5( 'give_api_user_secret_key' . $user['user_id'] );
878
		}
879
	}
880
881
	if ( ! empty( $cached_options ) ) {
882
		foreach ( $cached_options as $option ) {
883
			switch ( true ) {
884
				case ( false !== strpos( $option, 'transient' ) ):
885
					$option = str_replace( '_transient_', '', $option );
886
					delete_transient( $option );
887
					break;
888
889
				default:
890
					delete_option( $option );
891
			}
892
		}
893
	}
894
}
895