Test Failed
Push — issues/1944 ( 647dde...ea2ff6 )
by Ravinder
04:42
created

upgrade-functions.php ➔ give_v1818_assign_custom_amount_set_donation()   C

Complexity

Conditions 7
Paths 4

Size

Total Lines 45
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 25
nc 4
nop 0
dl 0
loc 45
rs 6.7272
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
 * @since 1.0
94
 * @since 1.8.12 Update new update process code.
95
 *
96
 * @param Give_Updates $give_updates
97
 *
98
 * @return void
99
 */
100
function give_show_upgrade_notices( $give_updates ) {
101
	// v1.3.2 Upgrades
102
	$give_updates->register(
103
		array(
104
			'id'       => 'upgrade_give_payment_customer_id',
105
			'version'  => '1.3.2',
106
			'callback' => 'give_v132_upgrade_give_payment_customer_id',
107
		)
108
	);
109
110
	// v1.3.4 Upgrades ensure the user has gone through 1.3.4.
111
	$give_updates->register(
112
		array(
113
			'id'       => 'upgrade_give_offline_status',
114
			'depend'   => 'upgrade_give_payment_customer_id',
115
			'version'  => '1.3.4',
116
			'callback' => 'give_v134_upgrade_give_offline_status',
117
		)
118
	);
119
120
	// v1.8 form metadata upgrades.
121
	$give_updates->register(
122
		array(
123
			'id'       => 'v18_upgrades_form_metadata',
124
			'version'  => '1.8',
125
			'callback' => 'give_v18_upgrades_form_metadata',
126
		)
127
	);
128
129
	// v1.8.9 Upgrades
130
	$give_updates->register(
131
		array(
132
			'id'       => 'v189_upgrades_levels_post_meta',
133
			'version'  => '1.8.9',
134
			'callback' => 'give_v189_upgrades_levels_post_meta_callback',
135
		)
136
	);
137
138
	// v1.8.12 Upgrades
139
	$give_updates->register(
140
		array(
141
			'id'       => 'v1812_update_amount_values',
142
			'version'  => '1.8.12',
143
			'callback' => 'give_v1812_update_amount_values_callback',
144
		)
145
	);
146
147
	// v1.8.12 Upgrades
148
	$give_updates->register(
149
		array(
150
			'id'       => 'v1812_update_donor_purchase_values',
151
			'version'  => '1.8.12',
152
			'callback' => 'give_v1812_update_donor_purchase_value_callback',
153
		)
154
	);
155
156
	// v1.8.13 Upgrades for donor
157
	$give_updates->register(
158
		array(
159
			'id'       => 'v1813_update_donor_user_roles',
160
			'version'  => '1.8.13',
161
			'callback' => 'give_v1813_update_donor_user_roles_callback',
162
		)
163
	);
164
165
	// v1.8.17 Upgrades for donations.
166
	$give_updates->register( array(
167
		'id'       => 'v1817_update_donation_iranian_currency_code',
168
		'version'  => '1.8.17',
169
		'callback' => 'give_v1817_update_donation_iranian_currency_code',
170
	) );
171
172
	// v1.8.17 Upgrades for cleanup of user roles.
173
	$give_updates->register( array(
174
		'id'       => 'v1817_cleanup_user_roles',
175
		'version'  => '1.8.17',
176
		'callback' => 'give_v1817_cleanup_user_roles',
177
	) );
178
179
	// v1.8.18 Upgrades for assigning custom amount to existing set donations.
180
	$give_updates->register( array(
181
		'id'       => 'v1818_assign_custom_amount_set_donation',
182
		'version'  => '1.8.18',
183
		'callback' => 'give_v1818_assign_custom_amount_set_donation',
184
	) );
185
186
	// v2.0.0 Upgrades
187
	$give_updates->register(
188
		array(
189
			'id'       => 'v20_upgrades_form_metadata',
190
			'version'  => '2.0.0',
191
			'callback' => 'give_v20_upgrades_form_metadata_callback',
192
		)
193
	);
194
195
	// v2.0.0 User Address Upgrades
196
	$give_updates->register(
197
		array(
198
			'id'       => 'v20_upgrades_user_address',
199
			'version'  => '2.0.0',
200
			'callback' => 'give_v20_upgrades_user_address',
201
		)
202
	);
203
204
	// v2.0.0 Upgrades
205
	$give_updates->register(
206
		array(
207
			'id'       => 'v20_upgrades_payment_metadata',
208
			'version'  => '2.0.0',
209
			'callback' => 'give_v20_upgrades_payment_metadata_callback',
210
		)
211
	);
212
213
	// v2.0.0 Upgrades
214
	$give_updates->register(
215
		array(
216
			'id'       => 'v20_logs_upgrades',
217
			'version'  => '2.0.0',
218
			'callback' => 'give_v20_logs_upgrades_callback',
219
220
		)
221
	);
222
223
	// v2.0.0 Donor Name Upgrades
224
	$give_updates->register(
225
		array(
226
			'id'       => 'v20_upgrades_donor_name',
227
			'version'  => '2.0.0',
228
			'callback' => 'give_v20_upgrades_donor_name',
229
		)
230
	);
231
232
	// v2.0.0 Upgrades
233
	$give_updates->register(
234
		array(
235
			'id'       => 'v20_move_metadata_into_new_table',
236
			'version'  => '2.0.0',
237
			'callback' => 'give_v20_move_metadata_into_new_table_callback',
238
			'depend'   => array( 'v20_upgrades_payment_metadata', 'v20_upgrades_form_metadata' ),
239
		)
240
	);
241
242
	// v2.0.0 Upgrades
243
	$give_updates->register(
244
		array(
245
			'id'       => 'v20_rename_donor_tables',
246
			'version'  => '2.0.0',
247
			'callback' => 'give_v20_rename_donor_tables_callback',
248
			'depend'   => array(
249
				'v20_move_metadata_into_new_table',
250
				'v20_logs_upgrades',
251
				'v20_upgrades_form_metadata',
252
				'v20_upgrades_payment_metadata',
253
				'v20_upgrades_user_address',
254
				'v20_upgrades_donor_name'
0 ignored issues
show
introduced by
Comma required after last value in array declaration
Loading history...
255
			),
256
		)
257
	);
258
}
259
260
add_action( 'give_register_updates', 'give_show_upgrade_notices' );
261
262
/**
263
 * Triggers all upgrade functions
264
 *
265
 * This function is usually triggered via AJAX
266
 *
267
 * @since 1.0
268
 * @return void
269
 */
270
function give_trigger_upgrades() {
271
272 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...
273
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
274
			'response' => 403,
275
		) );
276
	}
277
278
	$give_version = get_option( 'give_version' );
279
280
	if ( ! $give_version ) {
281
		// 1.0 is the first version to use this option so we must add it.
282
		$give_version = '1.0';
283
		add_option( 'give_version', $give_version );
284
	}
285
286
	update_option( 'give_version', GIVE_VERSION );
287
	delete_option( 'give_doing_upgrade' );
288
289
	if ( DOING_AJAX ) {
290
		die( 'complete' );
291
	} // End if().
292
}
293
294
add_action( 'wp_ajax_give_trigger_upgrades', 'give_trigger_upgrades' );
295
296
297
/**
298
 * Upgrades the
299
 *
300
 * Standardizes the discrepancies between two metakeys `_give_payment_customer_id` and `_give_payment_donor_id`
301
 *
302
 * @since      1.3.2
303
 */
304
function give_v132_upgrade_give_payment_customer_id() {
305
	global $wpdb;
306
307
	/* @var Give_Updates $give_updates */
308
	$give_updates = Give_Updates::get_instance();
309
310 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...
311
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
312
			'response' => 403,
313
		) );
314
	}
315
316
	ignore_user_abort( true );
317
318
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
319
		@set_time_limit( 0 );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

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