Completed
Push — issue/1723 ( c371a2 )
by Ravinder
502:26 queued 485:02
created

upgrade-functions.php ➔ give_v189_upgrades_levels_post_meta_callback()   C

Complexity

Conditions 13
Paths 56

Size

Total Lines 97

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
nc 56
nop 0
dl 0
loc 97
rs 5.3587
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
		case version_compare( $give_version, '1.8.8', '<' ) :
54
			give_v188_upgrades();
55
			$did_upgrade = true;
56
57
		case version_compare( $give_version, '1.8.9', '<' ) :
58
			give_v189_upgrades();
59
			$did_upgrade = true;
60
61
	}
62
63
	if ( $did_upgrade ) {
64
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
65
	}
66
}
67
68
add_action( 'admin_init', 'give_do_automatic_upgrades' );
69
add_action( 'give_upgrades', 'give_do_automatic_upgrades' );
70
71
/**
72
 * Display Upgrade Notices
73
 *
74
 * @since 1.0
75
 * @return void
76
 */
77
function give_show_upgrade_notices() {
78
	// Don't show notices on the upgrades page.
79
	if ( isset( $_GET['page'] ) && $_GET['page'] == 'give-upgrades' ) {
80
		return;
81
	}
82
83
	$give_version = get_option( 'give_version' );
84
85
	if ( ! $give_version ) {
86
		// 1.0 is the first version to use this option so we must add it.
87
		$give_version = '1.0';
88
	}
89
90
	$give_version = preg_replace( '/[^0-9.].*/', '', $give_version );
91
92
	/*
93
	 *  NOTICE:
94
	 *
95
	 *  When adding new upgrade notices, please be sure to put the action into the upgrades array during install:
96
	 *  /includes/install.php @ Appox Line 156
97
	 *
98
	 */
99
100
	// Resume updates.
101
	// Check if we have a stalled upgrade.
102
	$resume_upgrade = give_maybe_resume_upgrade();
103
	if ( ! empty( $resume_upgrade ) ) {
104
		$resume_url = add_query_arg( give_maybe_resume_upgrade(), admin_url( 'index.php' ) );
105
106
		Give()->notices->register_notice( array(
107
			'id'          => 'give-resume-updates',
108
			'type'        => 'warning',
109
			'description' => sprintf(
110
				__( 'Give needs to complete a database upgrade that was previously started, click <a href="%s">here</a> to resume the upgrade.', 'give' ),
111
				esc_url( $resume_url )
112
			),
113
		) );
114
115
		return;
116
	}
117
118
	// v1.3.2 Upgrades
119
	Give()->notices->register_notice( array(
120
		'id'          => 'give-version-1-3-2-updates',
121
		'type'        => 'warning',
122
		'description' => sprintf(
123
			'<p>' . __( 'Give needs to upgrade the donor database, click <a href="%s">here</a> to start the upgrade.', 'give' ) . '</p>',
124
			esc_url( admin_url( 'index.php?page=give-upgrades&give-upgrade=upgrade_give_payment_customer_id' ) )
125
		),
126
		'show'        => ( version_compare( $give_version, '1.3.2', '<' ) || ! give_has_upgrade_completed( 'upgrade_give_payment_customer_id' ) ),
127
	) );
128
129
	// v1.3.4 Upgrades //ensure the user has gone through 1.3.4.
130
	Give()->notices->register_notice( array(
131
		'id'          => 'give-version-1-3-4-updates',
132
		'type'        => 'warning',
133
		'description' => sprintf(
134
			'<p>' . __( 'Give needs to upgrade the donations database, click <a href="%s">here</a> to start the upgrade.', 'give' ) . '</p>',
135
			esc_url( admin_url( 'index.php?page=give-upgrades&give-upgrade=upgrade_give_offline_status' ) )
136
		),
137
		'show'        => ( version_compare( $give_version, '1.3.4', '<' ) || ( ! give_has_upgrade_completed( 'upgrade_give_offline_status' ) && give_has_upgrade_completed( 'upgrade_give_payment_customer_id' ) ) ),
138
	) );
139
140
	// v1.8 form metadata upgrades.
141
	Give()->notices->register_notice( array(
142
		'id'          => 'give-version-1-8-updates',
143
		'type'        => 'warning',
144
		'description' => sprintf(
145
			esc_html__( 'Give needs to upgrade the form database, click <a class="give-upgrade-link" href="%s">here</a> to start the upgrade.', 'give' ),
146
			esc_url( admin_url( 'index.php?page=give-upgrades&give-upgrade=give_v18_upgrades_form_metadata' ) )
147
		),
148
		'show'        => ( version_compare( $give_version, '1.8', '<' ) || ! give_has_upgrade_completed( 'v18_upgrades_form_metadata' ) )
149
	) );
150
151
	// v1.8.9 Upgrades
152
	Give()->notices->register_notice( array(
153
		'id'          => 'give-version-1-8-9-updates',
154
		'type'        => 'warning',
155
		'description' => sprintf(
156
			__( 'Give needs to upgrade the donation forms meta-fields in database, click <a href="%s">here</a> to start the upgrade.', 'give' ),
157
			esc_url( admin_url( 'index.php?page=give-upgrades&give-upgrade=v189_upgrades_levels_post_meta' ) )
158
		),
159
		'show'        => ( version_compare( $give_version, '1.8.9', '<' ) || ( ! give_has_upgrade_completed( 'v189_upgrades_levels_post_meta' ) ) ),
160
	) );
161
162
	// End 'Stepped' upgrade process notices.
163
	?>
164
	<script>
165
		jQuery(document).ready(function ($) {
166
			var $upgrade_links = $('.give-upgrade-link');
167
			if ($upgrade_links.length) {
168
				$upgrade_links.on('click', function (e) {
169
					e.preventDefault();
170
171
					if (!window.confirm('<?php _e( 'Please make sure to create a database backup before initiating the upgrade.', 'give' ); ?>')) {
172
						return;
173
					}
174
175
					// Redirect to upgrdae link.
176
					window.location.assign($(this).attr('href'));
177
				});
178
			}
179
		});
180
	</script>
181
	<?php
182
}
183
184
add_action( 'admin_notices', 'give_show_upgrade_notices' );
185
186
/**
187
 * Triggers all upgrade functions
188
 *
189
 * This function is usually triggered via AJAX
190
 *
191
 * @since 1.0
192
 * @return void
193
 */
194
function give_trigger_upgrades() {
195
196
	if ( ! current_user_can( 'manage_give_settings' ) ) {
197
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
198
			'response' => 403,
199
		) );
200
	}
201
202
	$give_version = get_option( 'give_version' );
203
204
	if ( ! $give_version ) {
205
		// 1.0 is the first version to use this option so we must add it.
206
		$give_version = '1.0';
207
		add_option( 'give_version', $give_version );
208
	}
209
210
	update_option( 'give_version', GIVE_VERSION );
211
	delete_option( 'give_doing_upgrade' );
212
213
	if ( DOING_AJAX ) {
214
		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...
215
	} // 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...
216
}
217
218
add_action( 'wp_ajax_give_trigger_upgrades', 'give_trigger_upgrades' );
219
220
/**
221
 * Check if the upgrade routine has been run for a specific action
222
 *
223
 * @since  1.0
224
 *
225
 * @param  string $upgrade_action The upgrade action to check completion for
226
 *
227
 * @return bool                   If the action has been added to the completed actions array
228
 */
229
function give_has_upgrade_completed( $upgrade_action = '' ) {
230
231
	if ( empty( $upgrade_action ) ) {
232
		return false;
233
	}
234
235
	$completed_upgrades = give_get_completed_upgrades();
236
237
	return in_array( $upgrade_action, $completed_upgrades );
238
239
}
240
241
/**
242
 * For use when doing 'stepped' upgrade routines, to see if we need to start somewhere in the middle
243
 *
244
 * @since 1.8
245
 *
246
 * @return mixed   When nothing to resume returns false, otherwise starts the upgrade where it left off
247
 */
248
function give_maybe_resume_upgrade() {
249
	$doing_upgrade = get_option( 'give_doing_upgrade', false );
250
	if ( empty( $doing_upgrade ) ) {
251
		return false;
252
	}
253
254
	return $doing_upgrade;
255
}
256
257
/**
258
 * Adds an upgrade action to the completed upgrades array
259
 *
260
 * @since  1.0
261
 *
262
 * @param  string $upgrade_action The action to add to the completed upgrades array
263
 *
264
 * @return bool                   If the function was successfully added
265
 */
266
function give_set_upgrade_complete( $upgrade_action = '' ) {
267
268
	if ( empty( $upgrade_action ) ) {
269
		return false;
270
	}
271
272
	$completed_upgrades   = give_get_completed_upgrades();
273
	$completed_upgrades[] = $upgrade_action;
274
275
	// Remove any blanks, and only show uniques.
276
	$completed_upgrades = array_unique( array_values( $completed_upgrades ) );
277
278
	return update_option( 'give_completed_upgrades', $completed_upgrades );
279
}
280
281
/**
282
 * Get's the array of completed upgrade actions
283
 *
284
 * @since  1.0
285
 * @return array The array of completed upgrades
286
 */
287
function give_get_completed_upgrades() {
288
289
	$completed_upgrades = get_option( 'give_completed_upgrades' );
290
291
	if ( false === $completed_upgrades ) {
292
		$completed_upgrades = array();
293
	}
294
295
	return $completed_upgrades;
296
297
}
298
299
/**
300
 * Upgrades the
301
 *
302
 * Standardizes the discrepancies between two metakeys `_give_payment_customer_id` and `_give_payment_donor_id`
303
 *
304
 * @since      1.3.2
305
 */
306
function give_v132_upgrade_give_payment_customer_id() {
307
	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...
308
	if ( ! current_user_can( 'manage_give_settings' ) ) {
309
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
310
			'response' => 403,
311
		) );
312
	}
313
314
	ignore_user_abort( true );
315
316
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
317
		@set_time_limit( 0 );
318
	}
319
320
	// UPDATE DB METAKEYS.
321
	$sql   = "UPDATE $wpdb->postmeta SET meta_key = '_give_payment_customer_id' WHERE meta_key = '_give_payment_donor_id'";
322
	$query = $wpdb->query( $sql );
323
324
	update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
325
	give_set_upgrade_complete( 'upgrade_give_payment_customer_id' );
326
	delete_option( 'give_doing_upgrade' );
327
	wp_redirect( admin_url() );
328
	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...
329
330
}
331
332
add_action( 'give_upgrade_give_payment_customer_id', 'give_v132_upgrade_give_payment_customer_id' );
333
334
/**
335
 * Upgrades the Offline Status
336
 *
337
 * Reverses the issue where offline donations in "pending" status where inappropriately marked as abandoned
338
 *
339
 * @since      1.3.4
340
 */
341
function give_v134_upgrade_give_offline_status() {
342
343
	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...
344
345
	if ( ! current_user_can( 'manage_give_settings' ) ) {
346
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
347
			'response' => 403,
348
		) );
349
	}
350
351
	ignore_user_abort( true );
352
353
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
354
		@set_time_limit( 0 );
355
	}
356
357
	// Get abandoned offline payments.
358
	$select = "SELECT ID FROM $wpdb->posts p ";
359
	$join   = "LEFT JOIN $wpdb->postmeta m ON p.ID = m.post_id ";
360
	$where  = "WHERE p.post_type = 'give_payment' ";
361
	$where  .= "AND ( p.post_status = 'abandoned' )";
362
	$where  .= "AND ( m.meta_key = '_give_payment_gateway' AND m.meta_value = 'offline' )";
363
364
	$sql            = $select . $join . $where;
365
	$found_payments = $wpdb->get_col( $sql );
366
367
	foreach ( $found_payments as $payment ) {
368
369
		// Only change ones marked abandoned since our release last week because the admin may have marked some abandoned themselves.
370
		$modified_time = get_post_modified_time( 'U', false, $payment );
371
372
		// 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...
373
		if ( $modified_time >= 1450124863 ) {
374
375
			give_update_payment_status( $payment, 'pending' );
376
377
		}
378
	}
379
380
	update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
381
	give_set_upgrade_complete( 'upgrade_give_offline_status' );
382
	delete_option( 'give_doing_upgrade' );
383
	wp_redirect( admin_url() );
384
	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...
385
386
}
387
388
add_action( 'give_upgrade_give_offline_status', 'give_v134_upgrade_give_offline_status' );
389
390
/**
391
 * Cleanup User Roles
392
 *
393
 * This upgrade routine removes unused roles and roles with typos
394
 *
395
 * @since      1.5.2
396
 */
397
function give_v152_cleanup_users() {
398
399
	$give_version = get_option( 'give_version' );
400
401
	if ( ! $give_version ) {
402
		// 1.0 is the first version to use this option so we must add it.
403
		$give_version = '1.0';
404
	}
405
406
	$give_version = preg_replace( '/[^0-9.].*/', '', $give_version );
407
408
	// v1.5.2 Upgrades
409
	if ( version_compare( $give_version, '1.5.2', '<' ) || ! give_has_upgrade_completed( 'upgrade_give_user_caps_cleanup' ) ) {
410
411
		// Delete all caps with "ss".
412
		// Also delete all unused "campaign" roles.
413
		$delete_caps = array(
414
			'delete_give_formss',
415
			'delete_others_give_formss',
416
			'delete_private_give_formss',
417
			'delete_published_give_formss',
418
			'read_private_forms',
419
			'edit_give_formss',
420
			'edit_others_give_formss',
421
			'edit_private_give_formss',
422
			'edit_published_give_formss',
423
			'publish_give_formss',
424
			'read_private_give_formss',
425
			'assign_give_campaigns_terms',
426
			'delete_give_campaigns',
427
			'delete_give_campaigns_terms',
428
			'delete_give_campaignss',
429
			'delete_others_give_campaignss',
430
			'delete_private_give_campaignss',
431
			'delete_published_give_campaignss',
432
			'edit_give_campaigns',
433
			'edit_give_campaigns_terms',
434
			'edit_give_campaignss',
435
			'edit_others_give_campaignss',
436
			'edit_private_give_campaignss',
437
			'edit_published_give_campaignss',
438
			'manage_give_campaigns_terms',
439
			'publish_give_campaignss',
440
			'read_give_campaigns',
441
			'read_private_give_campaignss',
442
			'view_give_campaigns_stats',
443
			'delete_give_paymentss',
444
			'delete_others_give_paymentss',
445
			'delete_private_give_paymentss',
446
			'delete_published_give_paymentss',
447
			'edit_give_paymentss',
448
			'edit_others_give_paymentss',
449
			'edit_private_give_paymentss',
450
			'edit_published_give_paymentss',
451
			'publish_give_paymentss',
452
			'read_private_give_paymentss',
453
		);
454
455
		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...
456
		foreach ( $delete_caps as $cap ) {
457
			foreach ( array_keys( $wp_roles->roles ) as $role ) {
458
				$wp_roles->remove_cap( $role, $cap );
459
			}
460
		}
461
462
		// Create Give plugin roles.
463
		$roles = new Give_Roles();
464
		$roles->add_roles();
465
		$roles->add_caps();
466
467
		// The Update Ran.
468
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
469
		give_set_upgrade_complete( 'upgrade_give_user_caps_cleanup' );
470
		delete_option( 'give_doing_upgrade' );
471
472
	}// 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...
473
474
}
475
476
add_action( 'admin_init', 'give_v152_cleanup_users' );
477
478
/**
479
 * 1.6 Upgrade routine to create the customer meta table.
480
 *
481
 * @since  1.6
482
 * @return void
483
 */
484
function give_v16_upgrades() {
485
	// Create the donor databases.
486
	$donors_db = new Give_DB_Donors();
487
	$donors_db->create_table();
488
	$donor_meta = new Give_DB_Donor_Meta();
489
	$donor_meta->create_table();
490
}
491
492
/**
493
 * 1.7 Upgrades.
494
 *
495
 * a. Update license api data for plugin addons.
496
 * b. Cleanup user roles.
497
 *
498
 * @since  1.7
499
 * @return void
500
 */
501
function give_v17_upgrades() {
502
	// Upgrade license data.
503
	give_v17_upgrade_addon_license_data();
504
	give_v17_cleanup_roles();
505
}
506
507
/**
508
 * Upgrade license data
509
 *
510
 * @since 1.7
511
 */
512
function give_v17_upgrade_addon_license_data() {
513
	$give_options = give_get_settings();
514
515
	$api_url = 'https://givewp.com/give-sl-api/';
516
517
	// Get addons license key.
518
	$addons = array();
519
	foreach ( $give_options as $key => $value ) {
520
		if ( false !== strpos( $key, '_license_key' ) ) {
521
			$addons[ $key ] = $value;
522
		}
523
	}
524
525
	// Bailout: We do not have any addon license data to upgrade.
526
	if ( empty( $addons ) ) {
527
		return false;
528
	}
529
530
	foreach ( $addons as $key => $addon_license ) {
531
532
		// Get addon shortname.
533
		$shortname = str_replace( '_license_key', '', $key );
534
535
		// Addon license option name.
536
		$addon_license_option_name = $shortname . '_license_active';
537
538
		// bailout if license is empty.
539
		if ( empty( $addon_license ) ) {
540
			delete_option( $addon_license_option_name );
541
			continue;
542
		}
543
544
		// Get addon name.
545
		$addon_name       = array();
546
		$addon_name_parts = explode( '_', str_replace( 'give_', '', $shortname ) );
547
		foreach ( $addon_name_parts as $name_part ) {
548
549
			// Fix addon name
550
			switch ( $name_part ) {
551
				case 'authorizenet' :
552
					$name_part = 'authorize.net';
553
					break;
554
			}
555
556
			$addon_name[] = ucfirst( $name_part );
557
		}
558
559
		$addon_name = implode( ' ', $addon_name );
560
561
		// Data to send to the API
562
		$api_params = array(
563
			'edd_action' => 'activate_license', // never change from "edd_" to "give_"!
564
			'license'    => $addon_license,
565
			'item_name'  => urlencode( $addon_name ),
566
			'url'        => home_url(),
567
		);
568
569
		// Call the API.
570
		$response = wp_remote_post(
571
			$api_url,
572
			array(
573
				'timeout'   => 15,
574
				'sslverify' => false,
575
				'body'      => $api_params,
576
			)
577
		);
578
579
		// Make sure there are no errors.
580
		if ( is_wp_error( $response ) ) {
581
			delete_option( $addon_license_option_name );
582
			continue;
583
		}
584
585
		// Tell WordPress to look for updates.
586
		set_site_transient( 'update_plugins', null );
587
588
		// Decode license data.
589
		$license_data = json_decode( wp_remote_retrieve_body( $response ) );
590
		update_option( $addon_license_option_name, $license_data );
591
	}// 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...
592
}
593
594
595
/**
596
 * Cleanup User Roles.
597
 *
598
 * This upgrade routine removes unused roles and roles with typos.
599
 *
600
 * @since      1.7
601
 */
602
function give_v17_cleanup_roles() {
603
604
	// Delete all caps with "_give_forms_" and "_give_payments_"
605
	// These roles have no usage; the proper is singular.
606
	$delete_caps = array(
607
		'view_give_forms_stats',
608
		'delete_give_forms_terms',
609
		'assign_give_forms_terms',
610
		'edit_give_forms_terms',
611
		'manage_give_forms_terms',
612
		'view_give_payments_stats',
613
		'manage_give_payments_terms',
614
		'edit_give_payments_terms',
615
		'assign_give_payments_terms',
616
		'delete_give_payments_terms',
617
	);
618
619
	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...
620
	foreach ( $delete_caps as $cap ) {
621
		foreach ( array_keys( $wp_roles->roles ) as $role ) {
622
			$wp_roles->remove_cap( $role, $cap );
623
		}
624
	}
625
626
	// Set roles again.
627
	$roles = new Give_Roles();
628
	$roles->add_roles();
629
	$roles->add_caps();
630
631
}
632
633
/**
634
 * 1.8 Upgrades.
635
 *
636
 * a. Upgrade checkbox settings to radio button settings.
637
 * a. Update form meta for new metabox settings.
638
 *
639
 * @since  1.8
640
 * @return void
641
 */
642
function give_v18_upgrades() {
643
	// Upgrade checkbox settings to radio button settings.
644
	give_v18_upgrades_core_setting();
645
}
646
647
/**
648
 * Upgrade core settings.
649
 *
650
 * @since  1.8
651
 * @return void
652
 */
653
function give_v18_upgrades_core_setting() {
654
	// Core settings which changes from checkbox to radio.
655
	$core_setting_names = array_merge(
656
		array_keys( give_v18_renamed_core_settings() ),
657
		array(
658
			'uninstall_on_delete',
659
			'scripts_footer',
660
			'test_mode',
661
			'email_access',
662
			'terms',
663
			'give_offline_donation_enable_billing_fields',
664
		)
665
	);
666
667
	// Bailout: If not any setting define.
668
	if ( $give_settings = get_option( 'give_settings' ) ) {
669
670
		$setting_changed = false;
671
672
		// Loop: check each setting field.
673
		foreach ( $core_setting_names as $setting_name ) {
674
			// New setting name.
675
			$new_setting_name = preg_replace( '/^(enable_|disable_)/', '', $setting_name );
676
677
			// Continue: If setting already set.
678
			if (
679
				array_key_exists( $new_setting_name, $give_settings )
680
				&& in_array( $give_settings[ $new_setting_name ], array( 'enabled', 'disabled' ) )
681
			) {
682
				continue;
683
			}
684
685
			// Set checkbox value to radio value.
686
			$give_settings[ $setting_name ] = ( ! empty( $give_settings[ $setting_name ] ) && 'on' === $give_settings[ $setting_name ] ? 'enabled' : 'disabled' );
687
688
			// @see https://github.com/WordImpress/Give/issues/1063
689
			if ( false !== strpos( $setting_name, 'disable_' ) ) {
690
691
				$give_settings[ $new_setting_name ] = ( give_is_setting_enabled( $give_settings[ $setting_name ] ) ? 'disabled' : 'enabled' );
692
			} elseif ( false !== strpos( $setting_name, 'enable_' ) ) {
693
694
				$give_settings[ $new_setting_name ] = ( give_is_setting_enabled( $give_settings[ $setting_name ] ) ? 'enabled' : 'disabled' );
695
			}
696
697
			// Tell bot to update core setting to db.
698
			if ( ! $setting_changed ) {
699
				$setting_changed = true;
700
			}
701
		}
702
703
		// Update setting only if they changed.
704
		if ( $setting_changed ) {
705
			update_option( 'give_settings', $give_settings );
706
		}
707
	}// 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...
708
709
	give_set_upgrade_complete( 'v18_upgrades_core_setting' );
710
}
711
712
/**
713
 * Upgrade form metadata for new metabox settings.
714
 *
715
 * @since  1.8
716
 * @return void
717
 */
718
function give_v18_upgrades_form_metadata() {
719
	if ( ! current_user_can( 'manage_give_settings' ) ) {
720
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
721
			'response' => 403,
722
		) );
723
	}
724
725
	ignore_user_abort( true );
726
727
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
728
		@set_time_limit( 0 );
729
	}
730
731
	$step = isset( $_GET['step'] ) ? absint( $_GET['step'] ) : 1;
732
733
	// form query
734
	$forms = new WP_Query( array(
735
			'paged'          => $step,
736
			'status'         => 'any',
737
			'order'          => 'ASC',
738
			'post_type'      => 'give_forms',
739
			'posts_per_page' => 20,
740
		)
741
	);
742
743
	if ( $forms->have_posts() ) {
744
		while ( $forms->have_posts() ) {
745
			$forms->the_post();
746
747
			// Form content.
748
			// Note in version 1.8 display content setting split into display content and content placement setting.
749
			// You can delete _give_content_option in future
750
			$show_content = give_get_meta( get_the_ID(), '_give_content_option', true );
751
			if ( $show_content && ! give_get_meta( get_the_ID(), '_give_display_content', true ) ) {
752
				$field_value = ( 'none' !== $show_content ? 'enabled' : 'disabled' );
753
				give_update_meta( get_the_ID(), '_give_display_content', $field_value );
754
755
				$field_value = ( 'none' !== $show_content ? $show_content : 'give_pre_form' );
756
				give_update_meta( get_the_ID(), '_give_content_placement', $field_value );
757
			}
758
759
			// "Disable" Guest Donation. Checkbox
760
			// See: https://github.com/WordImpress/Give/issues/1470
761
			$guest_donation        = give_get_meta( get_the_ID(), '_give_logged_in_only', true );
762
			$guest_donation_newval = ( in_array( $guest_donation, array( 'yes', 'on' ) ) ? 'disabled' : 'enabled' );
763
			give_update_meta( get_the_ID(), '_give_logged_in_only', $guest_donation_newval );
764
765
			// Offline Donations
766
			// See: https://github.com/WordImpress/Give/issues/1579
767
			$offline_donation = give_get_meta( get_the_ID(), '_give_customize_offline_donations', true );
768
			if ( 'no' === $offline_donation ) {
769
				$offline_donation_newval = 'global';
770
			} elseif ( 'yes' === $offline_donation ) {
771
				$offline_donation_newval = 'enabled';
772
			} else {
773
				$offline_donation_newval = 'disabled';
774
			}
775
			give_update_meta( get_the_ID(), '_give_customize_offline_donations', $offline_donation_newval );
776
777
			// Convert yes/no setting field to enabled/disabled.
778
			$form_radio_settings = array(
779
				// Custom Amount.
780
				'_give_custom_amount',
781
782
				// Donation Gaol.
783
				'_give_goal_option',
784
785
				// Close Form.
786
				'_give_close_form_when_goal_achieved',
787
788
				// Term & conditions.
789
				'_give_terms_option',
790
791
				// Billing fields.
792
				'_give_offline_donation_enable_billing_fields_single',
793
			);
794
795
			foreach ( $form_radio_settings as $meta_key ) {
796
				// Get value.
797
				$field_value = give_get_meta( get_the_ID(), $meta_key, true );
798
799
				// Convert meta value only if it is in yes/no/none.
800
				if ( in_array( $field_value, array( 'yes', 'on', 'no', 'none' ) ) ) {
801
802
					$field_value = ( in_array( $field_value, array( 'yes', 'on' ) ) ? 'enabled' : 'disabled' );
803
					give_update_meta( get_the_ID(), $meta_key, $field_value );
804
				}
805
			}
806
		}// 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...
807
808
		wp_reset_postdata();
809
810
		// Forms found so upgrade them
811
		$step ++;
812
		$redirect = add_query_arg( array(
813
			'page'         => 'give-upgrades',
814
			'give-upgrade' => 'give_v18_upgrades_form_metadata',
815
			'step'         => $step,
816
		), admin_url( 'index.php' ) );
817
		wp_redirect( $redirect );
818
		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...
819
820
	} else {
821
		// No more forms found, finish up.
822
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
823
		delete_option( 'give_doing_upgrade' );
824
		give_set_upgrade_complete( 'v18_upgrades_form_metadata' );
825
826
		wp_redirect( admin_url() );
827
		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...
828
	}
829
}
830
831
add_action( 'give_give_v18_upgrades_form_metadata', 'give_v18_upgrades_form_metadata' );
832
833
/**
834
 * Get list of core setting renamed in version 1.8.
835
 *
836
 * @since  1.8
837
 * @return array
838
 */
839
function give_v18_renamed_core_settings() {
840
	return array(
841
		'disable_paypal_verification' => 'paypal_verification',
842
		'disable_css'                 => 'css',
843
		'disable_welcome'             => 'welcome',
844
		'disable_forms_singular'      => 'forms_singular',
845
		'disable_forms_archives'      => 'forms_archives',
846
		'disable_forms_excerpt'       => 'forms_excerpt',
847
		'disable_form_featured_img'   => 'form_featured_img',
848
		'disable_form_sidebar'        => 'form_sidebar',
849
		'disable_admin_notices'       => 'admin_notices',
850
		'disable_the_content_filter'  => 'the_content_filter',
851
		'enable_floatlabels'          => 'floatlabels',
852
		'enable_categories'           => 'categories',
853
		'enable_tags'                 => 'tags',
854
	);
855
}
856
857
858
/**
859
 * Upgrade core settings.
860
 *
861
 * @since  1.8.7
862
 * @return void
863
 */
864
function give_v187_upgrades() {
865
	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...
866
867
	/**
868
	 * Upgrade 1: Remove stat and cache transients.
869
	 */
870
	$cached_options = $wpdb->get_col(
871
		$wpdb->prepare(
872
			"SELECT * FROM {$wpdb->options} where (option_name LIKE '%%%s%%' OR option_name LIKE '%%%s%%')",
873
			array(
874
				'_transient_give_stats_',
875
				'give_cache',
876
				'_transient_give_add_ons_feed',
877
				'_transient__give_ajax_works' .
878
				'_transient_give_total_api_keys',
879
				'_transient_give_i18n_give_promo_hide',
880
				'_transient_give_contributors',
881
				'_transient_give_estimated_monthly_stats',
882
				'_transient_give_earnings_total',
883
				'_transient_give_i18n_give_',
884
				'_transient__give_installed',
885
				'_transient__give_activation_redirect',
886
				'_transient__give_hide_license_notices_shortly_',
887
				'give_income_total',
888
			)
889
		),
890
		1
891
	);
892
893
	// User related transients.
894
	$user_apikey_options = $wpdb->get_results(
895
		$wpdb->prepare(
896
			"SELECT user_id, meta_key
897
			FROM $wpdb->usermeta
898
			WHERE meta_value=%s",
899
			'give_user_public_key'
900
		),
901
		ARRAY_A
902
	);
903
904
	if ( ! empty( $user_apikey_options ) ) {
905
		foreach ( $user_apikey_options as $user ) {
906
			$cached_options[] = '_transient_' . md5( 'give_api_user_' . $user['meta_key'] );
907
			$cached_options[] = '_transient_' . md5( 'give_api_user_public_key' . $user['user_id'] );
908
			$cached_options[] = '_transient_' . md5( 'give_api_user_secret_key' . $user['user_id'] );
909
		}
910
	}
911
912
	if ( ! empty( $cached_options ) ) {
913
		foreach ( $cached_options as $option ) {
914
			switch ( true ) {
915
				case ( false !== strpos( $option, 'transient' ) ):
916
					$option = str_replace( '_transient_', '', $option );
917
					delete_transient( $option );
918
					break;
919
920
				default:
921
					delete_option( $option );
922
			}
923
		}
924
	}
925
}
926
927
/**
928
 * Update Capabilities for Give_Worker User Role.
929
 *
930
 * This upgrade routine will update access rights for Give_Worker User Role.
931
 *
932
 * @since      1.8.8
933
 */
934
function give_v188_upgrades() {
935
936
	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...
937
938
	// Get the role object.
939
	$give_worker = get_role( 'give_worker' );
940
941
	// A list of capabilities to add for give workers.
942
	$caps_to_add = array(
943
		'edit_posts',
944
		'edit_pages',
945
	);
946
947
	foreach ( $caps_to_add as $cap ) {
948
		// Add the capability.
949
		$give_worker->add_cap( $cap );
950
	}
951
952
}
953
954
/**
955
 * Update Post meta for minimum and maximum amount for multi level donation forms
956
 *
957
 * This upgrade routine adds post meta for give_forms CPT for multi level donation form.
958
 *
959
 * @since      1.8.9
960
 */
961
function give_v189_upgrades_levels_post_meta_callback() {
962
963
	if ( ! current_user_can( 'manage_give_settings' ) ) {
964
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
965
			'response' => 403,
966
		) );
967
	}
968
969
	ignore_user_abort( true );
970
971
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
972
		@set_time_limit( 0 );
973
	}
974
975
	$step = isset( $_GET['step'] ) ? absint( $_GET['step'] ) : 1;
976
977
	// form query
978
	$donation_forms = new WP_Query( array(
979
			'paged'          => $step,
980
			'status'         => 'any',
981
			'order'          => 'ASC',
982
			'post_type'      => 'give_forms',
983
			'posts_per_page' => 20,
984
		)
985
	);
986
987
	if ( $donation_forms->have_posts() ) {
988
		while ( $donation_forms->have_posts() ) {
989
			$donation_forms->the_post();
990
			$form_id = get_the_ID();
991
992
			// Remove formatting from _give_set_price
993
			update_post_meta(
994
				$form_id,
995
				'_give_set_price',
996
				give_sanitize_amount( get_post_meta( $form_id, '_give_set_price', true ) )
997
			);
998
999
			// Remove formatting from _give_custom_amount_minimum
1000
			update_post_meta(
1001
				$form_id,
1002
				'_give_custom_amount_minimum',
1003
				give_sanitize_amount( get_post_meta( $form_id, '_give_custom_amount_minimum', true ) )
1004
			);
1005
1006
			// Bailout.
1007
			if ( 'set' === get_post_meta( $form_id, '_give_price_option', true ) ) {
1008
				continue;
1009
			}
1010
1011
			$donation_levels = get_post_meta( $form_id, '_give_donation_levels', true );
1012
1013
			if ( ! empty( $donation_levels ) ) {
1014
1015
				foreach ( $donation_levels as $index => $donation_level ) {
1016
					if( isset( $donation_level['_give_amount'] ) ) {
1017
						$donation_levels[$index]['_give_amount'] = give_sanitize_amount( $donation_level['_give_amount'] );
1018
					}
1019
				}
1020
1021
				update_post_meta( $form_id, '_give_donation_levels', $donation_levels );
1022
1023
				$donation_levels_amounts = wp_list_pluck( $donation_levels, '_give_amount' );
1024
1025
				$min_amount = min( $donation_levels_amounts );
1026
				$max_amount = max( $donation_levels_amounts );
1027
1028
				// Set Minimum and Maximum amount for Multi Level Donation Forms
1029
				give_update_meta( $form_id, '_give_levels_minimum_amount', $min_amount ? give_sanitize_amount( $min_amount ) : 0 );
1030
				give_update_meta( $form_id, '_give_levels_maximum_amount', $max_amount ? give_sanitize_amount( $max_amount ) : 0 );
1031
			}
1032
1033
		}
1034
1035
		/* Restore original Post Data */
1036
		wp_reset_postdata();
1037
1038
		// Forms found so upgrade them
1039
		$step ++;
1040
		$redirect = add_query_arg( array(
1041
			'page'         => 'give-upgrades',
1042
			'give-upgrade' => 'v189_upgrades_levels_post_meta',
1043
			'step'         => $step,
1044
		), admin_url( 'index.php' ) );
1045
		wp_redirect( $redirect );
1046
		exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_v189_upgrades_levels_post_meta_callback() 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...
1047
	} else {
1048
		// The Update Ran.
1049
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
1050
		give_set_upgrade_complete( 'v189_upgrades_levels_post_meta' );
1051
		delete_option( 'give_doing_upgrade' );
1052
1053
		wp_redirect( admin_url() );
1054
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_v189_upgrades_levels_post_meta_callback() 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...
1055
	}
1056
1057
}
1058
1059
add_action( 'give_v189_upgrades_levels_post_meta', 'give_v189_upgrades_levels_post_meta_callback' );
1060
1061
1062
/**
1063
 * Give version 1.8.9 upgrades
1064
 *
1065
 * @since      1.8.9
1066
 */
1067
function give_v189_upgrades() {
1068
	/**
1069
	 * 1. Remove user license related notice show blocked ( Give_Notice will handle )
1070
	 */
1071
	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...
1072
1073
	// Delete permanent notice blocker.
1074
	$wpdb->query(
1075
		$wpdb->prepare(
1076
			"
1077
					DELETE FROM $wpdb->usermeta
1078
					WHERE meta_key
1079
					LIKE '%%%s%%'
1080
					",
1081
			'_give_hide_license_notices_permanently'
1082
		)
1083
	);
1084
1085
	// Delete short notice blocker.
1086
	$wpdb->query(
1087
		$wpdb->prepare(
1088
			"
1089
					DELETE FROM $wpdb->options
1090
					WHERE option_name
1091
					LIKE '%%%s%%'
1092
					",
1093
			'__give_hide_license_notices_shortly_'
1094
		)
1095
	);
1096
1097
}
1098