Test Failed
Push — issues/2042 ( e8b6b5 )
by Ravinder
05:59
created

upgrade-functions.php ➔ give_do_automatic_upgrades()   C

Complexity

Conditions 11
Paths 36

Size

Total Lines 49
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 32
nc 36
nop 0
dl 0
loc 49
rs 5.2653
c 0
b 0
f 0

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