Test Failed
Push — feature/update-process ( c4e2da...b3a362 )
by Ravinder
04:46
created

upgrade-functions.php ➔ give_v201_create_tables()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 16
nop 0
dl 0
loc 19
rs 8.8571
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;
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...
80
81
		case version_compare( $give_version, '2.0.1', '<' ) :
82
			give_v201_create_tables();
83
			Give_Updates::get_instance()->__health_background_update( Give_Updates::get_instance() );
84
			$did_upgrade = true;
85
	}
86
87
	if ( $did_upgrade ) {
88
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
89
	}
90
}
91
92
add_action( 'admin_init', 'give_do_automatic_upgrades' );
93
add_action( 'give_upgrades', 'give_do_automatic_upgrades' );
94
95
/**
96
 * Display Upgrade Notices.
97
 *
98
 * IMPORTANT: ALSO UPDATE INSTALL.PHP WITH THE ID OF THE UPGRADE ROUTINE SO IT DOES NOT AFFECT NEW INSTALLS.
99
 *
100
 * @since 1.0
101
 * @since 1.8.12 Update new update process code.
102
 *
103
 * @param Give_Updates $give_updates
104
 *
105
 * @return void
106
 */
107
function give_show_upgrade_notices( $give_updates ) {
108
	// v1.3.2 Upgrades
109
	$give_updates->register(
110
		array(
111
			'id'       => 'upgrade_give_payment_customer_id',
112
			'version'  => '1.3.2',
113
			'callback' => 'give_v132_upgrade_give_payment_customer_id',
114
		)
115
	);
116
117
	// v1.3.4 Upgrades ensure the user has gone through 1.3.4.
118
	$give_updates->register(
119
		array(
120
			'id'       => 'upgrade_give_offline_status',
121
			'depend'   => 'upgrade_give_payment_customer_id',
122
			'version'  => '1.3.4',
123
			'callback' => 'give_v134_upgrade_give_offline_status',
124
		)
125
	);
126
127
	// v1.8 form metadata upgrades.
128
	$give_updates->register(
129
		array(
130
			'id'       => 'v18_upgrades_form_metadata',
131
			'version'  => '1.8',
132
			'callback' => 'give_v18_upgrades_form_metadata',
133
		)
134
	);
135
136
	// v1.8.9 Upgrades
137
	$give_updates->register(
138
		array(
139
			'id'       => 'v189_upgrades_levels_post_meta',
140
			'version'  => '1.8.9',
141
			'callback' => 'give_v189_upgrades_levels_post_meta_callback',
142
		)
143
	);
144
145
	// v1.8.12 Upgrades
146
	$give_updates->register(
147
		array(
148
			'id'       => 'v1812_update_amount_values',
149
			'version'  => '1.8.12',
150
			'callback' => 'give_v1812_update_amount_values_callback',
151
		)
152
	);
153
154
	// v1.8.12 Upgrades
155
	$give_updates->register(
156
		array(
157
			'id'       => 'v1812_update_donor_purchase_values',
158
			'version'  => '1.8.12',
159
			'callback' => 'give_v1812_update_donor_purchase_value_callback',
160
		)
161
	);
162
163
	// v1.8.13 Upgrades for donor
164
	$give_updates->register(
165
		array(
166
			'id'       => 'v1813_update_donor_user_roles',
167
			'version'  => '1.8.13',
168
			'callback' => 'give_v1813_update_donor_user_roles_callback',
169
		)
170
	);
171
172
	// v1.8.17 Upgrades for donations.
173
	$give_updates->register( array(
174
		'id'       => 'v1817_update_donation_iranian_currency_code',
175
		'version'  => '1.8.17',
176
		'callback' => 'give_v1817_update_donation_iranian_currency_code',
177
	) );
178
179
	// v1.8.17 Upgrades for cleanup of user roles.
180
	$give_updates->register( array(
181
		'id'       => 'v1817_cleanup_user_roles',
182
		'version'  => '1.8.17',
183
		'callback' => 'give_v1817_cleanup_user_roles',
184
	) );
185
186
	// v1.8.18 Upgrades for assigning custom amount to existing set donations.
187
	$give_updates->register( array(
188
		'id'       => 'v1818_assign_custom_amount_set_donation',
189
		'version'  => '1.8.18',
190
		'callback' => 'give_v1818_assign_custom_amount_set_donation',
191
	) );
192
193
	// v1.8.18 Cleanup the Give Worker Role Caps.
194
	$give_updates->register( array(
195
		'id'       => 'v1818_give_worker_role_cleanup',
196
		'version'  => '1.8.18',
197
		'callback' => 'give_v1818_give_worker_role_cleanup',
198
	) );
199
200
	// v2.0.0 Upgrades
201
	$give_updates->register(
202
		array(
203
			'id'       => 'v20_upgrades_form_metadata',
204
			'version'  => '2.0.0',
205
			'callback' => 'give_v20_upgrades_form_metadata_callback',
206
		)
207
	);
208
209
	// v2.0.0 User Address Upgrades
210
	$give_updates->register(
211
		array(
212
			'id'       => 'v20_upgrades_user_address',
213
			'version'  => '2.0.0',
214
			'callback' => 'give_v20_upgrades_user_address',
215
		)
216
	);
217
218
	// v2.0.0 Upgrades
219
	$give_updates->register(
220
		array(
221
			'id'       => 'v20_upgrades_payment_metadata',
222
			'version'  => '2.0.0',
223
			'callback' => 'give_v20_upgrades_payment_metadata_callback',
224
		)
225
	);
226
227
	// v2.0.0 Upgrades
228
	$give_updates->register(
229
		array(
230
			'id'       => 'v20_logs_upgrades',
231
			'version'  => '2.0.0',
232
			'callback' => 'give_v20_logs_upgrades_callback',
233
234
		)
235
	);
236
237
	// v2.0.0 Donor Name Upgrades
238
	$give_updates->register(
239
		array(
240
			'id'       => 'v20_upgrades_donor_name',
241
			'version'  => '2.0.0',
242
			'callback' => 'give_v20_upgrades_donor_name',
243
		)
244
	);
245
246
	// v2.0.0 Upgrades
247
	$give_updates->register(
248
		array(
249
			'id'       => 'v20_move_metadata_into_new_table',
250
			'version'  => '2.0.0',
251
			'callback' => 'give_v20_move_metadata_into_new_table_callback',
252
			'depend'   => array( 'v20_upgrades_payment_metadata', 'v20_upgrades_form_metadata' ),
253
		)
254
	);
255
256
	// v2.0.0 Upgrades
257
	$give_updates->register(
258
		array(
259
			'id'       => 'v20_rename_donor_tables',
260
			'version'  => '2.0.0',
261
			'callback' => 'give_v20_rename_donor_tables_callback',
262
			'depend'   => array(
263
				'v20_move_metadata_into_new_table',
264
				'v20_logs_upgrades',
265
				'v20_upgrades_form_metadata',
266
				'v20_upgrades_payment_metadata',
267
				'v20_upgrades_user_address',
268
				'v20_upgrades_donor_name'
0 ignored issues
show
introduced by
Comma required after last value in array declaration
Loading history...
269
			),
270
		)
271
	);
272
273
	// Run v2.0.0 Upgrades again in 2.0.1
274
	$give_updates->register(
275
		array(
276
			'id'       => 'v201_move_metadata_into_new_table',
277
			'version'  => '2.0.1',
278
			'callback' => 'give_v201_move_metadata_into_new_table_callback',
279
		)
280
	);
281
282
	// Run v2.0.0 Upgrades again in 2.0.1
283
	$give_updates->register(
284
		array(
285
			'id'       => 'v201_logs_upgrades',
286
			'version'  => '2.0.1',
287
			'callback' => 'give_v201_logs_upgrades_callback',
288
289
		)
290
	);
291
}
292
293
add_action( 'give_register_updates', 'give_show_upgrade_notices' );
294
295
/**
296
 * Triggers all upgrade functions
297
 *
298
 * This function is usually triggered via AJAX
299
 *
300
 * @since 1.0
301
 * @return void
302
 */
303
function give_trigger_upgrades() {
304
305 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...
306
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
307
			'response' => 403,
308
		) );
309
	}
310
311
	$give_version = get_option( 'give_version' );
312
313
	if ( ! $give_version ) {
314
		// 1.0 is the first version to use this option so we must add it.
315
		$give_version = '1.0';
316
		add_option( 'give_version', $give_version );
317
	}
318
319
	update_option( 'give_version', GIVE_VERSION );
320
	delete_option( 'give_doing_upgrade' );
321
322
	if ( DOING_AJAX ) {
323
		die( 'complete' );
324
	} // End if().
325
}
326
327
add_action( 'wp_ajax_give_trigger_upgrades', 'give_trigger_upgrades' );
328
329
330
/**
331
 * Upgrades the
332
 *
333
 * Standardizes the discrepancies between two metakeys `_give_payment_customer_id` and `_give_payment_donor_id`
334
 *
335
 * @since      1.3.2
336
 */
337
function give_v132_upgrade_give_payment_customer_id() {
338
	global $wpdb;
339
340
	/* @var Give_Updates $give_updates */
341
	$give_updates = Give_Updates::get_instance();
342
343 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...
344
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
345
			'response' => 403,
346
		) );
347
	}
348
349
	give_ignore_user_abort();
350
351
	// UPDATE DB METAKEYS.
352
	$sql   = "UPDATE $wpdb->postmeta SET meta_key = '_give_payment_customer_id' WHERE meta_key = '_give_payment_donor_id'";
353
	$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...
354
355
	$give_updates->percentage = 100;
0 ignored issues
show
Documentation Bug introduced by
It seems like 100 of type integer is incompatible with the declared type array of property $percentage.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

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

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

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

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

<?php

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

print $doubleQuoted;

will print an indented: Single is Value

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

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

Loading history...
1935
						continue;
1936
					}
1937
					
1938
					switch ( $post->post_type ) {
1939
						case 'give_forms':
1940
							$data['form_id'] = $data['post_id'];
1941
							unset( $data['post_id'] );
1942
1943
							Give()->form_meta->insert( $data );
1944
							// @todo: delete form meta from post meta table after releases 2.0.
1945
							/*delete_post_meta( get_the_ID(), $data['meta_key'] );*/
1946
1947
							break;
1948
1949
						case 'give_payment':
1950
							$data['payment_id'] = $data['post_id'];
1951
							unset( $data['post_id'] );
1952
1953
							Give()->payment_meta->insert( $data );
1954
1955
							// @todo: delete donation meta from post meta table after releases 2.0.
1956
							/*delete_post_meta( get_the_ID(), $data['meta_key'] );*/
1957
1958
							break;
1959
					}
1960
				}
1961
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1962
1963
		}// End while().
1964
1965
		wp_reset_postdata();
1966
	} else {
1967
		// No more forms found, finish up.
1968
		give_set_upgrade_complete( 'v20_move_metadata_into_new_table' );
1969
	}
1970
1971
}
1972
1973
/**
1974
 * Upgrade routine for splitting donor name into first name and last name.
1975
 *
1976
 * @since 2.0
1977
 *
1978
 * @return void
1979
 */
1980
function give_v20_upgrades_donor_name() {
1981
	/* @var Give_Updates $give_updates */
1982
	$give_updates = Give_Updates::get_instance();
1983
1984
	$donors = Give()->donors->get_donors( array(
1985
		'paged'  => $give_updates->step,
1986
		'number' => 100,
1987
	) );
1988
1989
	if ( $donors ) {
1990
		$give_updates->set_percentage( count( $donors ), $give_updates->step * 100 );
1991
		// Loop through Donors
1992
		foreach ( $donors as $donor ) {
1993
1994
			$donor_name       = explode( ' ', $donor->name, 2 );
1995
			$donor_first_name = Give()->donor_meta->get_meta( $donor->id, '_give_donor_first_name' );
1996
			$donor_last_name  = Give()->donor_meta->get_meta( $donor->id, '_give_donor_last_name' );
1997
1998
			// If first name meta of donor is not created, then create it.
1999
			if ( ! $donor_first_name && isset( $donor_name[0] ) ) {
2000
				Give()->donor_meta->add_meta( $donor->id, '_give_donor_first_name', $donor_name[0] );
2001
			}
2002
2003
			// If last name meta of donor is not created, then create it.
2004
			if ( ! $donor_last_name && isset( $donor_name[1] ) ) {
2005
				Give()->donor_meta->add_meta( $donor->id, '_give_donor_last_name', $donor_name[1] );
2006
			}
2007
2008
			// If Donor is connected with WP User then update user meta.
2009
			if ( $donor->user_id ) {
2010
				if ( isset( $donor_name[0] ) ) {
2011
					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...
2012
				}
2013
				if ( isset( $donor_name[1] ) ) {
2014
					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...
2015
				}
2016
			}
2017
		}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
2018
2019
	} else {
2020
		// The Update Ran.
2021
		give_set_upgrade_complete( 'v20_upgrades_donor_name' );
2022
	}
2023
2024
}
2025
2026
/**
2027
 * Upgrade routine for user addresses.
2028
 *
2029
 * @since 2.0
2030
 * @global wpdb $wpdb
2031
 *
2032
 * @return void
2033
 */
2034
function give_v20_upgrades_user_address() {
2035
	global $wpdb;
2036
2037
	/* @var Give_Updates $give_updates */
2038
	$give_updates = Give_Updates::get_instance();
2039
2040
	/* @var WP_User_Query $user_query */
2041
	$user_query = new WP_User_Query(
2042
		array(
2043
			'number' => 100,
2044
			'paged'  => $give_updates->step,
2045
		)
2046
	);
2047
2048
	$users = $user_query->get_results();
2049
2050
	if ( $users ) {
2051
		$give_updates->set_percentage( $user_query->get_total(), $give_updates->step * 100 );
2052
2053
		// Loop through Donors
2054
		foreach ( $users as $user ) {
2055
			/* @var Give_Donor $donor */
2056
			$donor = new Give_Donor( $user->ID, true );
2057
2058
			if ( ! $donor->id ) {
2059
				continue;
2060
			}
2061
2062
			$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...
2063
				$wpdb->prepare(
2064
					"
2065
					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...
2066
					WHERE user_id=%s
2067
					AND meta_key=%s
2068
					",
2069
					$user->ID,
2070
					'_give_user_address'
2071
				)
2072
			);
2073
2074
			if ( ! empty( $address ) ) {
2075
				$address = maybe_unserialize( $address );
2076
				$donor->add_address( 'personal', $address );
2077
				$donor->add_address( 'billing[]', $address );
2078
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
2079
2080
				// @todo: delete _give_user_address from user meta after releases 2.0.
2081
				/*delete_user_meta( $user->ID, '_give_user_address' );*/
2082
			}
2083
		}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
2084
2085
	} else {
2086
		// The Update Ran.
2087
		give_set_upgrade_complete( 'v20_upgrades_user_address' );
2088
	}
2089
2090
}
2091
2092
/**
2093
 * Upgrade logs data.
2094
 *
2095
 * @since  2.0
2096
 * @global wpdb $wpdb
2097
 * @return void
2098
 */
2099
function give_v20_rename_donor_tables_callback() {
2100
	global $wpdb;
2101
2102
	/* @var Give_Updates $give_updates */
2103
	$give_updates = Give_Updates::get_instance();
2104
2105
	$tables = array(
2106
		"{$wpdb->prefix}give_customers"    => "{$wpdb->prefix}give_donors",
2107
		"{$wpdb->prefix}give_customermeta" => "{$wpdb->prefix}give_donormeta",
2108
	);
2109
2110
	// Alter customer table
2111
	foreach ( $tables as $old_table => $new_table ) {
2112
		if (
2113
			$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...
2114
			! $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...
2115
		) {
2116
			$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...
2117
2118
			if ( "{$wpdb->prefix}give_donormeta" === $new_table ) {
2119
				$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...
2120
			}
2121
		}
2122
	}
2123
2124
	$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...
2125
2126
	// No more forms found, finish up.
2127
	give_set_upgrade_complete( 'v20_rename_donor_tables' );
2128
2129
	// Re initiate donor classes.
2130
	Give()->donors     = new Give_DB_Donors();
2131
	Give()->donor_meta = new Give_DB_Donor_Meta();
2132
}
2133
2134
2135
/**
2136
 * Create missing meta tables.
2137
 *
2138
 * @since  2.0.1
2139
 * @global wpdb $wpdb
2140
 * @return void
2141
 */
2142
function give_v201_create_tables(){
2143
	global $wpdb;
2144
2145
	if ( ! $wpdb->query( $wpdb->prepare( "SHOW TABLES LIKE %s", "{$wpdb->prefix}give_paymentmeta" ) ) ) {
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...
2146
		Give()->payment_meta->create_table();
2147
	}
2148
2149
	if ( ! $wpdb->query( $wpdb->prepare( "SHOW TABLES LIKE %s", "{$wpdb->prefix}give_formmeta" ) ) ) {
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...
2150
		Give()->form_meta->create_table();
2151
	}
2152
2153
	if ( ! $wpdb->query( $wpdb->prepare( "SHOW TABLES LIKE %s", "{$wpdb->prefix}give_logs" ) ) ) {
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...
2154
		Give()->logs->log_db->create_table();
2155
	}
2156
2157
	if ( ! $wpdb->query( $wpdb->prepare( "SHOW TABLES LIKE %s", "{$wpdb->prefix}give_logmeta" ) ) ) {
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...
2158
		Give()->logs->logmeta_db->create_table();
2159
	}
2160
}
2161
2162
/**
2163
 * Move payment and form metadata to new table
2164
 *
2165
 * @since  2.0.1
2166
 * @return void
2167
 */
2168 View Code Duplication
function give_v201_move_metadata_into_new_table_callback() {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in 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...
2169
	global $wpdb;
2170
	$give_updates = Give_Updates::get_instance();
2171
2172
	// form query
2173
	$payments = new WP_Query( array(
2174
			'paged'          => $give_updates->step,
2175
			'status'         => 'any',
2176
			'order'          => 'ASC',
2177
			'post_type'      => array( 'give_forms', 'give_payment' ),
2178
			'posts_per_page' => 100,
0 ignored issues
show
introduced by
Detected high pagination limit, posts_per_page is set to 100
Loading history...
2179
		)
2180
	);
2181
2182
	if ( $payments->have_posts() ) {
2183
		$give_updates->set_percentage( $payments->found_posts, $give_updates->step * 100 );
2184
2185
		while ( $payments->have_posts() ) {
2186
			$payments->the_post();
2187
			global $post;
2188
2189
			$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...
2190
				$wpdb->prepare(
2191
					"SELECT * FROM $wpdb->postmeta where post_id=%d",
2192
					get_the_ID()
2193
				),
2194
				ARRAY_A
2195
			);
2196
2197
			if ( ! empty( $meta_data ) ) {
2198
				foreach ( $meta_data as $index => $data ) {
2199
					// Check for duplicate meta values.
2200
					if( $result = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM " . ( 'give_forms' === $post->post_type ? $wpdb->formmeta : $wpdb->paymentmeta ) .  " WHERE meta_id=%d", $data['meta_id'] ), ARRAY_A ) ) {
0 ignored issues
show
Unused Code introduced by
$result 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
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
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...
Coding Style Comprehensibility introduced by
The string literal SELECT * FROM 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...
Coding Style Comprehensibility introduced by
The string literal WHERE meta_id=%d 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...
2201
						continue;
2202
					}
2203
2204
					switch ( $post->post_type ) {
2205
						case 'give_forms':
2206
							$data['form_id'] = $data['post_id'];
2207
							unset( $data['post_id'] );
2208
2209
							Give()->form_meta->insert( $data );
2210
							// @todo: delete form meta from post meta table after releases 2.0.
2211
							/*delete_post_meta( get_the_ID(), $data['meta_key'] );*/
2212
2213
							break;
2214
2215
						case 'give_payment':
2216
							$data['payment_id'] = $data['post_id'];
2217
							unset( $data['post_id'] );
2218
2219
							Give()->payment_meta->insert( $data );
2220
2221
							// @todo: delete donation meta from post meta table after releases 2.0.
2222
							/*delete_post_meta( get_the_ID(), $data['meta_key'] );*/
2223
2224
							break;
2225
					}
2226
				}
2227
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
2228
2229
		}// End while().
2230
2231
		wp_reset_postdata();
2232
	} else {
2233
		// No more forms found, finish up.
2234
		give_set_upgrade_complete( 'v201_move_metadata_into_new_table' );
2235
	}
2236
2237
}
2238
2239
/**
2240
 * Move data to new log table.
2241
 *
2242
 * @since  2.0.1
2243
 * @return void
2244
 */
2245 View Code Duplication
function give_v201_logs_upgrades_callback() {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in 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...
2246
	global $wpdb;
2247
	$give_updates = Give_Updates::get_instance();
2248
2249
	// form query
2250
	$forms = new WP_Query( array(
2251
			'paged'          => $give_updates->step,
2252
			'order'          => 'DESC',
2253
			'post_type'      => 'give_log',
2254
			'post_status'    => 'any',
2255
			'posts_per_page' => 100,
0 ignored issues
show
introduced by
Detected high pagination limit, posts_per_page is set to 100
Loading history...
2256
		)
2257
	);
2258
2259
	if ( $forms->have_posts() ) {
2260
		$give_updates->set_percentage( $forms->found_posts, $give_updates->step * 100 );
2261
2262
		while ( $forms->have_posts() ) {
2263
			$forms->the_post();
2264
			global $post;
2265
2266
			if( $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}give_logs WHERE ID=%d", $post->ID ) ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
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...
2267
				continue;
2268
			}
2269
2270
			$term      = get_the_terms( $post->ID, 'give_log_type' );
2271
			$term      = ! is_wp_error( $term ) && ! empty( $term ) ? $term[0] : array();
2272
			$term_name = ! empty( $term ) ? $term->slug : '';
2273
2274
			$log_data = array(
2275
				'ID'           => $post->ID,
2276
				'log_title'    => $post->post_title,
2277
				'log_content'  => $post->post_content,
2278
				'log_parent'   => 0,
2279
				'log_type'     => $term_name,
2280
				'log_date'     => $post->post_date,
2281
				'log_date_gmt' => $post->post_date_gmt,
2282
			);
2283
			$log_meta = array();
2284
2285
			if ( $old_log_meta = get_post_meta( $post->ID ) ) {
2286
				foreach ( $old_log_meta as $meta_key => $meta_value ) {
2287
					switch ( $meta_key ) {
2288
						case '_give_log_payment_id':
2289
							$log_data['log_parent']        = current( $meta_value );
2290
							$log_meta['_give_log_form_id'] = $post->post_parent;
2291
							break;
2292
2293
						default:
2294
							$log_meta[ $meta_key ] = current( $meta_value );
2295
					}
2296
				}
2297
			}
2298
2299
			if ( 'api_request' === $term_name ) {
2300
				$log_meta['_give_log_api_query'] = $post->post_excerpt;
2301
			}
2302
2303
			$wpdb->insert( "{$wpdb->prefix}give_logs", $log_data );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
2304
2305
			if ( ! empty( $log_meta ) ) {
2306
				foreach ( $log_meta as $meta_key => $meta_value ) {
2307
					Give()->logs->logmeta_db->update_meta( $post->ID, $meta_key, $meta_value );
2308
				}
2309
			}
2310
2311
			$logIDs[] = $post->ID;
2312
		}// End while().
2313
2314
		wp_reset_postdata();
2315
	} else {
2316
		// Delete log cache.
2317
		Give()->logs->delete_cache();
2318
2319
		// No more forms found, finish up.
2320
		give_set_upgrade_complete( 'v201_logs_upgrades' );
2321
	}
2322
}