Test Failed
Push — feature/meta-tables ( 00f89f )
by Ravinder
05:15
created

upgrade-functions.php ➔ give_do_automatic_upgrades()   C

Complexity

Conditions 11
Paths 36

Size

Total Lines 48
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

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

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
996
				give_delete_option( $old_setting );
997
				break;
998
999
			// @todo: Delete this option later ( version > 2.0 ) because we need this for backward compatibility give_get_admin_notice_emails.
1000
			case 'admin_notice_emails':
1001
				$recipients = give_get_admin_notice_emails();
0 ignored issues
show
Deprecated Code introduced by
The function give_get_admin_notice_emails() has been deprecated with message: 2.0

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
1002
1003
				foreach ( $new_setting as $setting ) {
0 ignored issues
show
Bug introduced by
The expression $new_setting of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1004
					// bailout if setting already exist.
1005
					if ( array_key_exists( $setting, $all_setting ) ) {
1006
						continue;
1007
					}
1008
1009
					give_update_option( $setting, $recipients );
1010
				}
1011
				break;
1012
1013
			default:
1014
				give_update_option( $new_setting, give_get_option( $old_setting ) );
0 ignored issues
show
Bug introduced by
It seems like $new_setting defined by $new_setting on line 983 can also be of type array; however, give_update_option() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1015
				give_delete_option( $old_setting );
1016
		}
1017
	}
1018
}
1019
1020
1021
/**
1022
 * Give version 1.8.9 upgrades
1023
 *
1024
 * @since      1.8.9
1025
 */
1026
function give_v1812_upgrades() {
1027
	/**
1028
	 * Validate number format settings.
1029
	 */
1030
	$give_settings        = give_get_settings();
1031
	$give_setting_updated = false;
1032
1033
	if ( $give_settings['thousands_separator'] === $give_settings['decimal_separator'] ) {
1034
		$give_settings['number_decimals']   = 0;
1035
		$give_settings['decimal_separator'] = '';
1036
		$give_setting_updated               = true;
1037
1038
	} elseif ( empty( $give_settings['decimal_separator'] ) ) {
1039
		$give_settings['number_decimals'] = 0;
1040
		$give_setting_updated             = true;
1041
1042
	} elseif ( 6 < absint( $give_settings['number_decimals'] ) ) {
1043
		$give_settings['number_decimals'] = 5;
1044
		$give_setting_updated             = true;
1045
	}
1046
1047
	if ( $give_setting_updated ) {
1048
		update_option( 'give_settings', $give_settings );
1049
	}
1050
}
1051
1052
1053
/**
1054
 * Give version 1.8.12 update
1055
 *
1056
 * Standardized amount values to six decimal
1057
 *
1058
 * @see        https://github.com/WordImpress/Give/issues/1849#issuecomment-315128602
1059
 *
1060
 * @since      1.8.12
1061
 */
1062
function give_v1812_update_amount_values_callback() {
1063
	/* @var Give_Updates $give_updates */
1064
	$give_updates = Give_Updates::get_instance();
1065
1066
	// form query
1067
	$donation_forms = new WP_Query( array(
1068
			'paged'          => $give_updates->step,
1069
			'status'         => 'any',
1070
			'order'          => 'ASC',
1071
			'post_type'      => array( 'give_forms', 'give_payment' ),
1072
			'posts_per_page' => 20,
1073
		)
1074
	);
1075
	if ( $donation_forms->have_posts() ) {
1076
		$give_updates->set_percentage( $donation_forms->found_posts, ( $give_updates->step * 20 ) );
1077
1078
		while ( $donation_forms->have_posts() ) {
1079
			$donation_forms->the_post();
1080
			global $post;
1081
1082
			$meta = get_post_meta( $post->ID );
1083
1084
			switch ( $post->post_type ) {
1085
				case 'give_forms':
1086
					// _give_set_price
1087
					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...
1088
						update_post_meta( $post->ID, '_give_set_price', give_sanitize_amount_for_db( $meta['_give_set_price'][0] ) );
1089
					}
1090
1091
					// _give_custom_amount_minimum
1092
					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...
1093
						update_post_meta( $post->ID, '_give_custom_amount_minimum', give_sanitize_amount_for_db( $meta['_give_custom_amount_minimum'][0] ) );
1094
					}
1095
1096
					// _give_levels_minimum_amount
1097
					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...
1098
						update_post_meta( $post->ID, '_give_levels_minimum_amount', give_sanitize_amount_for_db( $meta['_give_levels_minimum_amount'][0] ) );
1099
					}
1100
1101
					// _give_levels_maximum_amount
1102
					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...
1103
						update_post_meta( $post->ID, '_give_levels_maximum_amount', give_sanitize_amount_for_db( $meta['_give_levels_maximum_amount'][0] ) );
1104
					}
1105
1106
					// _give_set_goal
1107
					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...
1108
						update_post_meta( $post->ID, '_give_set_goal', give_sanitize_amount_for_db( $meta['_give_set_goal'][0] ) );
1109
					}
1110
1111
					// _give_form_earnings
1112
					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...
1113
						update_post_meta( $post->ID, '_give_form_earnings', give_sanitize_amount_for_db( $meta['_give_form_earnings'][0] ) );
1114
					}
1115
1116
					// _give_custom_amount_minimum
1117
					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...
1118
						$donation_levels = unserialize( $meta['_give_donation_levels'][0] );
1119
1120
						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...
1121
							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...
1122
								continue;
1123
							}
1124
1125
							$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...
1126
						}
1127
1128
						$meta['_give_donation_levels'] = $donation_levels;
1129
						update_post_meta( $post->ID, '_give_donation_levels', $meta['_give_donation_levels'] );
1130
					}
1131
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1132
1133
					break;
1134
1135
				case 'give_payment':
1136
					// _give_payment_total
1137
					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...
1138
						update_post_meta( $post->ID, '_give_payment_total', give_sanitize_amount_for_db( $meta['_give_payment_total'][0] ) );
1139
					}
1140
1141
					break;
1142
			}
1143
		}
1144
1145
		/* Restore original Post Data */
1146
		wp_reset_postdata();
1147
	} else {
1148
		// The Update Ran.
1149
		give_set_upgrade_complete( 'v1812_update_amount_values' );
1150
	}
1151
}
1152
1153
1154
/**
1155
 * Give version 1.8.12 update
1156
 *
1157
 * Standardized amount values to six decimal for donor
1158
 *
1159
 * @see        https://github.com/WordImpress/Give/issues/1849#issuecomment-315128602
1160
 *
1161
 * @since      1.8.12
1162
 */
1163
function give_v1812_update_donor_purchase_value_callback() {
1164
	/* @var Give_Updates $give_updates */
1165
	$give_updates = Give_Updates::get_instance();
1166
	$offset       = 1 === $give_updates->step ? 0 : $give_updates->step * 20;
1167
1168
	// form query
1169
	$donors = Give()->donors->get_donors( array(
1170
			'number' => 20,
1171
			'offset' => $offset,
1172
		)
1173
	);
1174
1175
	if ( ! empty( $donors ) ) {
1176
		$give_updates->set_percentage( Give()->donors->count(), $offset );
1177
1178
		/* @var Object $donor */
1179
		foreach ( $donors as $donor ) {
1180
			Give()->donors->update( $donor->id, array( 'purchase_value' => give_sanitize_amount_for_db( $donor->purchase_value ) ) );
1181
		}
1182
	} else {
1183
		// The Update Ran.
1184
		give_set_upgrade_complete( 'v1812_update_donor_purchase_values' );
1185
	}
1186
}
1187
1188
/**
1189
 * Upgrade form metadata for new metabox settings.
1190
 *
1191
 * @since  2.0
1192
 * @return void
1193
 */
1194
function give_v20_upgrades_form_metadata_callback() {
1195
	$give_updates = Give_Updates::get_instance();
1196
1197
	// form query
1198
	$forms = new WP_Query( array(
1199
			'paged'          => $give_updates->step,
1200
			'status'         => 'any',
1201
			'order'          => 'ASC',
1202
			'post_type'      => 'give_forms',
1203
			'posts_per_page' => 20,
1204
		)
1205
	);
1206
1207
	if ( $forms->have_posts() ) {
1208
		$give_updates->set_percentage( $forms->found_posts, ( $give_updates->step * 20 ) );
1209
1210
		while ( $forms->have_posts() ) {
1211
			$forms->the_post();
1212
1213
			// Update offline instruction email notification status.
1214
			$offline_instruction_notification_status = get_post_meta( get_the_ID(), '_give_customize_offline_donations', true );
1215
			$offline_instruction_notification_status = give_is_setting_enabled( $offline_instruction_notification_status, array( 'enabled', 'global' ) )
0 ignored issues
show
Documentation introduced by
array('enabled', 'global') is of type array<integer,string,{"0":"string","1":"string"}>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1216
				? $offline_instruction_notification_status
1217
				: 'global';
1218
			update_post_meta( get_the_ID(), '_give_offline-donation-instruction_notification', $offline_instruction_notification_status );
1219
1220
			// Update offline instruction email message.
1221
			update_post_meta(
1222
				get_the_ID(),
1223
				'_give_offline-donation-instruction_email_message',
1224
				get_post_meta(
1225
					get_the_ID(),
1226
					// @todo: Delete this option later ( version > 2.0 ).
1227
					'_give_offline_donation_email',
1228
					true
1229
				)
1230
			);
1231
1232
			// Update offline instruction email subject.
1233
			update_post_meta(
1234
				get_the_ID(),
1235
				'_give_offline-donation-instruction_email_subject',
1236
				get_post_meta(
1237
					get_the_ID(),
1238
					// @todo: Delete this option later ( version > 2.0 ).
1239
					'_give_offline_donation_subject',
1240
					true
1241
				)
1242
			);
1243
1244
			// @todo add db upgrade for _give_payment_meta,_give_payment_customer_id, _give_payment_user_email, _give_payment_user_ip.
1245
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1246
1247
		}// End while().
1248
1249
		wp_reset_postdata();
1250
	} else {
1251
		// No more forms found, finish up.
1252
		give_set_upgrade_complete( 'v20_upgrades_form_metadata' );
1253
	}
1254
1255
	//  delete _give_payment_user_id now we are getting user id from donor id.
1256
}
1257
1258
1259
/**
1260
 * Upgrade logs data.
1261
 *
1262
 * @since  2.0
1263
 * @return void
1264
 */
1265
function give_v20_logs_upgrades_callback() {
1266
	global $wpdb;
1267
	$give_updates = Give_Updates::get_instance();
1268
1269
	// form query
1270
	$forms = new WP_Query( array(
1271
			'paged'          => $give_updates->step,
1272
			'order'          => 'DESC',
1273
			'post_type'      => 'give_log',
1274
			'post_status'    => 'any',
1275
			'posts_per_page' => 20,
1276
		)
1277
	);
1278
1279
	if ( $forms->have_posts() ) {
1280
		$give_updates->set_percentage( $forms->found_posts, $give_updates->step * 20 );
1281
1282
		while ( $forms->have_posts() ) {
1283
			$forms->the_post();
1284
			global $post;
1285
			$term = get_the_terms( $post->ID, 'give_log_type' );
1286
			$term = ! is_wp_error( $term ) && ! empty( $term ) ? $term[0] : array();
1287
			$term_name = ! empty( $term )? $term->slug : '';
1288
1289
			$log_data = array(
1290
				'ID'           => $post->ID,
1291
				'log_title'    => $post->post_title,
1292
				'log_content'  => $post->post_content,
1293
				'log_parent'   => 0,
1294
				'log_type'     => $term_name,
1295
				'log_date'     => $post->post_date,
1296
				'log_date_gmt' => $post->post_date_gmt,
1297
			);
1298
			$log_meta = array();
1299
1300
			if( $old_log_meta = get_post_meta( $post->ID ) ) {
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...
1301
				foreach ( $old_log_meta as $meta_key => $meta_value ) {
1302
					switch ( $meta_key ) {
1303
						case '_give_log_payment_id':
1304
							$log_data['log_parent'] = current( $meta_value );
1305
							$log_meta['_give_log_form_id'] = $post->post_parent;
1306
							break;
1307
1308
						default:
1309
							$log_meta[$meta_key] = current(  $meta_value );
0 ignored issues
show
introduced by
Array keys should be surrounded by spaces unless they contain a string or an integer.
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 2 found
Loading history...
1310
					}
1311
				}
1312
			}
1313
1314
			if( 'api_request' === $term_name ){
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...
1315
				$log_meta['_give_log_api_query'] = $post->post_excerpt;
1316
			}
1317
1318
			$wpdb->insert( "{$wpdb->prefix}give_logs", $log_data );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
1319
1320
			if( ! empty( $log_meta ) ) {
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...
1321
				foreach ( $log_meta as $meta_key => $meta_value ){
1322
					Give()->logs->logmeta_db->update_meta( $post->ID, $meta_key, $meta_value );
1323
				}
1324
			}
1325
1326
			$logIDs[] = $post->ID;
1327
		}// End while().
1328
1329
		wp_reset_postdata();
1330
	} else {
1331
		// Delete terms and taxonomy.
1332
		$terms = get_terms( 'give_log_type', array( 'fields' => 'ids', 'hide_empty' => false ) );
1333
		if( ! empty( $terms ) ) {
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...
1334
			foreach ( $terms as $term ) {
1335
				wp_delete_term( $term, 'give_log_type' );
1336
			}
1337
		}
1338
1339
		// Delete logs
1340
		$logIDs = get_posts( array(
1341
				'order'          => 'DESC',
1342
				'post_type'      => 'give_log',
1343
				'post_status'    => 'any',
1344
				'posts_per_page' => - 1,
1345
				'fields'         => 'ids',
1346
			)
1347
		);
1348
1349
		if ( ! empty( $logIDs ) ) {
1350
			foreach ( $logIDs as $log ) {
1351
				// Delete term relationship and posts.
1352
				wp_delete_object_term_relationships( $log, 'give_log_type' );
1353
				wp_delete_post( $log, true );
1354
			}
1355
		}
1356
1357
		unregister_taxonomy( 'give_log_type' );
1358
1359
		// Delete log cache.
1360
		Give()->logs->delete_cache();
1361
1362
		// No more forms found, finish up.
1363
		give_set_upgrade_complete( 'v20_logs_upgrades' );
1364
	}
1365
}
1366
1367
/**
1368
 * Move payment and form metadata to new table
1369
 *
1370
 * @since  2.0
1371
 * @return void
1372
 */
1373
function give_v20_move_metadata_into_new_table_callback() {
1374
	global $wpdb;
1375
	$give_updates = Give_Updates::get_instance();
1376
1377
	// form query
1378
	$payments = new WP_Query( array(
1379
			'paged'          => $give_updates->step,
1380
			'status'         => 'any',
1381
			'order'          => 'ASC',
1382
			'post_type'      => array( 'give_forms', 'give_payment' ),
1383
			'posts_per_page' => 20,
1384
		)
1385
	);
1386
1387
	if ( $payments->have_posts() ) {
1388
		$give_updates->set_percentage( $payments->found_posts, $give_updates->step * 20 );
1389
1390
		while ( $payments->have_posts() ) {
1391
			$payments->the_post();
1392
			$meta_data = $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...
1393
				$wpdb->prepare(
1394
					"SELECT * FROM $wpdb->postmeta where post_id=%d",
1395
					get_the_ID()
1396
				),
1397
				ARRAY_A
1398
			);
1399
1400
			if ( ! empty( $meta_data ) ) {
1401
				foreach ( $meta_data as $index => $data ) {
1402
					switch ( get_post_type( get_the_ID() ) ) {
1403 View Code Duplication
						case 'give_forms':
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...
1404
							$data['form_id'] = $data['post_id'];
1405
							unset( $data['post_id'] );
1406
1407
							Give()->form_meta->insert( $data );
1408
							delete_post_meta( get_the_ID(), $data['meta_key'] );
1409
1410
							break;
1411
1412 View Code Duplication
						case 'give_payment':
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...
1413
							$data['payment_id'] = $data['post_id'];
1414
							unset( $data['post_id'] );
1415
1416
							Give()->payment_meta->insert( $data );
1417
							delete_post_meta( get_the_ID(), $data['meta_key'] );
1418
1419
							break;
1420
					}
1421
				}
1422
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1423
1424
		}// End while().
1425
1426
		wp_reset_postdata();
1427
	} else {
1428
		// No more forms found, finish up.
1429
		give_set_upgrade_complete( 'v20_move_metadata_into_new_table' );
1430
	}
1431
}
1432
1433