Completed
Push — issues/1781 ( da0482 )
by Ravinder
19:23
created

upgrade-functions.php ➔ give_show_upgrade_notices()   D

Complexity

Conditions 14
Paths 41

Size

Total Lines 96
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

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