Test Failed
Push — issues/370 ( 51cc5e...d56982 )
by Ravinder
05:20
created

upgrade-functions.php ➔ give_v20_upgrades_user_address()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 54
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 27
nc 5
nop 0
dl 0
loc 54
rs 8.7449
c 0
b 0
f 0

How to fix   Long Method   

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
 * Perform automatic database upgrades when necessary.
21
 *
22
 * @since  1.6
23
 * @return void
24
 */
25
function give_do_automatic_upgrades() {
26
	$did_upgrade  = false;
27
	$give_version = preg_replace( '/[^0-9.].*/', '', get_option( 'give_version' ) );
28
29
	if ( ! $give_version ) {
30
		// 1.0 is the first version to use this option so we must add it.
31
		$give_version = '1.0';
32
	}
33
34
	switch ( true ) {
35
36
		case version_compare( $give_version, '1.6', '<' ) :
37
			give_v16_upgrades();
38
			$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...
39
40
		case version_compare( $give_version, '1.7', '<' ) :
41
			give_v17_upgrades();
42
			$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...
43
44
		case version_compare( $give_version, '1.8', '<' ) :
45
			give_v18_upgrades();
46
			$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...
47
48
		case version_compare( $give_version, '1.8.7', '<' ) :
49
			give_v187_upgrades();
50
			$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...
51
52
		case version_compare( $give_version, '1.8.8', '<' ) :
53
			give_v188_upgrades();
54
			$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...
55
56
		case version_compare( $give_version, '1.8.9', '<' ) :
57
			give_v189_upgrades();
58
			$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...
59
60
		case version_compare( $give_version, '1.8.12', '<' ) :
61
			give_v1812_upgrades();
62
			$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...
63
64
		case version_compare( $give_version, '1.8.13', '<' ) :
65
			give_v1813_upgrades();
66
			$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...
67
68
		case version_compare( $give_version, '2.0', '<' ) :
69
			give_v20_upgrades();
70
			$did_upgrade = true;
71
	}
72
73
	if ( $did_upgrade ) {
74
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
75
	}
76
}
77
78
add_action( 'admin_init', 'give_do_automatic_upgrades' );
79
add_action( 'give_upgrades', 'give_do_automatic_upgrades' );
80
81
/**
82
 * Display Upgrade Notices
83
 *
84
 * @since 1.0
85
 * @since 1.8.12 Update new update process code.
86
 *
87
 * @param Give_Updates $give_updates
88
 *
89
 * @return void
90
 */
91
function give_show_upgrade_notices( $give_updates ) {
92
	// v1.3.2 Upgrades
93
	$give_updates->register(
94
		array(
95
			'id'       => 'upgrade_give_payment_customer_id',
96
			'version'  => '1.3.2',
97
			'callback' => 'give_v132_upgrade_give_payment_customer_id',
98
		)
99
	);
100
101
	// v1.3.4 Upgrades ensure the user has gone through 1.3.4.
102
	$give_updates->register(
103
		array(
104
			'id'       => 'upgrade_give_offline_status',
105
			'depend'   => 'upgrade_give_payment_customer_id',
106
			'version'  => '1.3.4',
107
			'callback' => 'give_v134_upgrade_give_offline_status',
108
		)
109
	);
110
111
	// v1.8 form metadata upgrades.
112
	$give_updates->register(
113
		array(
114
			'id'       => 'v18_upgrades_form_metadata',
115
			'version'  => '1.8',
116
			'callback' => 'give_v18_upgrades_form_metadata',
117
		)
118
	);
119
120
	// v1.8.9 Upgrades
121
	$give_updates->register(
122
		array(
123
			'id'       => 'v189_upgrades_levels_post_meta',
124
			'version'  => '1.8.9',
125
			'callback' => 'give_v189_upgrades_levels_post_meta_callback',
126
		)
127
	);
128
129
	// v1.8.12 Upgrades
130
	$give_updates->register(
131
		array(
132
			'id'       => 'v1812_update_amount_values',
133
			'version'  => '1.8.12',
134
			'callback' => 'give_v1812_update_amount_values_callback',
135
		)
136
	);
137
138
	// v1.8.12 Upgrades
139
	$give_updates->register(
140
		array(
141
			'id'       => 'v1812_update_donor_purchase_values',
142
			'version'  => '1.8.12',
143
			'callback' => 'give_v1812_update_donor_purchase_value_callback',
144
		)
145
	);
146
147
	// v1.8.13 Upgrades for donor
148
	$give_updates->register(
149
		array(
150
			'id'       => 'v1813_update_donor_user_roles',
151
			'version'  => '1.8.13',
152
			'callback' => 'give_v1813_update_donor_user_roles_callback',
153
		)
154
	);
155
156
	// v2.0.0 Upgrades
157
	$give_updates->register(
158
		array(
159
			'id'       => 'v20_upgrades_form_metadata',
160
			'version'  => '2.0.0',
161
			'callback' => 'give_v20_upgrades_form_metadata_callback',
162
		)
163
	);
164
165
	// v2.0.0 User Address Upgrades
166
	$give_updates->register(
167
		array(
168
			'id'       => 'v20_upgrades_user_address',
169
			'version'  => '2.0.0',
170
			'callback' => 'give_v20_upgrades_user_address',
171
		)
172
	);
173
174
	// v2.0.0 Upgrades
175
	$give_updates->register(
176
		array(
177
			'id'       => 'v20_upgrades_payment_metadata',
178
			'version'  => '2.0.0',
179
			'callback' => 'give_v20_upgrades_payment_metadata_callback',
180
		)
181
	);
182
183
	// v2.0.0 Upgrades
184
	$give_updates->register(
185
		array(
186
			'id'       => 'v20_logs_upgrades',
187
			'version'  => '2.0.0',
188
			'callback' => 'give_v20_logs_upgrades_callback',
189
190
		)
191
	);
192
193
	// v2.0.0 Upgrades
194
	$give_updates->register(
195
		array(
196
			'id'       => 'v20_move_metadata_into_new_table',
197
			'version'  => '2.0.0',
198
			'callback' => 'give_v20_move_metadata_into_new_table_callback',
199
			'depend'   => array( 'v20_upgrades_payment_metadata', 'v20_upgrades_form_metadata' ),
200
		)
201
	);
202
203
	// v2.0.0 Donor Name Upgrades
204
	$give_updates->register(
205
		array(
206
			'id'       => 'v20_upgrades_donor_name',
207
			'version'  => '2.0.0',
208
			'callback' => 'give_v20_upgrades_donor_name',
209
		)
210
	);
211
212
	// v2.0.0 Upgrades
213
	$give_updates->register(
214
		array(
215
			'id'       => 'v20_rename_donor_tables',
216
			'version'  => '2.0.0',
217
			'callback' => 'give_v20_rename_donor_tables_callback',
218
			'depend'   => array(
219
				'v20_move_metadata_into_new_table',
220
				'v20_logs_upgrades',
221
				'v20_upgrades_form_metadata',
222
				'v20_upgrades_payment_metadata',
223
				'v20_upgrades_user_address'
0 ignored issues
show
introduced by
Comma required after last value in array declaration
Loading history...
224
			),
225
		)
226
	);
227
}
228
229
add_action( 'give_register_updates', 'give_show_upgrade_notices' );
230
231
/**
232
 * Triggers all upgrade functions
233
 *
234
 * This function is usually triggered via AJAX
235
 *
236
 * @since 1.0
237
 * @return void
238
 */
239
function give_trigger_upgrades() {
240
241 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...
242
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
243
			'response' => 403,
244
		) );
245
	}
246
247
	$give_version = get_option( 'give_version' );
248
249
	if ( ! $give_version ) {
250
		// 1.0 is the first version to use this option so we must add it.
251
		$give_version = '1.0';
252
		add_option( 'give_version', $give_version );
253
	}
254
255
	update_option( 'give_version', GIVE_VERSION );
256
	delete_option( 'give_doing_upgrade' );
257
258
	if ( DOING_AJAX ) {
259
		die( 'complete' );
260
	} // End if().
261
}
262
263
add_action( 'wp_ajax_give_trigger_upgrades', 'give_trigger_upgrades' );
264
265
266
/**
267
 * Upgrades the
268
 *
269
 * Standardizes the discrepancies between two metakeys `_give_payment_customer_id` and `_give_payment_donor_id`
270
 *
271
 * @since      1.3.2
272
 */
273
function give_v132_upgrade_give_payment_customer_id() {
274
	global $wpdb;
275
276
	/* @var Give_Updates $give_updates */
277
	$give_updates = Give_Updates::get_instance();
278
279 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...
280
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
281
			'response' => 403,
282
		) );
283
	}
284
285
	ignore_user_abort( true );
286
287
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
288
		@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...
289
	}
290
291
	// UPDATE DB METAKEYS.
292
	$sql   = "UPDATE $wpdb->postmeta SET meta_key = '_give_payment_customer_id' WHERE meta_key = '_give_payment_donor_id'";
293
	$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...
294
295
	$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...
296
	give_set_upgrade_complete( 'upgrade_give_payment_customer_id' );
297
}
298
299
300
/**
301
 * Upgrades the Offline Status
302
 *
303
 * Reverses the issue where offline donations in "pending" status where inappropriately marked as abandoned
304
 *
305
 * @since      1.3.4
306
 */
307
function give_v134_upgrade_give_offline_status() {
308
	global $wpdb;
309
310
	/* @var Give_Updates $give_updates */
311
	$give_updates = Give_Updates::get_instance();
312
313
	// Get abandoned offline payments.
314
	$select = "SELECT ID FROM $wpdb->posts p ";
315
	$join   = "LEFT JOIN $wpdb->postmeta m ON p.ID = m.post_id ";
316
	$where  = "WHERE p.post_type = 'give_payment' ";
317
	$where  .= "AND ( p.post_status = 'abandoned' )";
318
	$where  .= "AND ( m.meta_key = '_give_payment_gateway' AND m.meta_value = 'offline' )";
319
320
	$sql            = $select . $join . $where;
321
	$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...
322
323
	foreach ( $found_payments as $payment ) {
324
325
		// Only change ones marked abandoned since our release last week because the admin may have marked some abandoned themselves.
326
		$modified_time = get_post_modified_time( 'U', false, $payment );
327
328
		// 1450124863 =  12/10/2015 20:42:25.
329
		if ( $modified_time >= 1450124863 ) {
330
331
			give_update_payment_status( $payment, 'pending' );
332
333
		}
334
	}
335
336
	$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...
337
	give_set_upgrade_complete( 'upgrade_give_offline_status' );
338
}
339
340
341
/**
342
 * Cleanup User Roles
343
 *
344
 * This upgrade routine removes unused roles and roles with typos
345
 *
346
 * @since      1.5.2
347
 */
348
function give_v152_cleanup_users() {
349
350
	$give_version = get_option( 'give_version' );
351
352
	if ( ! $give_version ) {
353
		// 1.0 is the first version to use this option so we must add it.
354
		$give_version = '1.0';
355
	}
356
357
	$give_version = preg_replace( '/[^0-9.].*/', '', $give_version );
358
359
	// v1.5.2 Upgrades
360
	if ( version_compare( $give_version, '1.5.2', '<' ) || ! give_has_upgrade_completed( 'upgrade_give_user_caps_cleanup' ) ) {
361
362
		// Delete all caps with "ss".
363
		// Also delete all unused "campaign" roles.
364
		$delete_caps = array(
365
			'delete_give_formss',
366
			'delete_others_give_formss',
367
			'delete_private_give_formss',
368
			'delete_published_give_formss',
369
			'read_private_forms',
370
			'edit_give_formss',
371
			'edit_others_give_formss',
372
			'edit_private_give_formss',
373
			'edit_published_give_formss',
374
			'publish_give_formss',
375
			'read_private_give_formss',
376
			'assign_give_campaigns_terms',
377
			'delete_give_campaigns',
378
			'delete_give_campaigns_terms',
379
			'delete_give_campaignss',
380
			'delete_others_give_campaignss',
381
			'delete_private_give_campaignss',
382
			'delete_published_give_campaignss',
383
			'edit_give_campaigns',
384
			'edit_give_campaigns_terms',
385
			'edit_give_campaignss',
386
			'edit_others_give_campaignss',
387
			'edit_private_give_campaignss',
388
			'edit_published_give_campaignss',
389
			'manage_give_campaigns_terms',
390
			'publish_give_campaignss',
391
			'read_give_campaigns',
392
			'read_private_give_campaignss',
393
			'view_give_campaigns_stats',
394
			'delete_give_paymentss',
395
			'delete_others_give_paymentss',
396
			'delete_private_give_paymentss',
397
			'delete_published_give_paymentss',
398
			'edit_give_paymentss',
399
			'edit_others_give_paymentss',
400
			'edit_private_give_paymentss',
401
			'edit_published_give_paymentss',
402
			'publish_give_paymentss',
403
			'read_private_give_paymentss',
404
		);
405
406
		global $wp_roles;
407
		foreach ( $delete_caps as $cap ) {
408
			foreach ( array_keys( $wp_roles->roles ) as $role ) {
409
				$wp_roles->remove_cap( $role, $cap );
410
			}
411
		}
412
413
		// Create Give plugin roles.
414
		$roles = new Give_Roles();
415
		$roles->add_roles();
416
		$roles->add_caps();
417
418
		// The Update Ran.
419
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
420
		give_set_upgrade_complete( 'upgrade_give_user_caps_cleanup' );
421
		delete_option( 'give_doing_upgrade' );
422
423
	}// End if().
424
425
}
426
427
add_action( 'admin_init', 'give_v152_cleanup_users' );
428
429
/**
430
 * 1.6 Upgrade routine to create the customer meta table.
431
 *
432
 * @since  1.6
433
 * @return void
434
 */
435
function give_v16_upgrades() {
436
	// Create the donor databases.
437
	$donors_db = new Give_DB_Donors();
438
	$donors_db->create_table();
439
	$donor_meta = new Give_DB_Donor_Meta();
440
	$donor_meta->create_table();
441
}
442
443
/**
444
 * 1.7 Upgrades.
445
 *
446
 * a. Update license api data for plugin addons.
447
 * b. Cleanup user roles.
448
 *
449
 * @since  1.7
450
 * @return void
451
 */
452
function give_v17_upgrades() {
453
	// Upgrade license data.
454
	give_v17_upgrade_addon_license_data();
455
	give_v17_cleanup_roles();
456
}
457
458
/**
459
 * Upgrade license data
460
 *
461
 * @since 1.7
462
 */
463
function give_v17_upgrade_addon_license_data() {
464
	$give_options = give_get_settings();
465
466
	$api_url = 'https://givewp.com/give-sl-api/';
467
468
	// Get addons license key.
469
	$addons = array();
470
	foreach ( $give_options as $key => $value ) {
471
		if ( false !== strpos( $key, '_license_key' ) ) {
472
			$addons[ $key ] = $value;
473
		}
474
	}
475
476
	// Bailout: We do not have any addon license data to upgrade.
477
	if ( empty( $addons ) ) {
478
		return false;
479
	}
480
481
	foreach ( $addons as $key => $addon_license ) {
482
483
		// Get addon shortname.
484
		$shortname = str_replace( '_license_key', '', $key );
485
486
		// Addon license option name.
487
		$addon_license_option_name = $shortname . '_license_active';
488
489
		// bailout if license is empty.
490
		if ( empty( $addon_license ) ) {
491
			delete_option( $addon_license_option_name );
492
			continue;
493
		}
494
495
		// Get addon name.
496
		$addon_name       = array();
497
		$addon_name_parts = explode( '_', str_replace( 'give_', '', $shortname ) );
498
		foreach ( $addon_name_parts as $name_part ) {
499
500
			// Fix addon name
501
			switch ( $name_part ) {
502
				case 'authorizenet' :
503
					$name_part = 'authorize.net';
504
					break;
505
			}
506
507
			$addon_name[] = ucfirst( $name_part );
508
		}
509
510
		$addon_name = implode( ' ', $addon_name );
511
512
		// Data to send to the API
513
		$api_params = array(
514
			'edd_action' => 'activate_license', // never change from "edd_" to "give_"!
515
			'license'    => $addon_license,
516
			'item_name'  => urlencode( $addon_name ),
517
			'url'        => home_url(),
518
		);
519
520
		// Call the API.
521
		$response = wp_remote_post(
522
			$api_url,
523
			array(
524
				'timeout'   => 15,
525
				'sslverify' => false,
526
				'body'      => $api_params,
527
			)
528
		);
529
530
		// Make sure there are no errors.
531
		if ( is_wp_error( $response ) ) {
532
			delete_option( $addon_license_option_name );
533
			continue;
534
		}
535
536
		// Tell WordPress to look for updates.
537
		set_site_transient( 'update_plugins', null );
538
539
		// Decode license data.
540
		$license_data = json_decode( wp_remote_retrieve_body( $response ) );
541
		update_option( $addon_license_option_name, $license_data );
542
	}// End foreach().
543
}
544
545
546
/**
547
 * Cleanup User Roles.
548
 *
549
 * This upgrade routine removes unused roles and roles with typos.
550
 *
551
 * @since      1.7
552
 */
553
function give_v17_cleanup_roles() {
554
555
	// Delete all caps with "_give_forms_" and "_give_payments_"
556
	// These roles have no usage; the proper is singular.
557
	$delete_caps = array(
558
		'view_give_forms_stats',
559
		'delete_give_forms_terms',
560
		'assign_give_forms_terms',
561
		'edit_give_forms_terms',
562
		'manage_give_forms_terms',
563
		'view_give_payments_stats',
564
		'manage_give_payments_terms',
565
		'edit_give_payments_terms',
566
		'assign_give_payments_terms',
567
		'delete_give_payments_terms',
568
	);
569
570
	global $wp_roles;
571
	foreach ( $delete_caps as $cap ) {
572
		foreach ( array_keys( $wp_roles->roles ) as $role ) {
573
			$wp_roles->remove_cap( $role, $cap );
574
		}
575
	}
576
577
	// Set roles again.
578
	$roles = new Give_Roles();
579
	$roles->add_roles();
580
	$roles->add_caps();
581
582
}
583
584
/**
585
 * 1.8 Upgrades.
586
 *
587
 * a. Upgrade checkbox settings to radio button settings.
588
 * a. Update form meta for new metabox settings.
589
 *
590
 * @since  1.8
591
 * @return void
592
 */
593
function give_v18_upgrades() {
594
	// Upgrade checkbox settings to radio button settings.
595
	give_v18_upgrades_core_setting();
596
}
597
598
/**
599
 * Upgrade core settings.
600
 *
601
 * @since  1.8
602
 * @return void
603
 */
604
function give_v18_upgrades_core_setting() {
605
	// Core settings which changes from checkbox to radio.
606
	$core_setting_names = array_merge(
607
		array_keys( give_v18_renamed_core_settings() ),
608
		array(
609
			'uninstall_on_delete',
610
			'scripts_footer',
611
			'test_mode',
612
			'email_access',
613
			'terms',
614
			'give_offline_donation_enable_billing_fields',
615
		)
616
	);
617
618
	// Bailout: If not any setting define.
619
	if ( $give_settings = get_option( 'give_settings' ) ) {
620
621
		$setting_changed = false;
622
623
		// Loop: check each setting field.
624
		foreach ( $core_setting_names as $setting_name ) {
625
			// New setting name.
626
			$new_setting_name = preg_replace( '/^(enable_|disable_)/', '', $setting_name );
627
628
			// Continue: If setting already set.
629
			if (
630
				array_key_exists( $new_setting_name, $give_settings )
631
				&& in_array( $give_settings[ $new_setting_name ], array( 'enabled', 'disabled' ) )
632
			) {
633
				continue;
634
			}
635
636
			// Set checkbox value to radio value.
637
			$give_settings[ $setting_name ] = ( ! empty( $give_settings[ $setting_name ] ) && 'on' === $give_settings[ $setting_name ] ? 'enabled' : 'disabled' );
638
639
			// @see https://github.com/WordImpress/Give/issues/1063
640
			if ( false !== strpos( $setting_name, 'disable_' ) ) {
641
642
				$give_settings[ $new_setting_name ] = ( give_is_setting_enabled( $give_settings[ $setting_name ] ) ? 'disabled' : 'enabled' );
643
			} elseif ( false !== strpos( $setting_name, 'enable_' ) ) {
644
645
				$give_settings[ $new_setting_name ] = ( give_is_setting_enabled( $give_settings[ $setting_name ] ) ? 'enabled' : 'disabled' );
646
			}
647
648
			// Tell bot to update core setting to db.
649
			if ( ! $setting_changed ) {
650
				$setting_changed = true;
651
			}
652
		}
653
654
		// Update setting only if they changed.
655
		if ( $setting_changed ) {
656
			update_option( 'give_settings', $give_settings );
657
		}
658
	}// End if().
659
660
	give_set_upgrade_complete( 'v18_upgrades_core_setting' );
661
}
662
663
/**
664
 * Upgrade form metadata for new metabox settings.
665
 *
666
 * @since  1.8
667
 * @return void
668
 */
669
function give_v18_upgrades_form_metadata() {
670
	/* @var Give_Updates $give_updates */
671
	$give_updates = Give_Updates::get_instance();
672
673
	// form query
674
	$forms = new WP_Query( array(
675
			'paged'          => $give_updates->step,
676
			'status'         => 'any',
677
			'order'          => 'ASC',
678
			'post_type'      => 'give_forms',
679
			'posts_per_page' => 20,
680
		)
681
	);
682
683
	if ( $forms->have_posts() ) {
684
		$give_updates->set_percentage( $forms->found_posts, ( $give_updates->step * 20 ) );
685
686
		while ( $forms->have_posts() ) {
687
			$forms->the_post();
688
689
			// Form content.
690
			// Note in version 1.8 display content setting split into display content and content placement setting.
691
			// You can delete _give_content_option in future
692
			$show_content = give_get_meta( get_the_ID(), '_give_content_option', true );
693
			if ( $show_content && ! give_get_meta( get_the_ID(), '_give_display_content', true ) ) {
694
				$field_value = ( 'none' !== $show_content ? 'enabled' : 'disabled' );
695
				give_update_meta( get_the_ID(), '_give_display_content', $field_value );
696
697
				$field_value = ( 'none' !== $show_content ? $show_content : 'give_pre_form' );
698
				give_update_meta( get_the_ID(), '_give_content_placement', $field_value );
699
			}
700
701
			// "Disable" Guest Donation. Checkbox
702
			// See: https://github.com/WordImpress/Give/issues/1470
703
			$guest_donation        = give_get_meta( get_the_ID(), '_give_logged_in_only', true );
704
			$guest_donation_newval = ( in_array( $guest_donation, array( 'yes', 'on' ) ) ? 'disabled' : 'enabled' );
705
			give_update_meta( get_the_ID(), '_give_logged_in_only', $guest_donation_newval );
706
707
			// Offline Donations
708
			// See: https://github.com/WordImpress/Give/issues/1579
709
			$offline_donation = give_get_meta( get_the_ID(), '_give_customize_offline_donations', true );
710
			if ( 'no' === $offline_donation ) {
711
				$offline_donation_newval = 'global';
712
			} elseif ( 'yes' === $offline_donation ) {
713
				$offline_donation_newval = 'enabled';
714
			} else {
715
				$offline_donation_newval = 'disabled';
716
			}
717
			give_update_meta( get_the_ID(), '_give_customize_offline_donations', $offline_donation_newval );
718
719
			// Convert yes/no setting field to enabled/disabled.
720
			$form_radio_settings = array(
721
				// Custom Amount.
722
				'_give_custom_amount',
723
724
				// Donation Gaol.
725
				'_give_goal_option',
726
727
				// Close Form.
728
				'_give_close_form_when_goal_achieved',
729
730
				// Term & conditions.
731
				'_give_terms_option',
732
733
				// Billing fields.
734
				'_give_offline_donation_enable_billing_fields_single',
735
			);
736
737
			foreach ( $form_radio_settings as $meta_key ) {
738
				// Get value.
739
				$field_value = give_get_meta( get_the_ID(), $meta_key, true );
740
741
				// Convert meta value only if it is in yes/no/none.
742
				if ( in_array( $field_value, array( 'yes', 'on', 'no', 'none' ) ) ) {
743
744
					$field_value = ( in_array( $field_value, array( 'yes', 'on' ) ) ? 'enabled' : 'disabled' );
745
					give_update_meta( get_the_ID(), $meta_key, $field_value );
746
				}
747
			}
748
		}// End while().
749
750
		wp_reset_postdata();
751
752
	} else {
753
		// No more forms found, finish up.
754
		give_set_upgrade_complete( 'v18_upgrades_form_metadata' );
755
	}
756
}
757
758
759
/**
760
 * Get list of core setting renamed in version 1.8.
761
 *
762
 * @since  1.8
763
 * @return array
764
 */
765
function give_v18_renamed_core_settings() {
766
	return array(
767
		'disable_paypal_verification' => 'paypal_verification',
768
		'disable_css'                 => 'css',
769
		'disable_welcome'             => 'welcome',
770
		'disable_forms_singular'      => 'forms_singular',
771
		'disable_forms_archives'      => 'forms_archives',
772
		'disable_forms_excerpt'       => 'forms_excerpt',
773
		'disable_form_featured_img'   => 'form_featured_img',
774
		'disable_form_sidebar'        => 'form_sidebar',
775
		'disable_admin_notices'       => 'admin_notices',
776
		'disable_the_content_filter'  => 'the_content_filter',
777
		'enable_floatlabels'          => 'floatlabels',
778
		'enable_categories'           => 'categories',
779
		'enable_tags'                 => 'tags',
780
	);
781
}
782
783
784
/**
785
 * Upgrade core settings.
786
 *
787
 * @since  1.8.7
788
 * @return void
789
 */
790
function give_v187_upgrades() {
791
	global $wpdb;
792
793
	/**
794
	 * Upgrade 1: Remove stat and cache transients.
795
	 */
796
	$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...
797
		$wpdb->prepare(
798
			"SELECT * FROM {$wpdb->options} where (option_name LIKE '%%%s%%' OR option_name LIKE '%%%s%%')",
799
			array(
800
				'_transient_give_stats_',
801
				'give_cache',
802
				'_transient_give_add_ons_feed',
803
				'_transient__give_ajax_works',
804
				'_transient_give_total_api_keys',
805
				'_transient_give_i18n_give_promo_hide',
806
				'_transient_give_contributors',
807
				'_transient_give_estimated_monthly_stats',
808
				'_transient_give_earnings_total',
809
				'_transient_give_i18n_give_',
810
				'_transient__give_installed',
811
				'_transient__give_activation_redirect',
812
				'_transient__give_hide_license_notices_shortly_',
813
				'give_income_total',
814
			)
815
		),
816
		1
817
	);
818
819
	// User related transients.
820
	$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...
821
		$wpdb->prepare(
822
			"SELECT user_id, meta_key
823
			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...
824
			WHERE meta_value=%s",
825
			'give_user_public_key'
826
		),
827
		ARRAY_A
828
	);
829
830
	if ( ! empty( $user_apikey_options ) ) {
831
		foreach ( $user_apikey_options as $user ) {
832
			$cached_options[] = '_transient_' . md5( 'give_api_user_' . $user['meta_key'] );
833
			$cached_options[] = '_transient_' . md5( 'give_api_user_public_key' . $user['user_id'] );
834
			$cached_options[] = '_transient_' . md5( 'give_api_user_secret_key' . $user['user_id'] );
835
		}
836
	}
837
838
	if ( ! empty( $cached_options ) ) {
839
		foreach ( $cached_options as $option ) {
840 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...
841
				case ( false !== strpos( $option, 'transient' ) ):
842
					$option = str_replace( '_transient_', '', $option );
843
					delete_transient( $option );
844
					break;
845
846
				default:
847
					delete_option( $option );
848
			}
849
		}
850
	}
851
}
852
853
/**
854
 * Update Capabilities for Give_Worker User Role.
855
 *
856
 * This upgrade routine will update access rights for Give_Worker User Role.
857
 *
858
 * @since      1.8.8
859
 */
860
function give_v188_upgrades() {
861
862
	global $wp_roles;
863
864
	// Get the role object.
865
	$give_worker = get_role( 'give_worker' );
866
867
	// A list of capabilities to add for give workers.
868
	$caps_to_add = array(
869
		'edit_posts',
870
		'edit_pages',
871
	);
872
873
	foreach ( $caps_to_add as $cap ) {
874
		// Add the capability.
875
		$give_worker->add_cap( $cap );
876
	}
877
878
}
879
880
/**
881
 * Update Post meta for minimum and maximum amount for multi level donation forms
882
 *
883
 * This upgrade routine adds post meta for give_forms CPT for multi level donation form.
884
 *
885
 * @since      1.8.9
886
 */
887
function give_v189_upgrades_levels_post_meta_callback() {
888
	/* @var Give_Updates $give_updates */
889
	$give_updates = Give_Updates::get_instance();
890
891
	// form query
892
	$donation_forms = new WP_Query( array(
893
			'paged'          => $give_updates->step,
894
			'status'         => 'any',
895
			'order'          => 'ASC',
896
			'post_type'      => 'give_forms',
897
			'posts_per_page' => 20,
898
		)
899
	);
900
901
	if ( $donation_forms->have_posts() ) {
902
		$give_updates->set_percentage( $donation_forms->found_posts, ( $give_updates->step * 20 ) );
903
904
		while ( $donation_forms->have_posts() ) {
905
			$donation_forms->the_post();
906
			$form_id = get_the_ID();
907
908
			// Remove formatting from _give_set_price
909
			update_post_meta(
910
				$form_id,
911
				'_give_set_price',
912
				give_sanitize_amount( get_post_meta( $form_id, '_give_set_price', true ) )
913
			);
914
915
			// Remove formatting from _give_custom_amount_minimum
916
			update_post_meta(
917
				$form_id,
918
				'_give_custom_amount_minimum',
919
				give_sanitize_amount( get_post_meta( $form_id, '_give_custom_amount_minimum', true ) )
920
			);
921
922
			// Bailout.
923
			if ( 'set' === get_post_meta( $form_id, '_give_price_option', true ) ) {
924
				continue;
925
			}
926
927
			$donation_levels = get_post_meta( $form_id, '_give_donation_levels', true );
928
929
			if ( ! empty( $donation_levels ) ) {
930
931
				foreach ( $donation_levels as $index => $donation_level ) {
932
					if ( isset( $donation_level['_give_amount'] ) ) {
933
						$donation_levels[ $index ]['_give_amount'] = give_sanitize_amount( $donation_level['_give_amount'] );
934
					}
935
				}
936
937
				update_post_meta( $form_id, '_give_donation_levels', $donation_levels );
938
939
				$donation_levels_amounts = wp_list_pluck( $donation_levels, '_give_amount' );
940
941
				$min_amount = min( $donation_levels_amounts );
942
				$max_amount = max( $donation_levels_amounts );
943
944
				// Set Minimum and Maximum amount for Multi Level Donation Forms
945
				give_update_meta( $form_id, '_give_levels_minimum_amount', $min_amount ? give_sanitize_amount( $min_amount ) : 0 );
946
				give_update_meta( $form_id, '_give_levels_maximum_amount', $max_amount ? give_sanitize_amount( $max_amount ) : 0 );
947
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
948
949
		}
950
951
		/* Restore original Post Data */
952
		wp_reset_postdata();
953
	} else {
954
		// The Update Ran.
955
		give_set_upgrade_complete( 'v189_upgrades_levels_post_meta' );
956
	}
957
958
}
959
960
961
/**
962
 * Give version 1.8.9 upgrades
963
 *
964
 * @since      1.8.9
965
 */
966
function give_v189_upgrades() {
967
	/**
968
	 * 1. Remove user license related notice show blocked ( Give_Notice will handle )
969
	 */
970
	global $wpdb;
971
972
	// Delete permanent notice blocker.
973
	$wpdb->query(
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
974
		$wpdb->prepare(
975
			"
976
					DELETE FROM $wpdb->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...
977
					WHERE meta_key
978
					LIKE '%%%s%%'
979
					",
980
			'_give_hide_license_notices_permanently'
981
		)
982
	);
983
984
	// Delete short notice blocker.
985
	$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...
986
		$wpdb->prepare(
987
			"
988
					DELETE FROM $wpdb->options
989
					WHERE option_name
990
					LIKE '%%%s%%'
991
					",
992
			'__give_hide_license_notices_shortly_'
993
		)
994
	);
995
}
996
997
/**
998
 * 2.0 Upgrades.
999
 *
1000
 * @since  2.0
1001
 * @return void
1002
 */
1003
function give_v20_upgrades() {
1004
	// Upgrade email settings.
1005
	give_v20_upgrades_email_setting();
1006
	give_v20_upgrade_donor_register_email_message();
1007
}
1008
1009
/**
1010
 * Move old email api settings to new email setting api for following emails:
1011
 *    1. new offline donation         [This was hard coded]
1012
 *    2. offline donation instruction
1013
 *    3. new donation
1014
 *    4. donation receipt
1015
 *
1016
 * @since 2.0
1017
 */
1018
function give_v20_upgrades_email_setting() {
1019
	$all_setting = give_get_settings();
1020
1021
	// Bailout on fresh install.
1022
	if ( empty( $all_setting ) ) {
1023
		return;
1024
	}
1025
1026
	$settings = array(
1027
		'offline_donation_subject'      => 'offline-donation-instruction_email_subject',
1028
		'global_offline_donation_email' => 'offline-donation-instruction_email_message',
1029
		'donation_subject'              => 'donation-receipt_email_subject',
1030
		'donation_receipt'              => 'donation-receipt_email_message',
1031
		'donation_notification_subject' => 'new-donation_email_subject',
1032
		'donation_notification'         => 'new-donation_email_message',
1033
		'admin_notice_emails'           => array(
1034
			'new-donation_recipient',
1035
			'new-offline-donation_recipient',
1036
			'new-donor-register_recipient',
1037
		),
1038
		'admin_notices'                 => 'new-donation_notification',
1039
	);
1040
1041
	foreach ( $settings as $old_setting => $new_setting ) {
1042
		// Do not update already modified
1043
		if ( ! is_array( $new_setting ) ) {
1044
			if ( array_key_exists( $new_setting, $all_setting ) || ! array_key_exists( $old_setting, $all_setting ) ) {
1045
				continue;
1046
			}
1047
		}
1048
1049
		switch ( $old_setting ) {
1050
			case 'admin_notices':
1051
				$notification_status = give_get_option( $old_setting, 'disabled' );
1052
1053
				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 1041 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...
1054
				give_delete_option( $old_setting );
1055
				break;
1056
1057
			// @todo: Delete this option later ( version > 2.0 ) because we need this for backward compatibility give_get_admin_notice_emails.
1058
			case 'admin_notice_emails':
1059
				$recipients = give_get_admin_notice_emails();
1060
1061
				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...
1062
					// bailout if setting already exist.
1063
					if ( array_key_exists( $setting, $all_setting ) ) {
1064
						continue;
1065
					}
1066
1067
					give_update_option( $setting, $recipients );
1068
				}
1069
				break;
1070
1071
			default:
1072
				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 1041 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
		}
1075
	}
1076
}
1077
1078
/**
1079
 * Update Donor Register Email Message.
1080
 *
1081
 * @since 2.0
1082
 */
1083
function give_v20_upgrade_donor_register_email_message() {
1084
	$all_setting = give_get_settings();
1085
1086
	// Bailout on fresh install.
1087
	if ( empty( $all_setting ) ) {
1088
		return;
1089
	}
1090
1091
	$donor_register_email = Give_Donor_Register_Email::get_instance();
1092
	give_update_option( 'donor-register_email_message', $donor_register_email->get_default_email_message() );
1093
}
1094
1095
1096
/**
1097
 * Give version 1.8.9 upgrades
1098
 *
1099
 * @since      1.8.9
1100
 */
1101
function give_v1812_upgrades() {
1102
	/**
1103
	 * Validate number format settings.
1104
	 */
1105
	$give_settings        = give_get_settings();
1106
	$give_setting_updated = false;
1107
1108
	if ( $give_settings['thousands_separator'] === $give_settings['decimal_separator'] ) {
1109
		$give_settings['number_decimals']   = 0;
1110
		$give_settings['decimal_separator'] = '';
1111
		$give_setting_updated               = true;
1112
1113
	} elseif ( empty( $give_settings['decimal_separator'] ) ) {
1114
		$give_settings['number_decimals'] = 0;
1115
		$give_setting_updated             = true;
1116
1117
	} elseif ( 6 < absint( $give_settings['number_decimals'] ) ) {
1118
		$give_settings['number_decimals'] = 5;
1119
		$give_setting_updated             = true;
1120
	}
1121
1122
	if ( $give_setting_updated ) {
1123
		update_option( 'give_settings', $give_settings );
1124
	}
1125
}
1126
1127
1128
/**
1129
 * Give version 1.8.12 update
1130
 *
1131
 * Standardized amount values to six decimal
1132
 *
1133
 * @see        https://github.com/WordImpress/Give/issues/1849#issuecomment-315128602
1134
 *
1135
 * @since      1.8.12
1136
 */
1137
function give_v1812_update_amount_values_callback() {
1138
	/* @var Give_Updates $give_updates */
1139
	$give_updates = Give_Updates::get_instance();
1140
1141
	// form query
1142
	$donation_forms = new WP_Query( array(
1143
			'paged'          => $give_updates->step,
1144
			'status'         => 'any',
1145
			'order'          => 'ASC',
1146
			'post_type'      => array( 'give_forms', 'give_payment' ),
1147
			'posts_per_page' => 20,
1148
		)
1149
	);
1150
	if ( $donation_forms->have_posts() ) {
1151
		$give_updates->set_percentage( $donation_forms->found_posts, ( $give_updates->step * 20 ) );
1152
1153
		while ( $donation_forms->have_posts() ) {
1154
			$donation_forms->the_post();
1155
			global $post;
1156
1157
			$meta = get_post_meta( $post->ID );
1158
1159
			switch ( $post->post_type ) {
1160
				case 'give_forms':
1161
					// _give_set_price
1162
					if ( ! empty( $meta['_give_set_price'][0] ) ) {
1163
						update_post_meta( $post->ID, '_give_set_price', give_sanitize_amount_for_db( $meta['_give_set_price'][0] ) );
1164
					}
1165
1166
					// _give_custom_amount_minimum
1167
					if ( ! empty( $meta['_give_custom_amount_minimum'][0] ) ) {
1168
						update_post_meta( $post->ID, '_give_custom_amount_minimum', give_sanitize_amount_for_db( $meta['_give_custom_amount_minimum'][0] ) );
1169
					}
1170
1171
					// _give_levels_minimum_amount
1172
					if ( ! empty( $meta['_give_levels_minimum_amount'][0] ) ) {
1173
						update_post_meta( $post->ID, '_give_levels_minimum_amount', give_sanitize_amount_for_db( $meta['_give_levels_minimum_amount'][0] ) );
1174
					}
1175
1176
					// _give_levels_maximum_amount
1177
					if ( ! empty( $meta['_give_levels_maximum_amount'][0] ) ) {
1178
						update_post_meta( $post->ID, '_give_levels_maximum_amount', give_sanitize_amount_for_db( $meta['_give_levels_maximum_amount'][0] ) );
1179
					}
1180
1181
					// _give_set_goal
1182
					if ( ! empty( $meta['_give_set_goal'][0] ) ) {
1183
						update_post_meta( $post->ID, '_give_set_goal', give_sanitize_amount_for_db( $meta['_give_set_goal'][0] ) );
1184
					}
1185
1186
					// _give_form_earnings
1187
					if ( ! empty( $meta['_give_form_earnings'][0] ) ) {
1188
						update_post_meta( $post->ID, '_give_form_earnings', give_sanitize_amount_for_db( $meta['_give_form_earnings'][0] ) );
1189
					}
1190
1191
					// _give_custom_amount_minimum
1192
					if ( ! empty( $meta['_give_donation_levels'][0] ) ) {
1193
						$donation_levels = unserialize( $meta['_give_donation_levels'][0] );
1194
1195
						foreach ( $donation_levels as $index => $level ) {
1196
							if ( empty( $level['_give_amount'] ) ) {
1197
								continue;
1198
							}
1199
1200
							$donation_levels[ $index ]['_give_amount'] = give_sanitize_amount_for_db( $level['_give_amount'] );
1201
						}
1202
1203
						$meta['_give_donation_levels'] = $donation_levels;
1204
						update_post_meta( $post->ID, '_give_donation_levels', $meta['_give_donation_levels'] );
1205
					}
1206
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1207
1208
					break;
1209
1210
				case 'give_payment':
1211
					// _give_payment_total
1212
					if ( ! empty( $meta['_give_payment_total'][0] ) ) {
1213
						update_post_meta( $post->ID, '_give_payment_total', give_sanitize_amount_for_db( $meta['_give_payment_total'][0] ) );
1214
					}
1215
1216
					break;
1217
			}
1218
		}
1219
1220
		/* Restore original Post Data */
1221
		wp_reset_postdata();
1222
	} else {
1223
		// The Update Ran.
1224
		give_set_upgrade_complete( 'v1812_update_amount_values' );
1225
	}
1226
}
1227
1228
1229
/**
1230
 * Give version 1.8.12 update
1231
 *
1232
 * Standardized amount values to six decimal for donor
1233
 *
1234
 * @see        https://github.com/WordImpress/Give/issues/1849#issuecomment-315128602
1235
 *
1236
 * @since      1.8.12
1237
 */
1238
function give_v1812_update_donor_purchase_value_callback() {
1239
	/* @var Give_Updates $give_updates */
1240
	$give_updates = Give_Updates::get_instance();
1241
	$offset       = 1 === $give_updates->step ? 0 : $give_updates->step * 20;
1242
1243
	// form query
1244
	$donors = Give()->donors->get_donors( array(
1245
			'number' => 20,
1246
			'offset' => $offset,
1247
		)
1248
	);
1249
1250
	if ( ! empty( $donors ) ) {
1251
		$give_updates->set_percentage( Give()->donors->count(), $offset );
1252
1253
		/* @var Object $donor */
1254
		foreach ( $donors as $donor ) {
1255
			Give()->donors->update( $donor->id, array( 'purchase_value' => give_sanitize_amount_for_db( $donor->purchase_value ) ) );
1256
		}
1257
	} else {
1258
		// The Update Ran.
1259
		give_set_upgrade_complete( 'v1812_update_donor_purchase_values' );
1260
	}
1261
}
1262
1263
/**
1264
 * Upgrade routine for updating user roles for existing donors.
1265
 *
1266
 * @since 1.8.13
1267
 */
1268
function give_v1813_update_donor_user_roles_callback() {
1269
	/* @var Give_Updates $give_updates */
1270
	$give_updates = Give_Updates::get_instance();
1271
	$offset       = 1 === $give_updates->step ? 0 : $give_updates->step * 20;
1272
1273
	// Fetch all the existing donors.
1274
	$donors = Give()->donors->get_donors( array(
1275
			'number' => 20,
1276
			'offset' => $offset,
1277
		)
1278
	);
1279
1280
	if ( ! empty( $donors ) ) {
1281
		$give_updates->set_percentage( Give()->donors->count(), ( $give_updates->step * 20 ) );
1282
1283
		/* @var Object $donor */
1284
		foreach ( $donors as $donor ) {
1285
			$user_id = $donor->user_id;
1286
1287
			// Proceed, if donor is attached with user.
1288
			if ( $user_id ) {
1289
				$user = get_userdata( $user_id );
1290
1291
				// Update user role, if user has subscriber role.
1292
				if ( is_array( $user->roles ) && in_array( 'subscriber', $user->roles ) ) {
1293
					wp_update_user(
1294
						array(
1295
							'ID'   => $user_id,
1296
							'role' => 'give_donor',
1297
						)
1298
					);
1299
				}
1300
			}
1301
		}
1302
	} else {
1303
		// The Update Ran.
1304
		give_set_upgrade_complete( 'v1813_update_donor_user_roles' );
1305
	}
1306
}
1307
1308
/**
1309
 * Version 1.8.13 automatic updates
1310
 *
1311
 * @since 1.8.13
1312
 */
1313
function give_v1813_upgrades() {
1314
	// Update admin setting.
1315
	give_update_option( 'donor_default_user_role', 'give_donor' );
1316
1317
	// Update Give roles.
1318
	$roles = new Give_Roles();
1319
	$roles->add_roles();
1320
	$roles->add_caps();
1321
}
1322
1323
/**
1324
 * Upgrade form metadata for new metabox settings.
1325
 *
1326
 * @since  2.0
1327
 * @return void
1328
 */
1329
function give_v20_upgrades_form_metadata_callback() {
1330
	$give_updates = Give_Updates::get_instance();
1331
1332
	// form query
1333
	$forms = new WP_Query( array(
1334
			'paged'          => $give_updates->step,
1335
			'status'         => 'any',
1336
			'order'          => 'ASC',
1337
			'post_type'      => 'give_forms',
1338
			'posts_per_page' => 20,
1339
		)
1340
	);
1341
1342
	if ( $forms->have_posts() ) {
1343
		$give_updates->set_percentage( $forms->found_posts, ( $give_updates->step * 20 ) );
1344
1345
		while ( $forms->have_posts() ) {
1346
			$forms->the_post();
1347
			global $post;
1348
1349
			// Update offline instruction email notification status.
1350
			$offline_instruction_notification_status = get_post_meta( get_the_ID(), '_give_customize_offline_donations', true );
1351
			$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...
1352
				? $offline_instruction_notification_status
1353
				: 'global';
1354
			update_post_meta( get_the_ID(), '_give_offline-donation-instruction_notification', $offline_instruction_notification_status );
1355
1356
			// Update offline instruction email message.
1357
			update_post_meta(
1358
				get_the_ID(),
1359
				'_give_offline-donation-instruction_email_message',
1360
				get_post_meta(
1361
					get_the_ID(),
1362
					// @todo: Delete this option later ( version > 2.0 ).
1363
					'_give_offline_donation_email',
1364
					true
1365
				)
1366
			);
1367
1368
			// Update offline instruction email subject.
1369
			update_post_meta(
1370
				get_the_ID(),
1371
				'_give_offline-donation-instruction_email_subject',
1372
				get_post_meta(
1373
					get_the_ID(),
1374
					// @todo: Delete this option later ( version > 2.0 ).
1375
					'_give_offline_donation_subject',
1376
					true
1377
				)
1378
			);
1379
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1380
1381
		}// End while().
1382
1383
		wp_reset_postdata();
1384
	} else {
1385
		// No more forms found, finish up.
1386
		give_set_upgrade_complete( 'v20_upgrades_form_metadata' );
1387
	}
1388
}
1389
1390
1391
/**
1392
 * Upgrade payment metadata for new metabox settings.
1393
 *
1394
 * @since  2.0
1395
 * @global wpdb $wpdb
1396
 * @return void
1397
 */
1398
function give_v20_upgrades_payment_metadata_callback() {
1399
	global $wpdb;
1400
	$give_updates = Give_Updates::get_instance();
1401
1402
	// form query
1403
	$forms = new WP_Query( array(
1404
			'paged'          => $give_updates->step,
1405
			'status'         => 'any',
1406
			'order'          => 'ASC',
1407
			'post_type'      => 'give_payment',
1408
			'posts_per_page' => 20,
1409
		)
1410
	);
1411
1412
	if ( $forms->have_posts() ) {
1413
		$give_updates->set_percentage( $forms->found_posts, ( $give_updates->step * 20 ) );
1414
1415
		while ( $forms->have_posts() ) {
1416
			$forms->the_post();
1417
			global $post;
1418
1419
			// Split _give_payment_meta meta.
1420
			$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...
1421
			if ( ! empty( $payment_meta ) ) {
1422
				_give_20_bc_split_and_save_give_payment_meta( $post->ID, maybe_unserialize( $payment_meta ) );
1423
			}
1424
1425
			$deprecated_meta_keys = array(
1426
				'_give_payment_customer_id' => '_give_payment_donor_id',
1427
				'_give_payment_user_email'  => '_give_payment_donor_email',
1428
				'_give_payment_user_ip'     => '_give_payment_donor_ip',
1429
			);
1430
1431
			foreach ( $deprecated_meta_keys as $old_meta_key => $new_meta_key ) {
1432
				// Do not add new meta key if already exist.
1433
				if ( give_get_meta( $post->ID, $new_meta_key, true ) ) {
1434
					continue;
1435
				}
1436
1437
				$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...
1438
				if ( ! empty( $meta_id ) ) {
1439
					$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...
1440
				}
1441
			}
1442
1443
			// Bailout
1444
			if ( $donor_id = give_get_meta( $post->ID, '_give_payment_donor_id', true ) ) {
1445
				/* @var Give_Donor $donor */
1446
				$donor = new Give_Donor( $donor_id );
1447
1448
				$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...
1449
				$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...
1450
				$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...
1451
				$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...
1452
				$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...
1453
				$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...
1454
1455
				// Save address.
1456
				$donor->add_address( 'billing[]', $address );
1457
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1458
1459
		}// End while().
1460
1461
		wp_reset_postdata();
1462
	} else {
1463
		// Delete user id meta.
1464
		$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...
1465
1466
		// No more forms found, finish up.
1467
		give_set_upgrade_complete( 'v20_upgrades_payment_metadata' );
1468
	}
1469
}
1470
1471
1472
/**
1473
 * Upgrade logs data.
1474
 * @todo   : check if payment price id is necessary to store in log meta or not
1475
 *
1476
 * @since  2.0
1477
 * @return void
1478
 */
1479
function give_v20_logs_upgrades_callback() {
1480
	global $wpdb;
1481
	$give_updates = Give_Updates::get_instance();
1482
1483
	// form query
1484
	$forms = new WP_Query( array(
1485
			'paged'          => $give_updates->step,
1486
			'order'          => 'DESC',
1487
			'post_type'      => 'give_log',
1488
			'post_status'    => 'any',
1489
			'posts_per_page' => 20,
1490
		)
1491
	);
1492
1493
	if ( $forms->have_posts() ) {
1494
		$give_updates->set_percentage( $forms->found_posts, $give_updates->step * 20 );
1495
1496
		while ( $forms->have_posts() ) {
1497
			$forms->the_post();
1498
			global $post;
1499
			$term      = get_the_terms( $post->ID, 'give_log_type' );
1500
			$term      = ! is_wp_error( $term ) && ! empty( $term ) ? $term[0] : array();
1501
			$term_name = ! empty( $term ) ? $term->slug : '';
1502
1503
			$log_data = array(
1504
				'ID'           => $post->ID,
1505
				'log_title'    => $post->post_title,
1506
				'log_content'  => $post->post_content,
1507
				'log_parent'   => 0,
1508
				'log_type'     => $term_name,
1509
				'log_date'     => $post->post_date,
1510
				'log_date_gmt' => $post->post_date_gmt,
1511
			);
1512
			$log_meta = array();
1513
1514
			if ( $old_log_meta = get_post_meta( $post->ID ) ) {
1515
				foreach ( $old_log_meta as $meta_key => $meta_value ) {
1516
					switch ( $meta_key ) {
1517
						case '_give_log_payment_id':
1518
							$log_data['log_parent']        = current( $meta_value );
1519
							$log_meta['_give_log_form_id'] = $post->post_parent;
1520
							break;
1521
1522
						default:
1523
							$log_meta[ $meta_key ] = current( $meta_value );
1524
					}
1525
				}
1526
			}
1527
1528
			if ( 'api_request' === $term_name ) {
1529
				$log_meta['_give_log_api_query'] = $post->post_excerpt;
1530
			}
1531
1532
			$wpdb->insert( "{$wpdb->prefix}give_logs", $log_data );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
1533
1534
			if ( ! empty( $log_meta ) ) {
1535
				foreach ( $log_meta as $meta_key => $meta_value ) {
1536
					Give()->logs->logmeta_db->update_meta( $post->ID, $meta_key, $meta_value );
1537
				}
1538
			}
1539
1540
			$logIDs[] = $post->ID;
1541
		}// End while().
1542
1543
		wp_reset_postdata();
1544
	} else {
1545
		// Delete terms and taxonomy.
1546
		$terms = get_terms( 'give_log_type', array( 'fields' => 'ids', 'hide_empty' => false ) );
1547
		if ( ! empty( $terms ) ) {
1548
			foreach ( $terms as $term ) {
1549
				wp_delete_term( $term, 'give_log_type' );
1550
			}
1551
		}
1552
1553
		// Delete logs.
1554
		$logIDs = get_posts( array(
1555
				'order'          => 'DESC',
1556
				'post_type'      => 'give_log',
1557
				'post_status'    => 'any',
1558
				'posts_per_page' => - 1,
1559
				'fields'         => 'ids',
1560
			)
1561
		);
1562
1563
		if ( ! empty( $logIDs ) ) {
1564
			foreach ( $logIDs as $log ) {
1565
				// Delete term relationship and posts.
1566
				wp_delete_object_term_relationships( $log, 'give_log_type' );
1567
				wp_delete_post( $log, true );
1568
			}
1569
		}
1570
1571
		unregister_taxonomy( 'give_log_type' );
1572
1573
		// Delete log cache.
1574
		Give()->logs->delete_cache();
1575
1576
		// No more forms found, finish up.
1577
		give_set_upgrade_complete( 'v20_logs_upgrades' );
1578
	}
1579
}
1580
1581
1582
/**
1583
 * Move payment and form metadata to new table
1584
 *
1585
 * @since  2.0
1586
 * @return void
1587
 */
1588
function give_v20_move_metadata_into_new_table_callback() {
1589
	global $wpdb;
1590
	$give_updates = Give_Updates::get_instance();
1591
1592
	// form query
1593
	$payments = new WP_Query( array(
1594
			'paged'          => $give_updates->step,
1595
			'status'         => 'any',
1596
			'order'          => 'ASC',
1597
			'post_type'      => array( 'give_forms', 'give_payment' ),
1598
			'posts_per_page' => 20,
1599
		)
1600
	);
1601
1602
	if ( $payments->have_posts() ) {
1603
		$give_updates->set_percentage( $payments->found_posts, $give_updates->step * 20 );
1604
1605
		while ( $payments->have_posts() ) {
1606
			$payments->the_post();
1607
			global $post;
1608
1609
			$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...
1610
				$wpdb->prepare(
1611
					"SELECT * FROM $wpdb->postmeta where post_id=%d",
1612
					get_the_ID()
1613
				),
1614
				ARRAY_A
1615
			);
1616
1617
			if ( ! empty( $meta_data ) ) {
1618
				foreach ( $meta_data as $index => $data ) {
1619
					switch ( $post->post_type ) {
1620 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...
1621
							$data['form_id'] = $data['post_id'];
1622
							unset( $data['post_id'] );
1623
1624
							Give()->form_meta->insert( $data );
1625
							delete_post_meta( get_the_ID(), $data['meta_key'] );
1626
1627
							break;
1628
1629 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...
1630
							$data['payment_id'] = $data['post_id'];
1631
							unset( $data['post_id'] );
1632
1633
							Give()->payment_meta->insert( $data );
1634
							delete_post_meta( get_the_ID(), $data['meta_key'] );
1635
1636
							break;
1637
					}
1638
				}
1639
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1640
1641
		}// End while().
1642
1643
		wp_reset_postdata();
1644
	} else {
1645
		// No more forms found, finish up.
1646
		give_set_upgrade_complete( 'v20_move_metadata_into_new_table' );
1647
	}
1648
1649
}
1650
1651
/**
1652
 * Upgrade routine for splitting donor name into first name and last name.
1653
 *
1654
 * @since 2.0
1655
 *
1656
 * @return void
1657
 */
1658
function give_v20_upgrades_donor_name() {
1659
	/* @var Give_Updates $give_updates */
1660
	$give_updates = Give_Updates::get_instance();
1661
1662
	$args = array(
1663
		'offset' => ( 1 === $give_updates->step ) ? 0 : $give_updates->step * 20,
1664
	);
1665
1666
	$donors = Give()->donors->get_donors( $args );
1667
1668
	if( $donors ) {
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...
1669
		$give_updates->set_percentage( count( $donors ), $give_updates->step * 20 );
1670
		// Loop through Donors
1671
		foreach ( $donors as $donor ) {
1672
1673
			$donor_name       = explode( ' ', $donor->name, 2 );
1674
			$donor_first_name = Give()->donor_meta->get_meta( $donor->id, '_give_donor_first_name' );
1675
			$donor_last_name  = Give()->donor_meta->get_meta( $donor->id, '_give_donor_last_name' );
1676
1677
			// If first name meta of donor is not created, then create it.
1678
			if( ! $donor_first_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...
1679
				Give()->donor_meta->add_meta( $donor->id, '_give_donor_first_name', $donor_name[0] );
1680
			}
1681
1682
			// If last name meta of donor is not created, then create it.
1683
			if( ! $donor_last_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...
1684
				Give()->donor_meta->add_meta( $donor->id, '_give_donor_last_name', $donor_name[1] );
1685
			}
1686
1687
			// If Donor is connected with WP User then update user meta.
1688
			if( $donor->user_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...
1689
				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...
1690
				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...
1691
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1692
1693
		}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1694
1695
	}else {
1696
		// The Update Ran.
1697
		give_set_upgrade_complete( 'v20_upgrades_donor_name' );
1698
	}
1699
1700
}
1701
1702
/**
1703
 * Upgrade routine for user addresses.
1704
 *
1705
 * @since 2.0
1706
 * @global wpdb $wpdb
1707
 *
1708
 * @return void
1709
 */
1710
function give_v20_upgrades_user_address() {
1711
	global $wpdb;
1712
1713
	/* @var Give_Updates $give_updates */
1714
	$give_updates = Give_Updates::get_instance();
1715
1716
	/* @var WP_User_Query $user_query */
1717
	$user_query = new WP_User_Query(
1718
		array(
1719
			'number' => 20,
1720
			'offset' => ( 1 === $give_updates->step ) ? 0 : $give_updates->step * 20
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
1721
		)
1722
	);
1723
1724
	$users = $user_query->get_results();
1725
1726
	if( $users ) {
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...
1727
		$give_updates->set_percentage( $user_query->get_total(), $give_updates->step * 20 );
1728
1729
		// Loop through Donors
1730
		foreach ( $users as $user ) {
1731
			/* @var Give_Donor $donor */
1732
			$donor = new Give_Donor( $user->ID, true );
1733
1734
			if( ! $donor->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...
1735
				continue;
1736
			}
1737
1738
			$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...
1739
				$wpdb->prepare(
1740
					"
1741
					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...
1742
					WHERE user_id=%s
1743
					AND meta_key=%s
1744
					",
1745
					$user->ID,
1746
					'_give_user_address'
1747
				)
1748
			);
1749
1750
			if( ! empty( $address ) ) {
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...
1751
				$address = maybe_unserialize( $address );
1752
				$donor->add_address( 'personal', $address );
1753
				$donor->add_address( 'billing[]', $address );
1754
				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...
1755
			}
1756
		}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1757
1758
	}else {
1759
		// The Update Ran.
1760
		give_set_upgrade_complete( 'v20_upgrades_user_address' );
1761
	}
1762
1763
}
1764
1765
/**
1766
 * Upgrade logs data.
1767
 *
1768
 * @since  2.0
1769
 * @global wpdb $wpdb
1770
 * @return void
1771
 */
1772
function give_v20_rename_donor_tables_callback() {
1773
	global $wpdb;
1774
1775
	/* @var Give_Updates $give_updates */
1776
	$give_updates = Give_Updates::get_instance();
1777
1778
	$tables = array(
1779
		"{$wpdb->prefix}give_customers"    => "{$wpdb->prefix}give_donors",
1780
		"{$wpdb->prefix}give_customermeta" => "{$wpdb->prefix}give_donormeta",
1781
	);
1782
1783
	// Alter customer table
1784
	foreach ( $tables as $old_table => $new_table ) {
1785
		if (
1786
			$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...
1787
			! $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...
1788
		) {
1789
			$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...
1790
1791
			if ( "{$wpdb->prefix}give_donormeta" === $new_table ) {
1792
				$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...
1793
			}
1794
		}
1795
	}
1796
1797
	$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...
1798
1799
	// No more forms found, finish up.
1800
	give_set_upgrade_complete( 'v20_rename_donor_tables' );
1801
1802
	// Re initiate donor classes.
1803
	Give()->donors     = new Give_DB_Donors();
1804
	Give()->donor_meta = new Give_DB_Donor_Meta();
1805
}