Test Failed
Push — issues/2531 ( 7bbe65...07c620 )
by Ravinder
04:34
created

upgrade-functions.php ➔ give_v1818_give_worker_role_cleanup()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 40
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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