Test Failed
Push — issues/1944 ( 3305a3...3b18f3 )
by Ravinder
05:05
created

upgrade-functions.php ➔ give_v1817_process_cleanup_user_roles()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 41
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

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

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1408
		return;
1409
	}
1410
1411
	// Add Capabilities to user roles as required.
1412
	$add_caps = array(
1413
		'administrator' => array(
1414
			'view_give_payments',
1415
		),
1416
	);
1417
1418
	// Remove Capabilities to user roles as required.
1419
	$remove_caps = array(
1420
		'give_manager' => array(
1421
			'edit_others_pages',
1422
			'edit_others_posts',
1423
			'delete_others_pages',
1424
			'delete_others_posts',
1425
			'manage_categories',
1426
			'import',
1427
			'export',
1428
		),
1429
	);
1430
1431
	foreach ( $add_caps as $role => $caps ) {
1432
		foreach ( $caps as $cap ) {
1433
			$wp_roles->add_cap( $role, $cap );
1434
		}
1435
	}
1436
1437
	foreach ( $remove_caps as $role => $caps ) {
1438
		foreach ( $caps as $cap ) {
1439
			$wp_roles->remove_cap( $role, $cap );
1440
		}
1441
	}
1442
1443
}
1444
1445
/** Upgrade Routine - Clean up of User Roles for more flexibility.
1446
 *
1447
 * @since 1.8.17
1448
 */
1449
function give_v1817_cleanup_user_roles() {
1450
	/* @var Give_Updates $give_updates */
1451
	$give_updates = Give_Updates::get_instance();
1452
1453
	give_v1817_process_cleanup_user_roles();
1454
1455
	$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...
1456
1457
	// Create Give plugin roles.
1458
	$roles = new Give_Roles();
1459
	$roles->add_roles();
1460
	$roles->add_caps();
1461
1462
	give_set_upgrade_complete( 'v1817_cleanup_user_roles' );
1463
}
1464
1465
/**
1466
 *
1467
 * Upgrade form metadata for new metabox settings.
1468
 *
1469
 * @since  2.0
1470
 * @return void
1471
 */
1472
function give_v20_upgrades_form_metadata_callback() {
1473
	$give_updates = Give_Updates::get_instance();
1474
1475
	// form query
1476
	$forms = new WP_Query( array(
1477
			'paged'          => $give_updates->step,
1478
			'status'         => 'any',
1479
			'order'          => 'ASC',
1480
			'post_type'      => 'give_forms',
1481
			'posts_per_page' => 20,
1482
		)
1483
	);
1484
1485
	if ( $forms->have_posts() ) {
1486
		$give_updates->set_percentage( $forms->found_posts, ( $give_updates->step * 20 ) );
1487
1488
		while ( $forms->have_posts() ) {
1489
			$forms->the_post();
1490
			global $post;
1491
1492
			// Update offline instruction email notification status.
1493
			$offline_instruction_notification_status = get_post_meta( get_the_ID(), '_give_customize_offline_donations', true );
1494
			$offline_instruction_notification_status = give_is_setting_enabled( $offline_instruction_notification_status, array(
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...
1495
				'enabled',
1496
				'global',
1497
			) )
1498
				? $offline_instruction_notification_status
1499
				: 'global';
1500
			update_post_meta( get_the_ID(), '_give_offline-donation-instruction_notification', $offline_instruction_notification_status );
1501
1502
			// Update offline instruction email message.
1503
			update_post_meta(
1504
				get_the_ID(),
1505
				'_give_offline-donation-instruction_email_message',
1506
				get_post_meta(
1507
					get_the_ID(),
1508
					// @todo: Delete this option later ( version > 2.0 ).
1509
					'_give_offline_donation_email',
1510
					true
1511
				)
1512
			);
1513
1514
			// Update offline instruction email subject.
1515
			update_post_meta(
1516
				get_the_ID(),
1517
				'_give_offline-donation-instruction_email_subject',
1518
				get_post_meta(
1519
					get_the_ID(),
1520
					// @todo: Delete this option later ( version > 2.0 ).
1521
					'_give_offline_donation_subject',
1522
					true
1523
				)
1524
			);
1525
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1526
1527
		}// End while().
1528
1529
		wp_reset_postdata();
1530
	} else {
1531
		// No more forms found, finish up.
1532
		give_set_upgrade_complete( 'v20_upgrades_form_metadata' );
1533
	}
1534
}
1535
1536
1537
/**
1538
 * Upgrade payment metadata for new metabox settings.
1539
 *
1540
 * @since  2.0
1541
 * @global wpdb $wpdb
1542
 * @return void
1543
 */
1544
function give_v20_upgrades_payment_metadata_callback() {
1545
	global $wpdb;
1546
	$give_updates = Give_Updates::get_instance();
1547
1548
	// form query
1549
	$forms = new WP_Query( array(
1550
			'paged'          => $give_updates->step,
1551
			'status'         => 'any',
1552
			'order'          => 'ASC',
1553
			'post_type'      => 'give_payment',
1554
			'posts_per_page' => 20,
1555
		)
1556
	);
1557
1558
	if ( $forms->have_posts() ) {
1559
		$give_updates->set_percentage( $forms->found_posts, ( $give_updates->step * 20 ) );
1560
1561
		while ( $forms->have_posts() ) {
1562
			$forms->the_post();
1563
			global $post;
1564
1565
			// Split _give_payment_meta meta.
1566
			$payment_meta = maybe_unserialize( $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wpdb->postmeta WHERE meta_key=%s", '_give_payment_meta' ) ) );
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...
1567
			if ( ! empty( $payment_meta ) ) {
1568
				_give_20_bc_split_and_save_give_payment_meta( $post->ID, maybe_unserialize( $payment_meta ) );
1569
			}
1570
1571
			$deprecated_meta_keys = array(
1572
				'_give_payment_customer_id' => '_give_payment_donor_id',
1573
				'_give_payment_user_email'  => '_give_payment_donor_email',
1574
				'_give_payment_user_ip'     => '_give_payment_donor_ip',
1575
			);
1576
1577
			foreach ( $deprecated_meta_keys as $old_meta_key => $new_meta_key ) {
1578
				// Do not add new meta key if already exist.
1579
				if ( give_get_meta( $post->ID, $new_meta_key, true ) ) {
1580
					continue;
1581
				}
1582
1583
				$meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key=%s", $old_meta_key ) );
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...
1584
				if ( ! empty( $meta_id ) ) {
1585
					$wpdb->get_var( $wpdb->prepare( "UPDATE $wpdb->postmeta SET meta_key=%s WHERE meta_id=%d", $new_meta_key, $meta_id ) );
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...
1586
				}
1587
			}
1588
1589
			// Bailout
1590
			if ( $donor_id = give_get_meta( $post->ID, '_give_payment_donor_id', true ) ) {
1591
				/* @var Give_Donor $donor */
1592
				$donor = new Give_Donor( $donor_id );
1593
1594
				$address['line1']   = give_get_meta( $post->ID, '_give_donor_billing_address1', true, '' );
0 ignored issues
show
Documentation introduced by
'' is of type string, but the function expects a boolean.

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...
1595
				$address['line2']   = give_get_meta( $post->ID, '_give_donor_billing_address2', true, '' );
0 ignored issues
show
Documentation introduced by
'' is of type string, but the function expects a boolean.

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...
1596
				$address['city']    = give_get_meta( $post->ID, '_give_donor_billing_city', true, '' );
0 ignored issues
show
Documentation introduced by
'' is of type string, but the function expects a boolean.

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...
1597
				$address['state']   = give_get_meta( $post->ID, '_give_donor_billing_state', true, '' );
0 ignored issues
show
Documentation introduced by
'' is of type string, but the function expects a boolean.

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...
1598
				$address['zip']     = give_get_meta( $post->ID, '_give_donor_billing_zip', true, '' );
0 ignored issues
show
Documentation introduced by
'' is of type string, but the function expects a boolean.

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...
1599
				$address['country'] = give_get_meta( $post->ID, '_give_donor_billing_country', true, '' );
0 ignored issues
show
Documentation introduced by
'' is of type string, but the function expects a boolean.

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...
1600
1601
				// Save address.
1602
				$donor->add_address( 'billing[]', $address );
1603
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1604
1605
		}// End while().
1606
1607
		wp_reset_postdata();
1608
	} else {
1609
		// Delete user id meta.
1610
		$wpdb->get_var( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE meta_key=%s", '_give_payment_user_id' ) );
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...
1611
1612
		// No more forms found, finish up.
1613
		give_set_upgrade_complete( 'v20_upgrades_payment_metadata' );
1614
	}
1615
}
1616
1617
1618
/**
1619
 * Upgrade logs data.
1620
 *
1621
 * @todo   : check if payment price id is necessary to store in log meta or not
1622
 *
1623
 * @since  2.0
1624
 * @return void
1625
 */
1626
function give_v20_logs_upgrades_callback() {
1627
	global $wpdb;
1628
	$give_updates = Give_Updates::get_instance();
1629
1630
	// form query
1631
	$forms = new WP_Query( array(
1632
			'paged'          => $give_updates->step,
1633
			'order'          => 'DESC',
1634
			'post_type'      => 'give_log',
1635
			'post_status'    => 'any',
1636
			'posts_per_page' => 20,
1637
		)
1638
	);
1639
1640
	if ( $forms->have_posts() ) {
1641
		$give_updates->set_percentage( $forms->found_posts, $give_updates->step * 20 );
1642
1643
		while ( $forms->have_posts() ) {
1644
			$forms->the_post();
1645
			global $post;
1646
			$term      = get_the_terms( $post->ID, 'give_log_type' );
1647
			$term      = ! is_wp_error( $term ) && ! empty( $term ) ? $term[0] : array();
1648
			$term_name = ! empty( $term ) ? $term->slug : '';
1649
1650
			$log_data = array(
1651
				'ID'           => $post->ID,
1652
				'log_title'    => $post->post_title,
1653
				'log_content'  => $post->post_content,
1654
				'log_parent'   => 0,
1655
				'log_type'     => $term_name,
1656
				'log_date'     => $post->post_date,
1657
				'log_date_gmt' => $post->post_date_gmt,
1658
			);
1659
			$log_meta = array();
1660
1661
			if ( $old_log_meta = get_post_meta( $post->ID ) ) {
1662
				foreach ( $old_log_meta as $meta_key => $meta_value ) {
1663
					switch ( $meta_key ) {
1664
						case '_give_log_payment_id':
1665
							$log_data['log_parent']        = current( $meta_value );
1666
							$log_meta['_give_log_form_id'] = $post->post_parent;
1667
							break;
1668
1669
						default:
1670
							$log_meta[ $meta_key ] = current( $meta_value );
1671
					}
1672
				}
1673
			}
1674
1675
			if ( 'api_request' === $term_name ) {
1676
				$log_meta['_give_log_api_query'] = $post->post_excerpt;
1677
			}
1678
1679
			$wpdb->insert( "{$wpdb->prefix}give_logs", $log_data );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
1680
1681
			if ( ! empty( $log_meta ) ) {
1682
				foreach ( $log_meta as $meta_key => $meta_value ) {
1683
					Give()->logs->logmeta_db->update_meta( $post->ID, $meta_key, $meta_value );
1684
				}
1685
			}
1686
1687
			$logIDs[] = $post->ID;
1688
		}// End while().
1689
1690
		wp_reset_postdata();
1691
	} else {
1692
		// Delete terms and taxonomy.
1693
		$terms = get_terms( 'give_log_type', array( 'fields' => 'ids', 'hide_empty' => false ) );
1694
		if ( ! empty( $terms ) ) {
1695
			foreach ( $terms as $term ) {
1696
				wp_delete_term( $term, 'give_log_type' );
1697
			}
1698
		}
1699
1700
		// Delete logs.
1701
		$logIDs = get_posts( array(
1702
				'order'          => 'DESC',
1703
				'post_type'      => 'give_log',
1704
				'post_status'    => 'any',
1705
				'posts_per_page' => - 1,
1706
				'fields'         => 'ids',
1707
			)
1708
		);
1709
1710
		if ( ! empty( $logIDs ) ) {
1711
			foreach ( $logIDs as $log ) {
1712
				// Delete term relationship and posts.
1713
				wp_delete_object_term_relationships( $log, 'give_log_type' );
1714
				wp_delete_post( $log, true );
1715
			}
1716
		}
1717
1718
		unregister_taxonomy( 'give_log_type' );
1719
1720
		// Delete log cache.
1721
		Give()->logs->delete_cache();
1722
1723
		// No more forms found, finish up.
1724
		give_set_upgrade_complete( 'v20_logs_upgrades' );
1725
	}
1726
}
1727
1728
1729
/**
1730
 * Move payment and form metadata to new table
1731
 *
1732
 * @since  2.0
1733
 * @return void
1734
 */
1735
function give_v20_move_metadata_into_new_table_callback() {
1736
	global $wpdb;
1737
	$give_updates = Give_Updates::get_instance();
1738
1739
	// form query
1740
	$payments = new WP_Query( array(
1741
			'paged'          => $give_updates->step,
1742
			'status'         => 'any',
1743
			'order'          => 'ASC',
1744
			'post_type'      => array( 'give_forms', 'give_payment' ),
1745
			'posts_per_page' => 20,
1746
		)
1747
	);
1748
1749
	if ( $payments->have_posts() ) {
1750
		$give_updates->set_percentage( $payments->found_posts, $give_updates->step * 20 );
1751
1752
		while ( $payments->have_posts() ) {
1753
			$payments->the_post();
1754
			global $post;
1755
1756
			$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...
1757
				$wpdb->prepare(
1758
					"SELECT * FROM $wpdb->postmeta where post_id=%d",
1759
					get_the_ID()
1760
				),
1761
				ARRAY_A
1762
			);
1763
1764
			if ( ! empty( $meta_data ) ) {
1765
				foreach ( $meta_data as $index => $data ) {
1766
					switch ( $post->post_type ) {
1767 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...
1768
							$data['form_id'] = $data['post_id'];
1769
							unset( $data['post_id'] );
1770
1771
							Give()->form_meta->insert( $data );
1772
							delete_post_meta( get_the_ID(), $data['meta_key'] );
1773
1774
							break;
1775
1776 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...
1777
							$data['payment_id'] = $data['post_id'];
1778
							unset( $data['post_id'] );
1779
1780
							Give()->payment_meta->insert( $data );
1781
							delete_post_meta( get_the_ID(), $data['meta_key'] );
1782
1783
							break;
1784
					}
1785
				}
1786
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1787
1788
		}// End while().
1789
1790
		wp_reset_postdata();
1791
	} else {
1792
		// No more forms found, finish up.
1793
		give_set_upgrade_complete( 'v20_move_metadata_into_new_table' );
1794
	}
1795
1796
}
1797
1798
/**
1799
 * Upgrade routine for splitting donor name into first name and last name.
1800
 *
1801
 * @since 2.0
1802
 *
1803
 * @return void
1804
 */
1805
function give_v20_upgrades_donor_name() {
1806
	/* @var Give_Updates $give_updates */
1807
	$give_updates = Give_Updates::get_instance();
1808
1809
	$args = array(
1810
		'offset' => ( 1 === $give_updates->step ) ? 0 : $give_updates->step * 20,
1811
	);
1812
1813
	$donors = Give()->donors->get_donors( $args );
1814
1815
	if ( $donors ) {
1816
		$give_updates->set_percentage( count( $donors ), $give_updates->step * 20 );
1817
		// Loop through Donors
1818
		foreach ( $donors as $donor ) {
1819
1820
			$donor_name       = explode( ' ', $donor->name, 2 );
1821
			$donor_first_name = Give()->donor_meta->get_meta( $donor->id, '_give_donor_first_name' );
1822
			$donor_last_name  = Give()->donor_meta->get_meta( $donor->id, '_give_donor_last_name' );
1823
1824
			// If first name meta of donor is not created, then create it.
1825
			if ( ! $donor_first_name ) {
1826
				Give()->donor_meta->add_meta( $donor->id, '_give_donor_first_name', $donor_name[0] );
1827
			}
1828
1829
			// If last name meta of donor is not created, then create it.
1830
			if ( ! $donor_last_name ) {
1831
				Give()->donor_meta->add_meta( $donor->id, '_give_donor_last_name', $donor_name[1] );
1832
			}
1833
1834
			// If Donor is connected with WP User then update user meta.
1835
			if ( $donor->user_id ) {
1836
				update_user_meta( $donor->user_id, 'first_name', $donor_name[0] );
0 ignored issues
show
introduced by
update_user_meta() usage is highly discouraged, check VIP documentation on "Working with wp_users"
Loading history...
1837
				update_user_meta( $donor->user_id, 'last_name', $donor_name[1] );
0 ignored issues
show
introduced by
update_user_meta() usage is highly discouraged, check VIP documentation on "Working with wp_users"
Loading history...
1838
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1839
1840
		}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1841
1842
	} else {
1843
		// The Update Ran.
1844
		give_set_upgrade_complete( 'v20_upgrades_donor_name' );
1845
	}
1846
1847
}
1848
1849
/**
1850
 * Upgrade routine for user addresses.
1851
 *
1852
 * @since 2.0
1853
 * @global wpdb $wpdb
1854
 *
1855
 * @return void
1856
 */
1857
function give_v20_upgrades_user_address() {
1858
	global $wpdb;
1859
1860
	/* @var Give_Updates $give_updates */
1861
	$give_updates = Give_Updates::get_instance();
1862
1863
	/* @var WP_User_Query $user_query */
1864
	$user_query = new WP_User_Query(
1865
		array(
1866
			'number' => 20,
1867
			'offset' => ( 1 === $give_updates->step ) ? 0 : $give_updates->step * 20,
1868
		)
1869
	);
1870
1871
	$users = $user_query->get_results();
1872
1873
	if ( $users ) {
1874
		$give_updates->set_percentage( $user_query->get_total(), $give_updates->step * 20 );
1875
1876
		// Loop through Donors
1877
		foreach ( $users as $user ) {
1878
			/* @var Give_Donor $donor */
1879
			$donor = new Give_Donor( $user->ID, true );
1880
1881
			if ( ! $donor->id ) {
1882
				continue;
1883
			}
1884
1885
			$address = $wpdb->get_var(
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...
1886
				$wpdb->prepare(
1887
					"
1888
					SELECT meta_value 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...
1889
					WHERE user_id=%s
1890
					AND meta_key=%s
1891
					",
1892
					$user->ID,
1893
					'_give_user_address'
1894
				)
1895
			);
1896
1897
			if ( ! empty( $address ) ) {
1898
				$address = maybe_unserialize( $address );
1899
				$donor->add_address( 'personal', $address );
1900
				$donor->add_address( 'billing[]', $address );
1901
				delete_user_meta( $user->ID, '_give_user_address' );
0 ignored issues
show
introduced by
delete_user_meta() usage is highly discouraged, check VIP documentation on "Working with wp_users"
Loading history...
1902
			}
1903
		}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1904
1905
	} else {
1906
		// The Update Ran.
1907
		give_set_upgrade_complete( 'v20_upgrades_user_address' );
1908
	}
1909
1910
}
1911
1912
/**
1913
 * Upgrade logs data.
1914
 *
1915
 * @since  2.0
1916
 * @global wpdb $wpdb
1917
 * @return void
1918
 */
1919
function give_v20_rename_donor_tables_callback() {
1920
	global $wpdb;
1921
1922
	/* @var Give_Updates $give_updates */
1923
	$give_updates = Give_Updates::get_instance();
1924
1925
	$tables = array(
1926
		"{$wpdb->prefix}give_customers"    => "{$wpdb->prefix}give_donors",
1927
		"{$wpdb->prefix}give_customermeta" => "{$wpdb->prefix}give_donormeta",
1928
	);
1929
1930
	// Alter customer table
1931
	foreach ( $tables as $old_table => $new_table ) {
1932
		if (
1933
			$wpdb->query( $wpdb->prepare( "SHOW TABLES LIKE %s", $old_table ) ) &&
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...
Coding Style Comprehensibility introduced by
The string literal SHOW TABLES LIKE %s does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
1934
			! $wpdb->query( $wpdb->prepare( "SHOW TABLES LIKE %s", $new_table ) )
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...
Coding Style Comprehensibility introduced by
The string literal SHOW TABLES LIKE %s does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
1935
		) {
1936
			$wpdb->query( "ALTER TABLE {$old_table} RENAME TO {$new_table}" );
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...
introduced by
Attempting a database schema change is highly discouraged.
Loading history...
1937
1938
			if ( "{$wpdb->prefix}give_donormeta" === $new_table ) {
1939
				$wpdb->query( "ALTER TABLE {$new_table} CHANGE COLUMN customer_id donor_id bigint(20)" );
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...
introduced by
Attempting a database schema change is highly discouraged.
Loading history...
1940
			}
1941
		}
1942
	}
1943
1944
	$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...
1945
1946
	// No more forms found, finish up.
1947
	give_set_upgrade_complete( 'v20_rename_donor_tables' );
1948
1949
	// Re initiate donor classes.
1950
	Give()->donors     = new Give_DB_Donors();
1951
	Give()->donor_meta = new Give_DB_Donor_Meta();
1952
}