Test Failed
Push — issues/1925 ( 817edf )
by Ravinder
04:56
created

upgrade-functions.php ➔ give_v1812_update_amount_values_callback()   D

Complexity

Conditions 15
Paths 133

Size

Total Lines 91
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 44
nc 133
nop 0
dl 0
loc 91
rs 4.597
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
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;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
40
41
		case version_compare( $give_version, '1.7', '<' ) :
42
			give_v17_upgrades();
43
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
44
45
		case version_compare( $give_version, '1.8', '<' ) :
46
			give_v18_upgrades();
47
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
48
49
		case version_compare( $give_version, '1.8.7', '<' ) :
50
			give_v187_upgrades();
51
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
52
53
		case version_compare( $give_version, '1.8.8', '<' ) :
54
			give_v188_upgrades();
55
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
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
 * @since 1.8.12 Update new update process code.
76
 *
77
 * @param Give_Updates $give_updates
78
 *
79
 * @return void
80
 */
81
function give_show_upgrade_notices( $give_updates ) {
82
	// v1.3.2 Upgrades
83
	$give_updates->register(
84
		array(
85
			'id'       => 'upgrade_give_payment_customer_id',
86
			'version'  => '1.3.2',
87
			'callback' => 'give_v132_upgrade_give_payment_customer_id',
88
		)
89
	);
90
91
	// v1.3.4 Upgrades ensure the user has gone through 1.3.4.
92
	$give_updates->register(
93
		array(
94
			'id'       => 'upgrade_give_offline_status',
95
			'depend'   => 'upgrade_give_payment_customer_id',
96
			'version'  => '1.3.4',
97
			'callback' => 'give_v134_upgrade_give_offline_status',
98
		)
99
	);
100
101
	// v1.8 form metadata upgrades.
102
	$give_updates->register(
103
		array(
104
			'id'       => 'v18_upgrades_form_metadata',
105
			'version'  => '1.8',
106
			'callback' => 'give_v18_upgrades_form_metadata',
107
		)
108
	);
109
110
	// v1.8.9 Upgrades
111
	$give_updates->register(
112
		array(
113
			'id'       => 'v189_upgrades_levels_post_meta',
114
			'version'  => '1.8.9',
115
			'callback' => 'give_v189_upgrades_levels_post_meta_callback',
116
		)
117
	);
118
119
	// v1.8.12 Upgrades
120
	$give_updates->register(
121
		array(
122
			'id'       => 'v1812_update_amount_values',
123
			'version'  => '1.8.12',
124
			'callback' => 'give_v1812_update_amount_values_callback',
125
		)
126
	);
127
128
	// v1.8.12 Upgrades
129
	$give_updates->register(
130
		array(
131
			'id'       => 'v1812_update_donor_purchase_values',
132
			'version'  => '1.8.12',
133
			'callback' => 'give_v1812_update_donor_purchase_value_callback',
134
		)
135
	);
136
}
137
138
add_action( 'give_register_updates', 'give_show_upgrade_notices' );
139
140
/**
141
 * Triggers all upgrade functions
142
 *
143
 * This function is usually triggered via AJAX
144
 *
145
 * @since 1.0
146
 * @return void
147
 */
148
function give_trigger_upgrades() {
149
150 View Code Duplication
	if ( ! current_user_can( 'manage_give_settings' ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
151
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
152
			'response' => 403,
153
		) );
154
	}
155
156
	$give_version = get_option( 'give_version' );
157
158
	if ( ! $give_version ) {
159
		// 1.0 is the first version to use this option so we must add it.
160
		$give_version = '1.0';
161
		add_option( 'give_version', $give_version );
162
	}
163
164
	update_option( 'give_version', GIVE_VERSION );
165
	delete_option( 'give_doing_upgrade' );
166
167
	if ( DOING_AJAX ) {
168
		die( 'complete' );
169
	} // End if().
170
}
171
172
add_action( 'wp_ajax_give_trigger_upgrades', 'give_trigger_upgrades' );
173
174
/**
175
 * Check if the upgrade routine has been run for a specific action
176
 *
177
 * @since  1.0
178
 *
179
 * @param  string $upgrade_action The upgrade action to check completion for
180
 *
181
 * @return bool                   If the action has been added to the completed actions array
182
 */
183
function give_has_upgrade_completed( $upgrade_action = '' ) {
184
185
	if ( empty( $upgrade_action ) ) {
186
		return false;
187
	}
188
189
	$completed_upgrades = give_get_completed_upgrades();
190
191
	return in_array( $upgrade_action, $completed_upgrades );
192
193
}
194
195
/**
196
 * For use when doing 'stepped' upgrade routines, to see if we need to start somewhere in the middle
197
 *
198
 * @since 1.8
199
 *
200
 * @return mixed   When nothing to resume returns false, otherwise starts the upgrade where it left off
201
 */
202
function give_maybe_resume_upgrade() {
203
	$doing_upgrade = get_option( 'give_doing_upgrade', false );
204
	if ( empty( $doing_upgrade ) ) {
205
		return false;
206
	}
207
208
	return $doing_upgrade;
209
}
210
211
/**
212
 * Adds an upgrade action to the completed upgrades array
213
 *
214
 * @since  1.0
215
 *
216
 * @param  string $upgrade_action The action to add to the completed upgrades array
217
 *
218
 * @return bool                   If the function was successfully added
219
 */
220
function give_set_upgrade_complete( $upgrade_action = '' ) {
221
222
	if ( empty( $upgrade_action ) ) {
223
		return false;
224
	}
225
226
	$completed_upgrades   = give_get_completed_upgrades();
227
	$completed_upgrades[] = $upgrade_action;
228
229
	// Remove any blanks, and only show uniques.
230
	$completed_upgrades = array_unique( array_values( $completed_upgrades ) );
231
232
	/**
233
	 * Fire the action when any upgrade set to complete.
234
	 *
235
	 * @since 1.8.12
236
	 */
237
	do_action( 'give_set_upgrade_completed', $upgrade_action, $completed_upgrades );
238
239
	return update_option( 'give_completed_upgrades', $completed_upgrades );
240
}
241
242
/**
243
 * Get's the array of completed upgrade actions
244
 *
245
 * @since  1.0
246
 * @return array The array of completed upgrades
247
 */
248
function give_get_completed_upgrades() {
249
250
	return (array) get_option( 'give_completed_upgrades' );
251
252
}
253
254
/**
255
 * Upgrades the
256
 *
257
 * Standardizes the discrepancies between two metakeys `_give_payment_customer_id` and `_give_payment_donor_id`
258
 *
259
 * @since      1.3.2
260
 */
261
function give_v132_upgrade_give_payment_customer_id() {
262
	global $wpdb;
263
264
	/* @var Give_Updates $give_updates */
265
	$give_updates = Give_Updates::get_instance();
266
267 View Code Duplication
	if ( ! current_user_can( 'manage_give_settings' ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
268
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
269
			'response' => 403,
270
		) );
271
	}
272
273
	ignore_user_abort( true );
274
275
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
276
		@set_time_limit( 0 );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
Coding Style introduced by
Silencing errors is discouraged
Loading history...
277
	}
278
279
	// UPDATE DB METAKEYS.
280
	$sql   = "UPDATE $wpdb->postmeta SET meta_key = '_give_payment_customer_id' WHERE meta_key = '_give_payment_donor_id'";
281
	$query = $wpdb->query( $sql );
0 ignored issues
show
Unused Code introduced by
$query is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
282
283
	$give_updates->percentage = 100;
0 ignored issues
show
Documentation Bug introduced by
It seems like 100 of type integer is incompatible with the declared type array of property $percentage.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
284
	give_set_upgrade_complete( 'upgrade_give_payment_customer_id' );
285
}
286
287
288
/**
289
 * Upgrades the Offline Status
290
 *
291
 * Reverses the issue where offline donations in "pending" status where inappropriately marked as abandoned
292
 *
293
 * @since      1.3.4
294
 */
295
function give_v134_upgrade_give_offline_status() {
296
	global $wpdb;
297
298
	/* @var Give_Updates $give_updates */
299
	$give_updates = Give_Updates::get_instance();
300
301
	// Get abandoned offline payments.
302
	$select = "SELECT ID FROM $wpdb->posts p ";
303
	$join   = "LEFT JOIN $wpdb->postmeta m ON p.ID = m.post_id ";
304
	$where  = "WHERE p.post_type = 'give_payment' ";
305
	$where  .= "AND ( p.post_status = 'abandoned' )";
306
	$where  .= "AND ( m.meta_key = '_give_payment_gateway' AND m.meta_value = 'offline' )";
307
308
	$sql            = $select . $join . $where;
309
	$found_payments = $wpdb->get_col( $sql );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
310
311
	foreach ( $found_payments as $payment ) {
312
313
		// Only change ones marked abandoned since our release last week because the admin may have marked some abandoned themselves.
314
		$modified_time = get_post_modified_time( 'U', false, $payment );
315
316
		// 1450124863 =  12/10/2015 20:42:25.
317
		if ( $modified_time >= 1450124863 ) {
318
319
			give_update_payment_status( $payment, 'pending' );
320
321
		}
322
	}
323
324
	$give_updates->percentage = 100;
0 ignored issues
show
Documentation Bug introduced by
It seems like 100 of type integer is incompatible with the declared type array of property $percentage.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
325
	give_set_upgrade_complete( 'upgrade_give_offline_status' );
326
}
327
328
329
/**
330
 * Cleanup User Roles
331
 *
332
 * This upgrade routine removes unused roles and roles with typos
333
 *
334
 * @since      1.5.2
335
 */
336
function give_v152_cleanup_users() {
337
338
	$give_version = get_option( 'give_version' );
339
340
	if ( ! $give_version ) {
341
		// 1.0 is the first version to use this option so we must add it.
342
		$give_version = '1.0';
343
	}
344
345
	$give_version = preg_replace( '/[^0-9.].*/', '', $give_version );
346
347
	// v1.5.2 Upgrades
348
	if ( version_compare( $give_version, '1.5.2', '<' ) || ! give_has_upgrade_completed( 'upgrade_give_user_caps_cleanup' ) ) {
349
350
		// Delete all caps with "ss".
351
		// Also delete all unused "campaign" roles.
352
		$delete_caps = array(
353
			'delete_give_formss',
354
			'delete_others_give_formss',
355
			'delete_private_give_formss',
356
			'delete_published_give_formss',
357
			'read_private_forms',
358
			'edit_give_formss',
359
			'edit_others_give_formss',
360
			'edit_private_give_formss',
361
			'edit_published_give_formss',
362
			'publish_give_formss',
363
			'read_private_give_formss',
364
			'assign_give_campaigns_terms',
365
			'delete_give_campaigns',
366
			'delete_give_campaigns_terms',
367
			'delete_give_campaignss',
368
			'delete_others_give_campaignss',
369
			'delete_private_give_campaignss',
370
			'delete_published_give_campaignss',
371
			'edit_give_campaigns',
372
			'edit_give_campaigns_terms',
373
			'edit_give_campaignss',
374
			'edit_others_give_campaignss',
375
			'edit_private_give_campaignss',
376
			'edit_published_give_campaignss',
377
			'manage_give_campaigns_terms',
378
			'publish_give_campaignss',
379
			'read_give_campaigns',
380
			'read_private_give_campaignss',
381
			'view_give_campaigns_stats',
382
			'delete_give_paymentss',
383
			'delete_others_give_paymentss',
384
			'delete_private_give_paymentss',
385
			'delete_published_give_paymentss',
386
			'edit_give_paymentss',
387
			'edit_others_give_paymentss',
388
			'edit_private_give_paymentss',
389
			'edit_published_give_paymentss',
390
			'publish_give_paymentss',
391
			'read_private_give_paymentss',
392
		);
393
394
		global $wp_roles;
395
		foreach ( $delete_caps as $cap ) {
396
			foreach ( array_keys( $wp_roles->roles ) as $role ) {
397
				$wp_roles->remove_cap( $role, $cap );
398
			}
399
		}
400
401
		// Create Give plugin roles.
402
		$roles = new Give_Roles();
403
		$roles->add_roles();
404
		$roles->add_caps();
405
406
		// The Update Ran.
407
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
408
		give_set_upgrade_complete( 'upgrade_give_user_caps_cleanup' );
409
		delete_option( 'give_doing_upgrade' );
410
411
	}// End if().
412
413
}
414
415
add_action( 'admin_init', 'give_v152_cleanup_users' );
416
417
/**
418
 * 1.6 Upgrade routine to create the customer meta table.
419
 *
420
 * @since  1.6
421
 * @return void
422
 */
423
function give_v16_upgrades() {
424
	// Create the donor databases.
425
	$donors_db = new Give_DB_Donors();
426
	$donors_db->create_table();
427
	$donor_meta = new Give_DB_Donor_Meta();
428
	$donor_meta->create_table();
429
}
430
431
/**
432
 * 1.7 Upgrades.
433
 *
434
 * a. Update license api data for plugin addons.
435
 * b. Cleanup user roles.
436
 *
437
 * @since  1.7
438
 * @return void
439
 */
440
function give_v17_upgrades() {
441
	// Upgrade license data.
442
	give_v17_upgrade_addon_license_data();
443
	give_v17_cleanup_roles();
444
}
445
446
/**
447
 * Upgrade license data
448
 *
449
 * @since 1.7
450
 */
451
function give_v17_upgrade_addon_license_data() {
452
	$give_options = give_get_settings();
453
454
	$api_url = 'https://givewp.com/give-sl-api/';
455
456
	// Get addons license key.
457
	$addons = array();
458
	foreach ( $give_options as $key => $value ) {
459
		if ( false !== strpos( $key, '_license_key' ) ) {
460
			$addons[ $key ] = $value;
461
		}
462
	}
463
464
	// Bailout: We do not have any addon license data to upgrade.
465
	if ( empty( $addons ) ) {
466
		return false;
467
	}
468
469
	foreach ( $addons as $key => $addon_license ) {
470
471
		// Get addon shortname.
472
		$shortname = str_replace( '_license_key', '', $key );
473
474
		// Addon license option name.
475
		$addon_license_option_name = $shortname . '_license_active';
476
477
		// bailout if license is empty.
478
		if ( empty( $addon_license ) ) {
479
			delete_option( $addon_license_option_name );
480
			continue;
481
		}
482
483
		// Get addon name.
484
		$addon_name       = array();
485
		$addon_name_parts = explode( '_', str_replace( 'give_', '', $shortname ) );
486
		foreach ( $addon_name_parts as $name_part ) {
487
488
			// Fix addon name
489
			switch ( $name_part ) {
490
				case 'authorizenet' :
491
					$name_part = 'authorize.net';
492
					break;
493
			}
494
495
			$addon_name[] = ucfirst( $name_part );
496
		}
497
498
		$addon_name = implode( ' ', $addon_name );
499
500
		// Data to send to the API
501
		$api_params = array(
502
			'edd_action' => 'activate_license', // never change from "edd_" to "give_"!
503
			'license'    => $addon_license,
504
			'item_name'  => urlencode( $addon_name ),
505
			'url'        => home_url(),
506
		);
507
508
		// Call the API.
509
		$response = wp_remote_post(
510
			$api_url,
511
			array(
512
				'timeout'   => 15,
513
				'sslverify' => false,
514
				'body'      => $api_params,
515
			)
516
		);
517
518
		// Make sure there are no errors.
519
		if ( is_wp_error( $response ) ) {
520
			delete_option( $addon_license_option_name );
521
			continue;
522
		}
523
524
		// Tell WordPress to look for updates.
525
		set_site_transient( 'update_plugins', null );
526
527
		// Decode license data.
528
		$license_data = json_decode( wp_remote_retrieve_body( $response ) );
529
		update_option( $addon_license_option_name, $license_data );
530
	}// End foreach().
531
}
532
533
534
/**
535
 * Cleanup User Roles.
536
 *
537
 * This upgrade routine removes unused roles and roles with typos.
538
 *
539
 * @since      1.7
540
 */
541
function give_v17_cleanup_roles() {
542
543
	// Delete all caps with "_give_forms_" and "_give_payments_"
544
	// These roles have no usage; the proper is singular.
545
	$delete_caps = array(
546
		'view_give_forms_stats',
547
		'delete_give_forms_terms',
548
		'assign_give_forms_terms',
549
		'edit_give_forms_terms',
550
		'manage_give_forms_terms',
551
		'view_give_payments_stats',
552
		'manage_give_payments_terms',
553
		'edit_give_payments_terms',
554
		'assign_give_payments_terms',
555
		'delete_give_payments_terms',
556
	);
557
558
	global $wp_roles;
559
	foreach ( $delete_caps as $cap ) {
560
		foreach ( array_keys( $wp_roles->roles ) as $role ) {
561
			$wp_roles->remove_cap( $role, $cap );
562
		}
563
	}
564
565
	// Set roles again.
566
	$roles = new Give_Roles();
567
	$roles->add_roles();
568
	$roles->add_caps();
569
570
}
571
572
/**
573
 * 1.8 Upgrades.
574
 *
575
 * a. Upgrade checkbox settings to radio button settings.
576
 * a. Update form meta for new metabox settings.
577
 *
578
 * @since  1.8
579
 * @return void
580
 */
581
function give_v18_upgrades() {
582
	// Upgrade checkbox settings to radio button settings.
583
	give_v18_upgrades_core_setting();
584
}
585
586
/**
587
 * Upgrade core settings.
588
 *
589
 * @since  1.8
590
 * @return void
591
 */
592
function give_v18_upgrades_core_setting() {
593
	// Core settings which changes from checkbox to radio.
594
	$core_setting_names = array_merge(
595
		array_keys( give_v18_renamed_core_settings() ),
596
		array(
597
			'uninstall_on_delete',
598
			'scripts_footer',
599
			'test_mode',
600
			'email_access',
601
			'terms',
602
			'give_offline_donation_enable_billing_fields',
603
		)
604
	);
605
606
	// Bailout: If not any setting define.
607
	if ( $give_settings = get_option( 'give_settings' ) ) {
608
609
		$setting_changed = false;
610
611
		// Loop: check each setting field.
612
		foreach ( $core_setting_names as $setting_name ) {
613
			// New setting name.
614
			$new_setting_name = preg_replace( '/^(enable_|disable_)/', '', $setting_name );
615
616
			// Continue: If setting already set.
617
			if (
618
				array_key_exists( $new_setting_name, $give_settings )
619
				&& in_array( $give_settings[ $new_setting_name ], array( 'enabled', 'disabled' ) )
620
			) {
621
				continue;
622
			}
623
624
			// Set checkbox value to radio value.
625
			$give_settings[ $setting_name ] = ( ! empty( $give_settings[ $setting_name ] ) && 'on' === $give_settings[ $setting_name ] ? 'enabled' : 'disabled' );
626
627
			// @see https://github.com/WordImpress/Give/issues/1063
628
			if ( false !== strpos( $setting_name, 'disable_' ) ) {
629
630
				$give_settings[ $new_setting_name ] = ( give_is_setting_enabled( $give_settings[ $setting_name ] ) ? 'disabled' : 'enabled' );
631
			} elseif ( false !== strpos( $setting_name, 'enable_' ) ) {
632
633
				$give_settings[ $new_setting_name ] = ( give_is_setting_enabled( $give_settings[ $setting_name ] ) ? 'enabled' : 'disabled' );
634
			}
635
636
			// Tell bot to update core setting to db.
637
			if ( ! $setting_changed ) {
638
				$setting_changed = true;
639
			}
640
		}
641
642
		// Update setting only if they changed.
643
		if ( $setting_changed ) {
644
			update_option( 'give_settings', $give_settings );
645
		}
646
	}// End if().
647
648
	give_set_upgrade_complete( 'v18_upgrades_core_setting' );
649
}
650
651
/**
652
 * Upgrade form metadata for new metabox settings.
653
 *
654
 * @since  1.8
655
 * @return void
656
 */
657
function give_v18_upgrades_form_metadata() {
658
	/* @var Give_Updates $give_updates */
659
	$give_updates = Give_Updates::get_instance();
660
661
	// form query
662
	$forms = new WP_Query( array(
663
			'paged'          => $give_updates->step,
664
			'status'         => 'any',
665
			'order'          => 'ASC',
666
			'post_type'      => 'give_forms',
667
			'posts_per_page' => 20,
668
		)
669
	);
670
671
	if ( $forms->have_posts() ) {
672
		$give_updates->set_percentage( $forms->found_posts, $give_updates->step * 20 );
673
674
		while ( $forms->have_posts() ) {
675
			$forms->the_post();
676
677
			// Form content.
678
			// Note in version 1.8 display content setting split into display content and content placement setting.
679
			// You can delete _give_content_option in future
680
			$show_content = give_get_meta( get_the_ID(), '_give_content_option', true );
681
			if ( $show_content && ! give_get_meta( get_the_ID(), '_give_display_content', true ) ) {
682
				$field_value = ( 'none' !== $show_content ? 'enabled' : 'disabled' );
683
				give_update_meta( get_the_ID(), '_give_display_content', $field_value );
684
685
				$field_value = ( 'none' !== $show_content ? $show_content : 'give_pre_form' );
686
				give_update_meta( get_the_ID(), '_give_content_placement', $field_value );
687
			}
688
689
			// "Disable" Guest Donation. Checkbox
690
			// See: https://github.com/WordImpress/Give/issues/1470
691
			$guest_donation        = give_get_meta( get_the_ID(), '_give_logged_in_only', true );
692
			$guest_donation_newval = ( in_array( $guest_donation, array( 'yes', 'on' ) ) ? 'disabled' : 'enabled' );
693
			give_update_meta( get_the_ID(), '_give_logged_in_only', $guest_donation_newval );
694
695
			// Offline Donations
696
			// See: https://github.com/WordImpress/Give/issues/1579
697
			$offline_donation = give_get_meta( get_the_ID(), '_give_customize_offline_donations', true );
698
			if ( 'no' === $offline_donation ) {
699
				$offline_donation_newval = 'global';
700
			} elseif ( 'yes' === $offline_donation ) {
701
				$offline_donation_newval = 'enabled';
702
			} else {
703
				$offline_donation_newval = 'disabled';
704
			}
705
			give_update_meta( get_the_ID(), '_give_customize_offline_donations', $offline_donation_newval );
706
707
			// Convert yes/no setting field to enabled/disabled.
708
			$form_radio_settings = array(
709
				// Custom Amount.
710
				'_give_custom_amount',
711
712
				// Donation Gaol.
713
				'_give_goal_option',
714
715
				// Close Form.
716
				'_give_close_form_when_goal_achieved',
717
718
				// Term & conditions.
719
				'_give_terms_option',
720
721
				// Billing fields.
722
				'_give_offline_donation_enable_billing_fields_single',
723
			);
724
725
			foreach ( $form_radio_settings as $meta_key ) {
726
				// Get value.
727
				$field_value = give_get_meta( get_the_ID(), $meta_key, true );
728
729
				// Convert meta value only if it is in yes/no/none.
730
				if ( in_array( $field_value, array( 'yes', 'on', 'no', 'none' ) ) ) {
731
732
					$field_value = ( in_array( $field_value, array( 'yes', 'on' ) ) ? 'enabled' : 'disabled' );
733
					give_update_meta( get_the_ID(), $meta_key, $field_value );
734
				}
735
			}
736
		}// End while().
737
738
		wp_reset_postdata();
739
740
	} else {
741
		// No more forms found, finish up.
742
		give_set_upgrade_complete( 'v18_upgrades_form_metadata' );
743
	}
744
}
745
746
747
/**
748
 * Get list of core setting renamed in version 1.8.
749
 *
750
 * @since  1.8
751
 * @return array
752
 */
753
function give_v18_renamed_core_settings() {
754
	return array(
755
		'disable_paypal_verification' => 'paypal_verification',
756
		'disable_css'                 => 'css',
757
		'disable_welcome'             => 'welcome',
758
		'disable_forms_singular'      => 'forms_singular',
759
		'disable_forms_archives'      => 'forms_archives',
760
		'disable_forms_excerpt'       => 'forms_excerpt',
761
		'disable_form_featured_img'   => 'form_featured_img',
762
		'disable_form_sidebar'        => 'form_sidebar',
763
		'disable_admin_notices'       => 'admin_notices',
764
		'disable_the_content_filter'  => 'the_content_filter',
765
		'enable_floatlabels'          => 'floatlabels',
766
		'enable_categories'           => 'categories',
767
		'enable_tags'                 => 'tags',
768
	);
769
}
770
771
772
/**
773
 * Upgrade core settings.
774
 *
775
 * @since  1.8.7
776
 * @return void
777
 */
778
function give_v187_upgrades() {
779
	global $wpdb;
780
781
	/**
782
	 * Upgrade 1: Remove stat and cache transients.
783
	 */
784
	$cached_options = $wpdb->get_col(
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
785
		$wpdb->prepare(
786
			"SELECT * FROM {$wpdb->options} where (option_name LIKE '%%%s%%' OR option_name LIKE '%%%s%%')",
787
			array(
788
				'_transient_give_stats_',
789
				'give_cache',
790
				'_transient_give_add_ons_feed',
791
				'_transient__give_ajax_works' .
792
				'_transient_give_total_api_keys',
793
				'_transient_give_i18n_give_promo_hide',
794
				'_transient_give_contributors',
795
				'_transient_give_estimated_monthly_stats',
796
				'_transient_give_earnings_total',
797
				'_transient_give_i18n_give_',
798
				'_transient__give_installed',
799
				'_transient__give_activation_redirect',
800
				'_transient__give_hide_license_notices_shortly_',
801
				'give_income_total',
802
			)
803
		),
804
		1
805
	);
806
807
	// User related transients.
808
	$user_apikey_options = $wpdb->get_results(
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
809
		$wpdb->prepare(
810
			"SELECT user_id, meta_key
811
			FROM $wpdb->usermeta
0 ignored issues
show
introduced by
Usage of users/usermeta tables is highly discouraged in VIP context, For storing user additional user metadata, you should look at User Attributes.
Loading history...
812
			WHERE meta_value=%s",
813
			'give_user_public_key'
814
		),
815
		ARRAY_A
816
	);
817
818
	if ( ! empty( $user_apikey_options ) ) {
819
		foreach ( $user_apikey_options as $user ) {
820
			$cached_options[] = '_transient_' . md5( 'give_api_user_' . $user['meta_key'] );
821
			$cached_options[] = '_transient_' . md5( 'give_api_user_public_key' . $user['user_id'] );
822
			$cached_options[] = '_transient_' . md5( 'give_api_user_secret_key' . $user['user_id'] );
823
		}
824
	}
825
826
	if ( ! empty( $cached_options ) ) {
827
		foreach ( $cached_options as $option ) {
828 View Code Duplication
			switch ( true ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
829
				case ( false !== strpos( $option, 'transient' ) ):
830
					$option = str_replace( '_transient_', '', $option );
831
					delete_transient( $option );
832
					break;
833
834
				default:
835
					delete_option( $option );
836
			}
837
		}
838
	}
839
}
840
841
/**
842
 * Update Capabilities for Give_Worker User Role.
843
 *
844
 * This upgrade routine will update access rights for Give_Worker User Role.
845
 *
846
 * @since      1.8.8
847
 */
848
function give_v188_upgrades() {
849
850
	global $wp_roles;
851
852
	// Get the role object.
853
	$give_worker = get_role( 'give_worker' );
854
855
	// A list of capabilities to add for give workers.
856
	$caps_to_add = array(
857
		'edit_posts',
858
		'edit_pages',
859
	);
860
861
	foreach ( $caps_to_add as $cap ) {
862
		// Add the capability.
863
		$give_worker->add_cap( $cap );
864
	}
865
866
}
867
868
/**
869
 * Update Post meta for minimum and maximum amount for multi level donation forms
870
 *
871
 * This upgrade routine adds post meta for give_forms CPT for multi level donation form.
872
 *
873
 * @since      1.8.9
874
 */
875
function give_v189_upgrades_levels_post_meta_callback() {
876
	/* @var Give_Updates $give_updates */
877
	$give_updates = Give_Updates::get_instance();
878
879
	// form query
880
	$donation_forms = new WP_Query( array(
881
			'paged'          => $give_updates->step,
882
			'status'         => 'any',
883
			'order'          => 'ASC',
884
			'post_type'      => 'give_forms',
885
			'posts_per_page' => 20,
886
		)
887
	);
888
889
	if ( $donation_forms->have_posts() ) {
890
		$give_updates->set_percentage( $donation_forms->found_posts, $give_updates->step * 20 );
891
892
		while ( $donation_forms->have_posts() ) {
893
			$donation_forms->the_post();
894
			$form_id = get_the_ID();
895
896
			// Remove formatting from _give_set_price
897
			update_post_meta(
898
				$form_id,
899
				'_give_set_price',
900
				give_sanitize_amount( get_post_meta( $form_id, '_give_set_price', true ) )
901
			);
902
903
			// Remove formatting from _give_custom_amount_minimum
904
			update_post_meta(
905
				$form_id,
906
				'_give_custom_amount_minimum',
907
				give_sanitize_amount( get_post_meta( $form_id, '_give_custom_amount_minimum', true ) )
908
			);
909
910
			// Bailout.
911
			if ( 'set' === get_post_meta( $form_id, '_give_price_option', true ) ) {
912
				continue;
913
			}
914
915
			$donation_levels = get_post_meta( $form_id, '_give_donation_levels', true );
916
917
			if ( ! empty( $donation_levels ) ) {
918
919
				foreach ( $donation_levels as $index => $donation_level ) {
920
					if ( isset( $donation_level['_give_amount'] ) ) {
921
						$donation_levels[ $index ]['_give_amount'] = give_sanitize_amount( $donation_level['_give_amount'] );
922
					}
923
				}
924
925
				update_post_meta( $form_id, '_give_donation_levels', $donation_levels );
926
927
				$donation_levels_amounts = wp_list_pluck( $donation_levels, '_give_amount' );
928
929
				$min_amount = min( $donation_levels_amounts );
930
				$max_amount = max( $donation_levels_amounts );
931
932
				// Set Minimum and Maximum amount for Multi Level Donation Forms
933
				give_update_meta( $form_id, '_give_levels_minimum_amount', $min_amount ? give_sanitize_amount( $min_amount ) : 0 );
934
				give_update_meta( $form_id, '_give_levels_maximum_amount', $max_amount ? give_sanitize_amount( $max_amount ) : 0 );
935
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
936
937
		}
938
939
		/* Restore original Post Data */
940
		wp_reset_postdata();
941
	} else {
942
		// The Update Ran.
943
		give_set_upgrade_complete( 'v189_upgrades_levels_post_meta' );
944
	}
945
946
}
947
948
949
/**
950
 * Give version 1.8.9 upgrades
951
 *
952
 * @since      1.8.9
953
 */
954
function give_v189_upgrades() {
955
	/**
956
	 * 1. Remove user license related notice show blocked ( Give_Notice will handle )
957
	 */
958
	global $wpdb;
959
960
	// Delete permanent notice blocker.
961
	$wpdb->query(
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
962
		$wpdb->prepare(
963
			"
964
					DELETE FROM $wpdb->usermeta
0 ignored issues
show
introduced by
Usage of users/usermeta tables is highly discouraged in VIP context, For storing user additional user metadata, you should look at User Attributes.
Loading history...
965
					WHERE meta_key
966
					LIKE '%%%s%%'
967
					",
968
			'_give_hide_license_notices_permanently'
969
		)
970
	);
971
972
	// Delete short notice blocker.
973
	$wpdb->query(
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
974
		$wpdb->prepare(
975
			"
976
					DELETE FROM $wpdb->options
977
					WHERE option_name
978
					LIKE '%%%s%%'
979
					",
980
			'__give_hide_license_notices_shortly_'
981
		)
982
	);
983
984
}
985
986
987
/**
988
 * Give version 1.8.12 update
989
 *
990
 * Standardized amount values to six decimal
991
 *
992
 * @see        https://github.com/WordImpress/Give/issues/1849#issuecomment-315128602
993
 *
994
 * @since      1.8.12
995
 */
996
function give_v1812_update_amount_values_callback() {
997
	/* @var Give_Updates $give_updates */
998
	$give_updates = Give_Updates::get_instance();
999
1000
	// form query
1001
	$donation_forms = new WP_Query( array(
1002
			'paged'          => $give_updates->step,
1003
			'status'         => 'any',
1004
			'order'          => 'ASC',
1005
			'post_type'      => array( 'give_forms', 'give_payment' ),
1006
			'posts_per_page' => 20,
1007
		)
1008
	);
1009
1010
	if ( $donation_forms->have_posts() ) {
1011
		$give_updates->set_percentage( $donation_forms->found_posts );
0 ignored issues
show
Bug introduced by
The call to set_percentage() misses a required argument $current_total.

This check looks for function calls that miss required arguments.

Loading history...
1012
1013
		while ( $donation_forms->have_posts() ) {
1014
			$donation_forms->the_post();
1015
			global $post;
1016
1017
			$meta = get_post_meta( $post->ID );
1018
1019
			switch ( $post->post_type ) {
1020
				case 'give_forms':
1021
					// _give_set_price
1022
					if( ! empty( $meta['_give_set_price'][0] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1023
						update_post_meta( $post->ID, '_give_set_price', give_sanitize_amount_for_db( $meta['_give_set_price'][0] ) );
1024
					}
1025
1026
					// _give_custom_amount_minimum
1027
					if( ! empty( $meta['_give_custom_amount_minimum'][0] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1028
						update_post_meta( $post->ID, '_give_custom_amount_minimum', give_sanitize_amount_for_db( $meta['_give_custom_amount_minimum'][0] ) );
1029
					}
1030
1031
					// _give_levels_minimum_amount
1032
					if( ! empty( $meta['_give_levels_minimum_amount'][0] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1033
						update_post_meta( $post->ID, '_give_levels_minimum_amount', give_sanitize_amount_for_db( $meta['_give_levels_minimum_amount'][0] ) );
1034
					}
1035
1036
					// _give_levels_maximum_amount
1037
					if( ! empty( $meta['_give_levels_maximum_amount'][0] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1038
						update_post_meta( $post->ID, '_give_levels_maximum_amount', give_sanitize_amount_for_db( $meta['_give_levels_maximum_amount'][0] ) );
1039
					}
1040
1041
					// _give_set_goal
1042
					if( ! empty( $meta['_give_set_goal'][0] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1043
						update_post_meta( $post->ID, '_give_set_goal', give_sanitize_amount_for_db( $meta['_give_set_goal'][0] ) );
1044
					}
1045
1046
					// _give_form_earnings
1047
					if( ! empty( $meta['_give_form_earnings'][0] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1048
						update_post_meta( $post->ID, '_give_form_earnings', give_sanitize_amount_for_db( $meta['_give_form_earnings'][0] ) );
1049
					}
1050
1051
					// _give_custom_amount_minimum
1052
					if( ! empty( $meta['_give_donation_levels'][0] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1053
						$donation_levels = unserialize( $meta['_give_donation_levels'][0] );
1054
1055
						foreach( $donation_levels as $index => $level ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1056
							if( empty( $level['_give_amount'] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1057
								continue;
1058
							}
1059
1060
							$donation_levels[$index]['_give_amount'] = give_sanitize_amount_for_db( $level['_give_amount'] );
0 ignored issues
show
introduced by
Array keys should be surrounded by spaces unless they contain a string or an integer.
Loading history...
1061
						}
1062
1063
						$meta['_give_donation_levels'] = $donation_levels;
1064
						update_post_meta( $post->ID, '_give_donation_levels', $meta['_give_donation_levels'] );
1065
					}
1066
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1067
1068
					break;
1069
1070
				case 'give_payment':
1071
					// _give_payment_total
1072
					if( ! empty( $meta['_give_payment_total'][0] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1073
						update_post_meta( $post->ID, '_give_payment_total', give_sanitize_amount_for_db( $meta['_give_payment_total'][0] ) );
1074
					}
1075
1076
					break;
1077
			}
1078
		}
1079
1080
		/* Restore original Post Data */
1081
		wp_reset_postdata();
1082
	} else {
1083
		// The Update Ran.
1084
		give_set_upgrade_complete( 'v1812_update_amount_values' );
1085
	}
1086
}
1087
1088
1089
/**
1090
 * Give version 1.8.12 update
1091
 *
1092
 * Standardized amount values to six decimal for donor
1093
 *
1094
 * @see        https://github.com/WordImpress/Give/issues/1849#issuecomment-315128602
1095
 *
1096
 * @since      1.8.12
1097
 */
1098
function give_v1812_update_donor_purchase_value_callback() {
1099
	/* @var Give_Updates $give_updates */
1100
	$give_updates = Give_Updates::get_instance();
1101
	$offset       = 1 === $give_updates->step ? 0 : $give_updates->step * 20;
1102
1103
	// form query
1104
	$donors = Give()->donors->get_donors( array(
1105
			'number' => 20,
1106
			'offset' => $offset,
1107
		)
1108
	);
1109
1110
	if ( ! empty( $donors ) ) {
1111
		$give_updates->set_percentage( Give()->donors->count() );
0 ignored issues
show
Bug introduced by
The call to set_percentage() misses a required argument $current_total.

This check looks for function calls that miss required arguments.

Loading history...
1112
1113
		/* @var Object $donor */
1114
		foreach ( $donors as $donor ) {
1115
			Give()->donors->update( $donor->id, array( 'purchase_value' => give_sanitize_amount_for_db( $donor->purchase_value ) ) );
1116
		}
1117
	} else {
1118
		// The Update Ran.
1119
		give_set_upgrade_complete( 'v1812_update_donor_purchase_values' );
1120
	}
1121
}
1122