Test Failed
Push — feature/donor-tables ( 8c4924 )
by Ravinder
06:19
created

upgrade-functions.php ➔ give_v20_rename_donor_tables_callback()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 34
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 4
nop 0
dl 0
loc 34
rs 8.439
c 0
b 0
f 0
1
<?php
2
/**
3
 * Upgrade Functions
4
 *
5
 * @package     Give
6
 * @subpackage  Admin/Upgrades
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 * @since       1.0
10
 *
11
 * NOTICE: When adding new upgrade notices, please be sure to put the action into the upgrades array during install: /includes/install.php @ Appox Line 156
12
 */
13
14
// Exit if accessed directly.
15
if ( ! defined( 'ABSPATH' ) ) {
16
	exit;
17
}
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, '2.0', '<' ) :
66
			give_v20_upgrades();
67
			$did_upgrade = true;
68
	}
69
70
	if ( $did_upgrade ) {
71
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
72
	}
73
}
74
75
add_action( 'admin_init', 'give_do_automatic_upgrades' );
76
add_action( 'give_upgrades', 'give_do_automatic_upgrades' );
77
78
/**
79
 * Display Upgrade Notices
80
 *
81
 * @since 1.0
82
 * @since 1.8.12 Update new update process code.
83
 *
84
 * @param Give_Updates $give_updates
85
 *
86
 * @return void
87
 */
88
function give_show_upgrade_notices( $give_updates ) {
89
	// v1.3.2 Upgrades
90
	$give_updates->register(
91
		array(
92
			'id'       => 'upgrade_give_payment_customer_id',
93
			'version'  => '1.3.2',
94
			'callback' => 'give_v132_upgrade_give_payment_customer_id',
95
		)
96
	);
97
98
	// v1.3.4 Upgrades ensure the user has gone through 1.3.4.
99
	$give_updates->register(
100
		array(
101
			'id'       => 'upgrade_give_offline_status',
102
			'depend'   => 'upgrade_give_payment_customer_id',
103
			'version'  => '1.3.4',
104
			'callback' => 'give_v134_upgrade_give_offline_status',
105
		)
106
	);
107
108
	// v1.8 form metadata upgrades.
109
	$give_updates->register(
110
		array(
111
			'id'       => 'v18_upgrades_form_metadata',
112
			'version'  => '1.8',
113
			'callback' => 'give_v18_upgrades_form_metadata',
114
		)
115
	);
116
117
	// v1.8.9 Upgrades
118
	$give_updates->register(
119
		array(
120
			'id'       => 'v189_upgrades_levels_post_meta',
121
			'version'  => '1.8.9',
122
			'callback' => 'give_v189_upgrades_levels_post_meta_callback',
123
		)
124
	);
125
126
	// v1.8.12 Upgrades
127
	$give_updates->register(
128
		array(
129
			'id'       => 'v1812_update_amount_values',
130
			'version'  => '1.8.12',
131
			'callback' => 'give_v1812_update_amount_values_callback',
132
		)
133
	);
134
135
	// v1.8.12 Upgrades
136
	$give_updates->register(
137
		array(
138
			'id'       => 'v1812_update_donor_purchase_values',
139
			'version'  => '1.8.12',
140
			'callback' => 'give_v1812_update_donor_purchase_value_callback',
141
		)
142
	);
143
144
	// v2.0.0 Upgrades
145
	$give_updates->register(
146
		array(
147
			'id'       => 'v20_upgrades_form_metadata',
148
			'version'  => '2.0.0',
149
			'callback' => 'give_v20_upgrades_form_metadata_callback',
150
		)
151
	);
152
153
	// v2.0.0 Upgrades
154
	$give_updates->register(
155
		array(
156
			'id'       => 'v20_logs_upgrades',
157
			'version'  => '2.0.0',
158
			'callback' => 'give_v20_logs_upgrades_callback',
159
		)
160
	);
161
162
	// v2.0.0 Upgrades
163
	$give_updates->register(
164
		array(
165
			'id'       => 'v20_move_metadata_into_new_table',
166
			'version'  => '2.0.0',
167
			'callback' => 'give_v20_move_metadata_into_new_table_callback',
168
		)
169
	);
170
171
	// v2.0.0 Upgrades
172
	$give_updates->register(
173
		array(
174
			'id'       => 'v20_rename_donor_tables',
175
			'version'  => '2.0.0',
176
			'callback' => 'give_v20_rename_donor_tables_callback',
177
			'depend' => array( 'v20_move_metadata_into_new_table', 'v20_logs_upgrades', 'v20_upgrades_form_metadata' )
178
		)
179
	);
180
}
181
182
add_action( 'give_register_updates', 'give_show_upgrade_notices' );
183
184
/**
185
 * Triggers all upgrade functions
186
 *
187
 * This function is usually triggered via AJAX
188
 *
189
 * @since 1.0
190
 * @return void
191
 */
192
function give_trigger_upgrades() {
193
194
	if ( ! current_user_can( 'manage_give_settings' ) ) {
195
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
196
			'response' => 403,
197
		) );
198
	}
199
200
	$give_version = get_option( 'give_version' );
201
202
	if ( ! $give_version ) {
203
		// 1.0 is the first version to use this option so we must add it.
204
		$give_version = '1.0';
205
		add_option( 'give_version', $give_version );
206
	}
207
208
	update_option( 'give_version', GIVE_VERSION );
209
	delete_option( 'give_doing_upgrade' );
210
211
	if ( DOING_AJAX ) {
212
		die( 'complete' );
213
	} // End if().
214
}
215
216
add_action( 'wp_ajax_give_trigger_upgrades', 'give_trigger_upgrades' );
217
218
219
/**
220
 * Upgrades the
221
 *
222
 * Standardizes the discrepancies between two metakeys `_give_payment_customer_id` and `_give_payment_donor_id`
223
 *
224
 * @since      1.3.2
225
 */
226
function give_v132_upgrade_give_payment_customer_id() {
227
	global $wpdb;
228
229
	/* @var Give_Updates $give_updates */
230
	$give_updates = Give_Updates::get_instance();
231
232
	if ( ! current_user_can( 'manage_give_settings' ) ) {
233
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array(
234
			'response' => 403,
235
		) );
236
	}
237
238
	ignore_user_abort( true );
239
240
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
241
		@set_time_limit( 0 );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
Coding Style introduced by
Silencing errors is discouraged
Loading history...
242
	}
243
244
	// UPDATE DB METAKEYS.
245
	$sql   = "UPDATE $wpdb->postmeta SET meta_key = '_give_payment_customer_id' WHERE meta_key = '_give_payment_donor_id'";
246
	$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...
247
248
	$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...
249
	give_set_upgrade_complete( 'upgrade_give_payment_customer_id' );
250
}
251
252
253
/**
254
 * Upgrades the Offline Status
255
 *
256
 * Reverses the issue where offline donations in "pending" status where inappropriately marked as abandoned
257
 *
258
 * @since      1.3.4
259
 */
260
function give_v134_upgrade_give_offline_status() {
261
	global $wpdb;
262
263
	/* @var Give_Updates $give_updates */
264
	$give_updates = Give_Updates::get_instance();
265
266
	// Get abandoned offline payments.
267
	$select = "SELECT ID FROM $wpdb->posts p ";
268
	$join   = "LEFT JOIN $wpdb->postmeta m ON p.ID = m.post_id ";
269
	$where  = "WHERE p.post_type = 'give_payment' ";
270
	$where  .= "AND ( p.post_status = 'abandoned' )";
271
	$where  .= "AND ( m.meta_key = '_give_payment_gateway' AND m.meta_value = 'offline' )";
272
273
	$sql            = $select . $join . $where;
274
	$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...
275
276
	foreach ( $found_payments as $payment ) {
277
278
		// Only change ones marked abandoned since our release last week because the admin may have marked some abandoned themselves.
279
		$modified_time = get_post_modified_time( 'U', false, $payment );
280
281
		// 1450124863 =  12/10/2015 20:42:25.
282
		if ( $modified_time >= 1450124863 ) {
283
284
			give_update_payment_status( $payment, 'pending' );
285
286
		}
287
	}
288
289
	$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...
290
	give_set_upgrade_complete( 'upgrade_give_offline_status' );
291
}
292
293
294
/**
295
 * Cleanup User Roles
296
 *
297
 * This upgrade routine removes unused roles and roles with typos
298
 *
299
 * @since      1.5.2
300
 */
301
function give_v152_cleanup_users() {
302
303
	$give_version = get_option( 'give_version' );
304
305
	if ( ! $give_version ) {
306
		// 1.0 is the first version to use this option so we must add it.
307
		$give_version = '1.0';
308
	}
309
310
	$give_version = preg_replace( '/[^0-9.].*/', '', $give_version );
311
312
	// v1.5.2 Upgrades
313
	if ( version_compare( $give_version, '1.5.2', '<' ) || ! give_has_upgrade_completed( 'upgrade_give_user_caps_cleanup' ) ) {
314
315
		// Delete all caps with "ss".
316
		// Also delete all unused "campaign" roles.
317
		$delete_caps = array(
318
			'delete_give_formss',
319
			'delete_others_give_formss',
320
			'delete_private_give_formss',
321
			'delete_published_give_formss',
322
			'read_private_forms',
323
			'edit_give_formss',
324
			'edit_others_give_formss',
325
			'edit_private_give_formss',
326
			'edit_published_give_formss',
327
			'publish_give_formss',
328
			'read_private_give_formss',
329
			'assign_give_campaigns_terms',
330
			'delete_give_campaigns',
331
			'delete_give_campaigns_terms',
332
			'delete_give_campaignss',
333
			'delete_others_give_campaignss',
334
			'delete_private_give_campaignss',
335
			'delete_published_give_campaignss',
336
			'edit_give_campaigns',
337
			'edit_give_campaigns_terms',
338
			'edit_give_campaignss',
339
			'edit_others_give_campaignss',
340
			'edit_private_give_campaignss',
341
			'edit_published_give_campaignss',
342
			'manage_give_campaigns_terms',
343
			'publish_give_campaignss',
344
			'read_give_campaigns',
345
			'read_private_give_campaignss',
346
			'view_give_campaigns_stats',
347
			'delete_give_paymentss',
348
			'delete_others_give_paymentss',
349
			'delete_private_give_paymentss',
350
			'delete_published_give_paymentss',
351
			'edit_give_paymentss',
352
			'edit_others_give_paymentss',
353
			'edit_private_give_paymentss',
354
			'edit_published_give_paymentss',
355
			'publish_give_paymentss',
356
			'read_private_give_paymentss',
357
		);
358
359
		global $wp_roles;
360
		foreach ( $delete_caps as $cap ) {
361
			foreach ( array_keys( $wp_roles->roles ) as $role ) {
362
				$wp_roles->remove_cap( $role, $cap );
363
			}
364
		}
365
366
		// Create Give plugin roles.
367
		$roles = new Give_Roles();
368
		$roles->add_roles();
369
		$roles->add_caps();
370
371
		// The Update Ran.
372
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
373
		give_set_upgrade_complete( 'upgrade_give_user_caps_cleanup' );
374
		delete_option( 'give_doing_upgrade' );
375
376
	}// End if().
377
378
}
379
380
add_action( 'admin_init', 'give_v152_cleanup_users' );
381
382
/**
383
 * 1.6 Upgrade routine to create the customer meta table.
384
 *
385
 * @since  1.6
386
 * @return void
387
 */
388
function give_v16_upgrades() {
389
	// Create the donor databases.
390
	$donors_db = new Give_DB_Donors();
391
	$donors_db->create_table();
392
	$donor_meta = new Give_DB_Donor_Meta();
393
	$donor_meta->create_table();
394
}
395
396
/**
397
 * 1.7 Upgrades.
398
 *
399
 * a. Update license api data for plugin addons.
400
 * b. Cleanup user roles.
401
 *
402
 * @since  1.7
403
 * @return void
404
 */
405
function give_v17_upgrades() {
406
	// Upgrade license data.
407
	give_v17_upgrade_addon_license_data();
408
	give_v17_cleanup_roles();
409
}
410
411
/**
412
 * Upgrade license data
413
 *
414
 * @since 1.7
415
 */
416
function give_v17_upgrade_addon_license_data() {
417
	$give_options = give_get_settings();
418
419
	$api_url = 'https://givewp.com/give-sl-api/';
420
421
	// Get addons license key.
422
	$addons = array();
423
	foreach ( $give_options as $key => $value ) {
424
		if ( false !== strpos( $key, '_license_key' ) ) {
425
			$addons[ $key ] = $value;
426
		}
427
	}
428
429
	// Bailout: We do not have any addon license data to upgrade.
430
	if ( empty( $addons ) ) {
431
		return false;
432
	}
433
434
	foreach ( $addons as $key => $addon_license ) {
435
436
		// Get addon shortname.
437
		$shortname = str_replace( '_license_key', '', $key );
438
439
		// Addon license option name.
440
		$addon_license_option_name = $shortname . '_license_active';
441
442
		// bailout if license is empty.
443
		if ( empty( $addon_license ) ) {
444
			delete_option( $addon_license_option_name );
445
			continue;
446
		}
447
448
		// Get addon name.
449
		$addon_name       = array();
450
		$addon_name_parts = explode( '_', str_replace( 'give_', '', $shortname ) );
451
		foreach ( $addon_name_parts as $name_part ) {
452
453
			// Fix addon name
454
			switch ( $name_part ) {
455
				case 'authorizenet' :
456
					$name_part = 'authorize.net';
457
					break;
458
			}
459
460
			$addon_name[] = ucfirst( $name_part );
461
		}
462
463
		$addon_name = implode( ' ', $addon_name );
464
465
		// Data to send to the API
466
		$api_params = array(
467
			'edd_action' => 'activate_license', // never change from "edd_" to "give_"!
468
			'license'    => $addon_license,
469
			'item_name'  => urlencode( $addon_name ),
470
			'url'        => home_url(),
471
		);
472
473
		// Call the API.
474
		$response = wp_remote_post(
475
			$api_url,
476
			array(
477
				'timeout'   => 15,
478
				'sslverify' => false,
479
				'body'      => $api_params,
480
			)
481
		);
482
483
		// Make sure there are no errors.
484
		if ( is_wp_error( $response ) ) {
485
			delete_option( $addon_license_option_name );
486
			continue;
487
		}
488
489
		// Tell WordPress to look for updates.
490
		set_site_transient( 'update_plugins', null );
491
492
		// Decode license data.
493
		$license_data = json_decode( wp_remote_retrieve_body( $response ) );
494
		update_option( $addon_license_option_name, $license_data );
495
	}// End foreach().
496
}
497
498
499
/**
500
 * Cleanup User Roles.
501
 *
502
 * This upgrade routine removes unused roles and roles with typos.
503
 *
504
 * @since      1.7
505
 */
506
function give_v17_cleanup_roles() {
507
508
	// Delete all caps with "_give_forms_" and "_give_payments_"
509
	// These roles have no usage; the proper is singular.
510
	$delete_caps = array(
511
		'view_give_forms_stats',
512
		'delete_give_forms_terms',
513
		'assign_give_forms_terms',
514
		'edit_give_forms_terms',
515
		'manage_give_forms_terms',
516
		'view_give_payments_stats',
517
		'manage_give_payments_terms',
518
		'edit_give_payments_terms',
519
		'assign_give_payments_terms',
520
		'delete_give_payments_terms',
521
	);
522
523
	global $wp_roles;
524
	foreach ( $delete_caps as $cap ) {
525
		foreach ( array_keys( $wp_roles->roles ) as $role ) {
526
			$wp_roles->remove_cap( $role, $cap );
527
		}
528
	}
529
530
	// Set roles again.
531
	$roles = new Give_Roles();
532
	$roles->add_roles();
533
	$roles->add_caps();
534
535
}
536
537
/**
538
 * 1.8 Upgrades.
539
 *
540
 * a. Upgrade checkbox settings to radio button settings.
541
 * a. Update form meta for new metabox settings.
542
 *
543
 * @since  1.8
544
 * @return void
545
 */
546
function give_v18_upgrades() {
547
	// Upgrade checkbox settings to radio button settings.
548
	give_v18_upgrades_core_setting();
549
}
550
551
/**
552
 * Upgrade core settings.
553
 *
554
 * @since  1.8
555
 * @return void
556
 */
557
function give_v18_upgrades_core_setting() {
558
	// Core settings which changes from checkbox to radio.
559
	$core_setting_names = array_merge(
560
		array_keys( give_v18_renamed_core_settings() ),
561
		array(
562
			'uninstall_on_delete',
563
			'scripts_footer',
564
			'test_mode',
565
			'email_access',
566
			'terms',
567
			'give_offline_donation_enable_billing_fields',
568
		)
569
	);
570
571
	// Bailout: If not any setting define.
572
	if ( $give_settings = get_option( 'give_settings' ) ) {
573
574
		$setting_changed = false;
575
576
		// Loop: check each setting field.
577
		foreach ( $core_setting_names as $setting_name ) {
578
			// New setting name.
579
			$new_setting_name = preg_replace( '/^(enable_|disable_)/', '', $setting_name );
580
581
			// Continue: If setting already set.
582
			if (
583
				array_key_exists( $new_setting_name, $give_settings )
584
				&& in_array( $give_settings[ $new_setting_name ], array( 'enabled', 'disabled' ) )
585
			) {
586
				continue;
587
			}
588
589
			// Set checkbox value to radio value.
590
			$give_settings[ $setting_name ] = ( ! empty( $give_settings[ $setting_name ] ) && 'on' === $give_settings[ $setting_name ] ? 'enabled' : 'disabled' );
591
592
			// @see https://github.com/WordImpress/Give/issues/1063
593
			if ( false !== strpos( $setting_name, 'disable_' ) ) {
594
595
				$give_settings[ $new_setting_name ] = ( give_is_setting_enabled( $give_settings[ $setting_name ] ) ? 'disabled' : 'enabled' );
596
			} elseif ( false !== strpos( $setting_name, 'enable_' ) ) {
597
598
				$give_settings[ $new_setting_name ] = ( give_is_setting_enabled( $give_settings[ $setting_name ] ) ? 'enabled' : 'disabled' );
599
			}
600
601
			// Tell bot to update core setting to db.
602
			if ( ! $setting_changed ) {
603
				$setting_changed = true;
604
			}
605
		}
606
607
		// Update setting only if they changed.
608
		if ( $setting_changed ) {
609
			update_option( 'give_settings', $give_settings );
610
		}
611
	}// End if().
612
613
	give_set_upgrade_complete( 'v18_upgrades_core_setting' );
614
}
615
616
/**
617
 * Upgrade form metadata for new metabox settings.
618
 *
619
 * @since  1.8
620
 * @return void
621
 */
622
function give_v18_upgrades_form_metadata() {
623
	/* @var Give_Updates $give_updates */
624
	$give_updates = Give_Updates::get_instance();
625
626
	// form query
627
	$forms = new WP_Query( array(
628
			'paged'          => $give_updates->step,
629
			'status'         => 'any',
630
			'order'          => 'ASC',
631
			'post_type'      => 'give_forms',
632
			'posts_per_page' => 20,
633
		)
634
	);
635
636
	if ( $forms->have_posts() ) {
637
		$give_updates->set_percentage( $forms->found_posts, ( $give_updates->step * 20 ) );
638
639
		while ( $forms->have_posts() ) {
640
			$forms->the_post();
641
642
			// Form content.
643
			// Note in version 1.8 display content setting split into display content and content placement setting.
644
			// You can delete _give_content_option in future
645
			$show_content = give_get_meta( get_the_ID(), '_give_content_option', true );
646
			if ( $show_content && ! give_get_meta( get_the_ID(), '_give_display_content', true ) ) {
647
				$field_value = ( 'none' !== $show_content ? 'enabled' : 'disabled' );
648
				give_update_meta( get_the_ID(), '_give_display_content', $field_value );
649
650
				$field_value = ( 'none' !== $show_content ? $show_content : 'give_pre_form' );
651
				give_update_meta( get_the_ID(), '_give_content_placement', $field_value );
652
			}
653
654
			// "Disable" Guest Donation. Checkbox
655
			// See: https://github.com/WordImpress/Give/issues/1470
656
			$guest_donation        = give_get_meta( get_the_ID(), '_give_logged_in_only', true );
657
			$guest_donation_newval = ( in_array( $guest_donation, array( 'yes', 'on' ) ) ? 'disabled' : 'enabled' );
658
			give_update_meta( get_the_ID(), '_give_logged_in_only', $guest_donation_newval );
659
660
			// Offline Donations
661
			// See: https://github.com/WordImpress/Give/issues/1579
662
			$offline_donation = give_get_meta( get_the_ID(), '_give_customize_offline_donations', true );
663
			if ( 'no' === $offline_donation ) {
664
				$offline_donation_newval = 'global';
665
			} elseif ( 'yes' === $offline_donation ) {
666
				$offline_donation_newval = 'enabled';
667
			} else {
668
				$offline_donation_newval = 'disabled';
669
			}
670
			give_update_meta( get_the_ID(), '_give_customize_offline_donations', $offline_donation_newval );
671
672
			// Convert yes/no setting field to enabled/disabled.
673
			$form_radio_settings = array(
674
				// Custom Amount.
675
				'_give_custom_amount',
676
677
				// Donation Gaol.
678
				'_give_goal_option',
679
680
				// Close Form.
681
				'_give_close_form_when_goal_achieved',
682
683
				// Term & conditions.
684
				'_give_terms_option',
685
686
				// Billing fields.
687
				'_give_offline_donation_enable_billing_fields_single',
688
			);
689
690
			foreach ( $form_radio_settings as $meta_key ) {
691
				// Get value.
692
				$field_value = give_get_meta( get_the_ID(), $meta_key, true );
693
694
				// Convert meta value only if it is in yes/no/none.
695
				if ( in_array( $field_value, array( 'yes', 'on', 'no', 'none' ) ) ) {
696
697
					$field_value = ( in_array( $field_value, array( 'yes', 'on' ) ) ? 'enabled' : 'disabled' );
698
					give_update_meta( get_the_ID(), $meta_key, $field_value );
699
				}
700
			}
701
		}// End while().
702
703
		wp_reset_postdata();
704
705
	} else {
706
		// No more forms found, finish up.
707
		give_set_upgrade_complete( 'v18_upgrades_form_metadata' );
708
	}
709
}
710
711
712
/**
713
 * Get list of core setting renamed in version 1.8.
714
 *
715
 * @since  1.8
716
 * @return array
717
 */
718
function give_v18_renamed_core_settings() {
719
	return array(
720
		'disable_paypal_verification' => 'paypal_verification',
721
		'disable_css'                 => 'css',
722
		'disable_welcome'             => 'welcome',
723
		'disable_forms_singular'      => 'forms_singular',
724
		'disable_forms_archives'      => 'forms_archives',
725
		'disable_forms_excerpt'       => 'forms_excerpt',
726
		'disable_form_featured_img'   => 'form_featured_img',
727
		'disable_form_sidebar'        => 'form_sidebar',
728
		'disable_admin_notices'       => 'admin_notices',
729
		'disable_the_content_filter'  => 'the_content_filter',
730
		'enable_floatlabels'          => 'floatlabels',
731
		'enable_categories'           => 'categories',
732
		'enable_tags'                 => 'tags',
733
	);
734
}
735
736
737
/**
738
 * Upgrade core settings.
739
 *
740
 * @since  1.8.7
741
 * @return void
742
 */
743
function give_v187_upgrades() {
744
	global $wpdb;
745
746
	/**
747
	 * Upgrade 1: Remove stat and cache transients.
748
	 */
749
	$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...
750
		$wpdb->prepare(
751
			"SELECT * FROM {$wpdb->options} where (option_name LIKE '%%%s%%' OR option_name LIKE '%%%s%%')",
752
			array(
753
				'_transient_give_stats_',
754
				'give_cache',
755
				'_transient_give_add_ons_feed',
756
				'_transient__give_ajax_works',
757
				'_transient_give_total_api_keys',
758
				'_transient_give_i18n_give_promo_hide',
759
				'_transient_give_contributors',
760
				'_transient_give_estimated_monthly_stats',
761
				'_transient_give_earnings_total',
762
				'_transient_give_i18n_give_',
763
				'_transient__give_installed',
764
				'_transient__give_activation_redirect',
765
				'_transient__give_hide_license_notices_shortly_',
766
				'give_income_total',
767
			)
768
		),
769
		1
770
	);
771
772
	// User related transients.
773
	$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...
774
		$wpdb->prepare(
775
			"SELECT user_id, meta_key
776
			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...
777
			WHERE meta_value=%s",
778
			'give_user_public_key'
779
		),
780
		ARRAY_A
781
	);
782
783
	if ( ! empty( $user_apikey_options ) ) {
784
		foreach ( $user_apikey_options as $user ) {
785
			$cached_options[] = '_transient_' . md5( 'give_api_user_' . $user['meta_key'] );
786
			$cached_options[] = '_transient_' . md5( 'give_api_user_public_key' . $user['user_id'] );
787
			$cached_options[] = '_transient_' . md5( 'give_api_user_secret_key' . $user['user_id'] );
788
		}
789
	}
790
791
	if ( ! empty( $cached_options ) ) {
792
		foreach ( $cached_options as $option ) {
793 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...
794
				case ( false !== strpos( $option, 'transient' ) ):
795
					$option = str_replace( '_transient_', '', $option );
796
					delete_transient( $option );
797
					break;
798
799
				default:
800
					delete_option( $option );
801
			}
802
		}
803
	}
804
}
805
806
/**
807
 * Update Capabilities for Give_Worker User Role.
808
 *
809
 * This upgrade routine will update access rights for Give_Worker User Role.
810
 *
811
 * @since      1.8.8
812
 */
813
function give_v188_upgrades() {
814
815
	global $wp_roles;
816
817
	// Get the role object.
818
	$give_worker = get_role( 'give_worker' );
819
820
	// A list of capabilities to add for give workers.
821
	$caps_to_add = array(
822
		'edit_posts',
823
		'edit_pages',
824
	);
825
826
	foreach ( $caps_to_add as $cap ) {
827
		// Add the capability.
828
		$give_worker->add_cap( $cap );
829
	}
830
831
}
832
833
/**
834
 * Update Post meta for minimum and maximum amount for multi level donation forms
835
 *
836
 * This upgrade routine adds post meta for give_forms CPT for multi level donation form.
837
 *
838
 * @since      1.8.9
839
 */
840
function give_v189_upgrades_levels_post_meta_callback() {
841
	/* @var Give_Updates $give_updates */
842
	$give_updates = Give_Updates::get_instance();
843
844
	// form query
845
	$donation_forms = new WP_Query( array(
846
			'paged'          => $give_updates->step,
847
			'status'         => 'any',
848
			'order'          => 'ASC',
849
			'post_type'      => 'give_forms',
850
			'posts_per_page' => 20,
851
		)
852
	);
853
854
	if ( $donation_forms->have_posts() ) {
855
		$give_updates->set_percentage( $donation_forms->found_posts, ( $give_updates->step * 20 ) );
856
857
		while ( $donation_forms->have_posts() ) {
858
			$donation_forms->the_post();
859
			$form_id = get_the_ID();
860
861
			// Remove formatting from _give_set_price
862
			update_post_meta(
863
				$form_id,
864
				'_give_set_price',
865
				give_sanitize_amount( get_post_meta( $form_id, '_give_set_price', true ) )
866
			);
867
868
			// Remove formatting from _give_custom_amount_minimum
869
			update_post_meta(
870
				$form_id,
871
				'_give_custom_amount_minimum',
872
				give_sanitize_amount( get_post_meta( $form_id, '_give_custom_amount_minimum', true ) )
873
			);
874
875
			// Bailout.
876
			if ( 'set' === get_post_meta( $form_id, '_give_price_option', true ) ) {
877
				continue;
878
			}
879
880
			$donation_levels = get_post_meta( $form_id, '_give_donation_levels', true );
881
882
			if ( ! empty( $donation_levels ) ) {
883
884
				foreach ( $donation_levels as $index => $donation_level ) {
885
					if ( isset( $donation_level['_give_amount'] ) ) {
886
						$donation_levels[ $index ]['_give_amount'] = give_sanitize_amount( $donation_level['_give_amount'] );
887
					}
888
				}
889
890
				update_post_meta( $form_id, '_give_donation_levels', $donation_levels );
891
892
				$donation_levels_amounts = wp_list_pluck( $donation_levels, '_give_amount' );
893
894
				$min_amount = min( $donation_levels_amounts );
895
				$max_amount = max( $donation_levels_amounts );
896
897
				// Set Minimum and Maximum amount for Multi Level Donation Forms
898
				give_update_meta( $form_id, '_give_levels_minimum_amount', $min_amount ? give_sanitize_amount( $min_amount ) : 0 );
899
				give_update_meta( $form_id, '_give_levels_maximum_amount', $max_amount ? give_sanitize_amount( $max_amount ) : 0 );
900
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
901
902
		}
903
904
		/* Restore original Post Data */
905
		wp_reset_postdata();
906
	} else {
907
		// The Update Ran.
908
		give_set_upgrade_complete( 'v189_upgrades_levels_post_meta' );
909
	}
910
911
}
912
913
914
/**
915
 * Give version 1.8.9 upgrades
916
 *
917
 * @since      1.8.9
918
 */
919
function give_v189_upgrades() {
920
	/**
921
	 * 1. Remove user license related notice show blocked ( Give_Notice will handle )
922
	 */
923
	global $wpdb;
924
925
	// Delete permanent notice blocker.
926
	$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...
927
		$wpdb->prepare(
928
			"
929
					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...
930
					WHERE meta_key
931
					LIKE '%%%s%%'
932
					",
933
			'_give_hide_license_notices_permanently'
934
		)
935
	);
936
937
	// Delete short notice blocker.
938
	$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...
939
		$wpdb->prepare(
940
			"
941
					DELETE FROM $wpdb->options
942
					WHERE option_name
943
					LIKE '%%%s%%'
944
					",
945
			'__give_hide_license_notices_shortly_'
946
		)
947
	);
948
}
949
950
/**
951
 * 2.0 Upgrades.
952
 *
953
 * @since  2.0
954
 * @return void
955
 */
956
function give_v20_upgrades() {
957
	// Upgrade email settings.
958
	give_v20_upgrades_email_setting();
959
}
960
961
/**
962
 * Move old email api settings to new email setting api for following emails:
963
 *    1. new offline donation         [This was hard coded]
964
 *    2. offline donation instruction
965
 *    3. new donation
966
 *    4. donation receipt
967
 *
968
 * @since 2.0
969
 */
970
function give_v20_upgrades_email_setting() {
971
	$all_setting = give_get_settings();
972
973
	// Bailout on fresh install.
974
	if ( empty( $all_setting ) ) {
975
		return;
976
	}
977
978
	$settings = array(
979
		'offline_donation_subject'      => 'offline-donation-instruction_email_subject',
980
		'global_offline_donation_email' => 'offline-donation-instruction_email_message',
981
		'donation_subject'              => 'donation-receipt_email_subject',
982
		'donation_receipt'              => 'donation-receipt_email_message',
983
		'donation_notification_subject' => 'new-donation_email_subject',
984
		'donation_notification'         => 'new-donation_email_message',
985
		'admin_notice_emails'           => array(
986
			'new-donation_recipient',
987
			'new-offline-donation_recipient',
988
			'new-donor-register_recipient',
989
		),
990
		'admin_notices'                 => 'new-donation_notification',
991
	);
992
993
	foreach ( $settings as $old_setting => $new_setting ) {
994
		// Do not update already modified
995
		if ( ! is_array( $new_setting ) ) {
996
			if ( array_key_exists( $new_setting, $all_setting ) || ! array_key_exists( $old_setting, $all_setting ) ) {
997
				continue;
998
			}
999
		}
1000
1001
		switch ( $old_setting ) {
1002
			case 'admin_notices':
1003
				$notification_status = give_get_option( $old_setting, 'disabled' );
1004
1005
				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 993 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...
1006
				give_delete_option( $old_setting );
1007
				break;
1008
1009
			// @todo: Delete this option later ( version > 2.0 ) because we need this for backward compatibility give_get_admin_notice_emails.
1010
			case 'admin_notice_emails':
1011
				$recipients = give_get_admin_notice_emails();
1012
1013
				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...
1014
					// bailout if setting already exist.
1015
					if ( array_key_exists( $setting, $all_setting ) ) {
1016
						continue;
1017
					}
1018
1019
					give_update_option( $setting, $recipients );
1020
				}
1021
				break;
1022
1023
			default:
1024
				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 993 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...
1025
				give_delete_option( $old_setting );
1026
		}
1027
	}
1028
}
1029
1030
1031
/**
1032
 * Give version 1.8.9 upgrades
1033
 *
1034
 * @since      1.8.9
1035
 */
1036
function give_v1812_upgrades() {
1037
	/**
1038
	 * Validate number format settings.
1039
	 */
1040
	$give_settings        = give_get_settings();
1041
	$give_setting_updated = false;
1042
1043
	if ( $give_settings['thousands_separator'] === $give_settings['decimal_separator'] ) {
1044
		$give_settings['number_decimals']   = 0;
1045
		$give_settings['decimal_separator'] = '';
1046
		$give_setting_updated               = true;
1047
1048
	} elseif ( empty( $give_settings['decimal_separator'] ) ) {
1049
		$give_settings['number_decimals'] = 0;
1050
		$give_setting_updated             = true;
1051
1052
	} elseif ( 6 < absint( $give_settings['number_decimals'] ) ) {
1053
		$give_settings['number_decimals'] = 5;
1054
		$give_setting_updated             = true;
1055
	}
1056
1057
	if ( $give_setting_updated ) {
1058
		update_option( 'give_settings', $give_settings );
1059
	}
1060
}
1061
1062
1063
/**
1064
 * Give version 1.8.12 update
1065
 *
1066
 * Standardized amount values to six decimal
1067
 *
1068
 * @see        https://github.com/WordImpress/Give/issues/1849#issuecomment-315128602
1069
 *
1070
 * @since      1.8.12
1071
 */
1072
function give_v1812_update_amount_values_callback() {
1073
	/* @var Give_Updates $give_updates */
1074
	$give_updates = Give_Updates::get_instance();
1075
1076
	// form query
1077
	$donation_forms = new WP_Query( array(
1078
			'paged'          => $give_updates->step,
1079
			'status'         => 'any',
1080
			'order'          => 'ASC',
1081
			'post_type'      => array( 'give_forms', 'give_payment' ),
1082
			'posts_per_page' => 20,
1083
		)
1084
	);
1085
	if ( $donation_forms->have_posts() ) {
1086
		$give_updates->set_percentage( $donation_forms->found_posts, ( $give_updates->step * 20 ) );
1087
1088
		while ( $donation_forms->have_posts() ) {
1089
			$donation_forms->the_post();
1090
			global $post;
1091
1092
			$meta = get_post_meta( $post->ID );
1093
1094
			switch ( $post->post_type ) {
1095
				case 'give_forms':
1096
					// _give_set_price
1097
					if( ! empty( $meta['_give_set_price'][0] ) ) {
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...
1098
						update_post_meta( $post->ID, '_give_set_price', give_sanitize_amount_for_db( $meta['_give_set_price'][0] ) );
1099
					}
1100
1101
					// _give_custom_amount_minimum
1102
					if( ! empty( $meta['_give_custom_amount_minimum'][0] ) ) {
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...
1103
						update_post_meta( $post->ID, '_give_custom_amount_minimum', give_sanitize_amount_for_db( $meta['_give_custom_amount_minimum'][0] ) );
1104
					}
1105
1106
					// _give_levels_minimum_amount
1107
					if( ! empty( $meta['_give_levels_minimum_amount'][0] ) ) {
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...
1108
						update_post_meta( $post->ID, '_give_levels_minimum_amount', give_sanitize_amount_for_db( $meta['_give_levels_minimum_amount'][0] ) );
1109
					}
1110
1111
					// _give_levels_maximum_amount
1112
					if( ! empty( $meta['_give_levels_maximum_amount'][0] ) ) {
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...
1113
						update_post_meta( $post->ID, '_give_levels_maximum_amount', give_sanitize_amount_for_db( $meta['_give_levels_maximum_amount'][0] ) );
1114
					}
1115
1116
					// _give_set_goal
1117
					if( ! empty( $meta['_give_set_goal'][0] ) ) {
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...
1118
						update_post_meta( $post->ID, '_give_set_goal', give_sanitize_amount_for_db( $meta['_give_set_goal'][0] ) );
1119
					}
1120
1121
					// _give_form_earnings
1122
					if( ! empty( $meta['_give_form_earnings'][0] ) ) {
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...
1123
						update_post_meta( $post->ID, '_give_form_earnings', give_sanitize_amount_for_db( $meta['_give_form_earnings'][0] ) );
1124
					}
1125
1126
					// _give_custom_amount_minimum
1127
					if( ! empty( $meta['_give_donation_levels'][0] ) ) {
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...
1128
						$donation_levels = unserialize( $meta['_give_donation_levels'][0] );
1129
1130
						foreach( $donation_levels as $index => $level ) {
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...
1131
							if( empty( $level['_give_amount'] ) ) {
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...
1132
								continue;
1133
							}
1134
1135
							$donation_levels[$index]['_give_amount'] = give_sanitize_amount_for_db( $level['_give_amount'] );
0 ignored issues
show
introduced by
Array keys should be surrounded by spaces unless they contain a string or an integer.
Loading history...
1136
						}
1137
1138
						$meta['_give_donation_levels'] = $donation_levels;
1139
						update_post_meta( $post->ID, '_give_donation_levels', $meta['_give_donation_levels'] );
1140
					}
1141
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1142
1143
					break;
1144
1145
				case 'give_payment':
1146
					// _give_payment_total
1147
					if( ! empty( $meta['_give_payment_total'][0] ) ) {
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...
1148
						update_post_meta( $post->ID, '_give_payment_total', give_sanitize_amount_for_db( $meta['_give_payment_total'][0] ) );
1149
					}
1150
1151
					break;
1152
			}
1153
		}
1154
1155
		/* Restore original Post Data */
1156
		wp_reset_postdata();
1157
	} else {
1158
		// The Update Ran.
1159
		give_set_upgrade_complete( 'v1812_update_amount_values' );
1160
	}
1161
}
1162
1163
1164
/**
1165
 * Give version 1.8.12 update
1166
 *
1167
 * Standardized amount values to six decimal for donor
1168
 *
1169
 * @see        https://github.com/WordImpress/Give/issues/1849#issuecomment-315128602
1170
 *
1171
 * @since      1.8.12
1172
 */
1173
function give_v1812_update_donor_purchase_value_callback() {
1174
	/* @var Give_Updates $give_updates */
1175
	$give_updates = Give_Updates::get_instance();
1176
	$offset       = 1 === $give_updates->step ? 0 : $give_updates->step * 20;
1177
1178
	// form query
1179
	$donors = Give()->donors->get_donors( array(
1180
			'number' => 20,
1181
			'offset' => $offset,
1182
		)
1183
	);
1184
1185
	if ( ! empty( $donors ) ) {
1186
		$give_updates->set_percentage( Give()->donors->count(), $offset );
1187
1188
		/* @var Object $donor */
1189
		foreach ( $donors as $donor ) {
1190
			Give()->donors->update( $donor->id, array( 'purchase_value' => give_sanitize_amount_for_db( $donor->purchase_value ) ) );
1191
		}
1192
	} else {
1193
		// The Update Ran.
1194
		give_set_upgrade_complete( 'v1812_update_donor_purchase_values' );
1195
	}
1196
}
1197
1198
/**
1199
 * Upgrade form metadata for new metabox settings.
1200
 *
1201
 * @since  2.0
1202
 * @return void
1203
 */
1204
function give_v20_upgrades_form_metadata_callback() {
1205
	$give_updates = Give_Updates::get_instance();
1206
1207
	// form query
1208
	$forms = new WP_Query( array(
1209
			'paged'          => $give_updates->step,
1210
			'status'         => 'any',
1211
			'order'          => 'ASC',
1212
			'post_type'      => 'give_forms',
1213
			'posts_per_page' => 20,
1214
		)
1215
	);
1216
1217
	if ( $forms->have_posts() ) {
1218
		$give_updates->set_percentage( $forms->found_posts, ( $give_updates->step * 20 ) );
1219
1220
		while ( $forms->have_posts() ) {
1221
			$forms->the_post();
1222
1223
			// Update offline instruction email notification status.
1224
			$offline_instruction_notification_status = get_post_meta( get_the_ID(), '_give_customize_offline_donations', true );
1225
			$offline_instruction_notification_status = give_is_setting_enabled( $offline_instruction_notification_status, array( 'enabled', 'global' ) )
0 ignored issues
show
Documentation introduced by
array('enabled', 'global') is of type array<integer,string,{"0":"string","1":"string"}>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1226
				? $offline_instruction_notification_status
1227
				: 'global';
1228
			update_post_meta( get_the_ID(), '_give_offline-donation-instruction_notification', $offline_instruction_notification_status );
1229
1230
			// Update offline instruction email message.
1231
			update_post_meta(
1232
				get_the_ID(),
1233
				'_give_offline-donation-instruction_email_message',
1234
				get_post_meta(
1235
					get_the_ID(),
1236
					// @todo: Delete this option later ( version > 2.0 ).
1237
					'_give_offline_donation_email',
1238
					true
1239
				)
1240
			);
1241
1242
			// Update offline instruction email subject.
1243
			update_post_meta(
1244
				get_the_ID(),
1245
				'_give_offline-donation-instruction_email_subject',
1246
				get_post_meta(
1247
					get_the_ID(),
1248
					// @todo: Delete this option later ( version > 2.0 ).
1249
					'_give_offline_donation_subject',
1250
					true
1251
				)
1252
			);
1253
1254
			// @todo add db upgrade for _give_payment_meta,_give_payment_customer_id, _give_payment_user_email, _give_payment_user_ip.
1255
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
1256
1257
		}// End while().
1258
1259
		wp_reset_postdata();
1260
	} else {
1261
		// No more forms found, finish up.
1262
		give_set_upgrade_complete( 'v20_upgrades_form_metadata' );
1263
	}
1264
1265
	//  delete _give_payment_user_id now we are getting user id from donor id.
1266
}
1267
1268
1269
/**
1270
 * Upgrade logs data.
1271
 *
1272
 * @since  2.0
1273
 * @return void
1274
 */
1275
function give_v20_logs_upgrades_callback() {
1276
	global $wpdb;
1277
	$give_updates = Give_Updates::get_instance();
1278
1279
	// form query
1280
	$forms = new WP_Query( array(
1281
			'paged'          => $give_updates->step,
1282
			'order'          => 'DESC',
1283
			'post_type'      => 'give_log',
1284
			'post_status'    => 'any',
1285
			'posts_per_page' => 20,
1286
		)
1287
	);
1288
1289
	if ( $forms->have_posts() ) {
1290
		$give_updates->set_percentage( $forms->found_posts, $give_updates->step * 20 );
1291
1292
		while ( $forms->have_posts() ) {
1293
			$forms->the_post();
1294
			global $post;
1295
			$term = get_the_terms( $post->ID, 'give_log_type' );
1296
			$term = ! is_wp_error( $term ) && ! empty( $term ) ? $term[0] : array();
1297
			$term_name = ! empty( $term )? $term->slug : '';
1298
1299
			$log_data = array(
1300
				'ID'           => $post->ID,
1301
				'log_title'    => $post->post_title,
1302
				'log_content'  => $post->post_content,
1303
				'log_parent'   => 0,
1304
				'log_type'     => $term_name,
1305
				'log_date'     => $post->post_date,
1306
				'log_date_gmt' => $post->post_date_gmt,
1307
			);
1308
			$log_meta = array();
1309
1310
			if( $old_log_meta = get_post_meta( $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...
1311
				foreach ( $old_log_meta as $meta_key => $meta_value ) {
1312
					switch ( $meta_key ) {
1313
						case '_give_log_payment_id':
1314
							$log_data['log_parent'] = current( $meta_value );
1315
							$log_meta['_give_log_form_id'] = $post->post_parent;
1316
							break;
1317
1318
						default:
1319
							$log_meta[$meta_key] = current(  $meta_value );
0 ignored issues
show
introduced by
Array keys should be surrounded by spaces unless they contain a string or an integer.
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 2 found
Loading history...
1320
					}
1321
				}
1322
			}
1323
1324
			if( 'api_request' === $term_name ){
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
1325
				$log_meta['_give_log_api_query'] = $post->post_excerpt;
1326
			}
1327
1328
			$wpdb->insert( "{$wpdb->prefix}give_logs", $log_data );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
1329
1330
			if( ! empty( $log_meta ) ) {
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...
1331
				foreach ( $log_meta as $meta_key => $meta_value ){
1332
					Give()->logs->logmeta_db->update_meta( $post->ID, $meta_key, $meta_value );
1333
				}
1334
			}
1335
1336
			$logIDs[] = $post->ID;
1337
		}// End while().
1338
1339
		wp_reset_postdata();
1340
	} else {
1341
		// Delete terms and taxonomy.
1342
		$terms = get_terms( 'give_log_type', array( 'fields' => 'ids', 'hide_empty' => false ) );
1343
		if( ! empty( $terms ) ) {
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...
1344
			foreach ( $terms as $term ) {
1345
				wp_delete_term( $term, 'give_log_type' );
1346
			}
1347
		}
1348
1349
		// Delete logs
1350
		$logIDs = get_posts( array(
1351
				'order'          => 'DESC',
1352
				'post_type'      => 'give_log',
1353
				'post_status'    => 'any',
1354
				'posts_per_page' => - 1,
1355
				'fields'         => 'ids',
1356
			)
1357
		);
1358
1359
		if ( ! empty( $logIDs ) ) {
1360
			foreach ( $logIDs as $log ) {
1361
				// Delete term relationship and posts.
1362
				wp_delete_object_term_relationships( $log, 'give_log_type' );
1363
				wp_delete_post( $log, true );
1364
			}
1365
		}
1366
1367
		unregister_taxonomy( 'give_log_type' );
1368
1369
		// Delete log cache.
1370
		Give()->logs->delete_cache();
1371
1372
		// No more forms found, finish up.
1373
		give_set_upgrade_complete( 'v20_logs_upgrades' );
1374
	}
1375
}
1376
1377
/**
1378
 * Move payment and form metadata to new table
1379
 *
1380
 * @since  2.0
1381
 * @return void
1382
 */
1383
function give_v20_move_metadata_into_new_table_callback() {
1384
	global $wpdb;
1385
	$give_updates = Give_Updates::get_instance();
1386
1387
	// form query
1388
	$payments = new WP_Query( array(
1389
			'paged'          => $give_updates->step,
1390
			'status'         => 'any',
1391
			'order'          => 'ASC',
1392
			'post_type'      => array( 'give_forms', 'give_payment' ),
1393
			'posts_per_page' => 20,
1394
		)
1395
	);
1396
1397
	if ( $payments->have_posts() ) {
1398
		$give_updates->set_percentage( $payments->found_posts, $give_updates->step * 20 );
1399
1400
		while ( $payments->have_posts() ) {
1401
			$payments->the_post();
1402
			global $post;
1403
1404
			$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...
1405
				$wpdb->prepare(
1406
					"SELECT * FROM $wpdb->postmeta where post_id=%d",
1407
					get_the_ID()
1408
				),
1409
				ARRAY_A
1410
			);
1411
1412
			if ( ! empty( $meta_data ) ) {
1413
				foreach ( $meta_data as $index => $data ) {
1414
					switch ( $post->post_type ) {
1415 View Code Duplication
						case 'give_forms':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1416
							$data['form_id'] = $data['post_id'];
1417
							unset( $data['post_id'] );
1418
1419
							Give()->form_meta->insert( $data );
1420
							delete_post_meta( get_the_ID(), $data['meta_key'] );
1421
1422
							break;
1423
1424 View Code Duplication
						case 'give_payment':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1425
							$data['payment_id'] = $data['post_id'];
1426
							unset( $data['post_id'] );
1427
1428
							Give()->payment_meta->insert( $data );
1429
							delete_post_meta( get_the_ID(), $data['meta_key'] );
1430
1431
							break;
1432
					}
1433
				}
1434
			}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
1435
1436
		}// End while().
1437
1438
		wp_reset_postdata();
1439
	} else {
1440
		// No more forms found, finish up.
1441
		give_set_upgrade_complete( 'v20_move_metadata_into_new_table' );
1442
	}
1443
}
1444
1445
1446
/**
1447
 * Upgrade logs data.
1448
 *
1449
 * @since  2.0
1450
 * @global wpdb $wpdb
1451
 * @return void
1452
 */
1453
function give_v20_rename_donor_tables_callback() {
1454
	global $wpdb;
1455
1456
	/* @var Give_Updates $give_updates */
1457
	$give_updates = Give_Updates::get_instance();
1458
1459
	$tables = array(
1460
		"{$wpdb->prefix}give_customers"    => "{$wpdb->prefix}give_donors",
1461
		"{$wpdb->prefix}give_customermeta" => "{$wpdb->prefix}give_donormeta",
1462
	);
1463
1464
	// Alter customer table
1465
	foreach ( $tables as $old_table => $new_table ) {
1466
		if (
1467
			$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...
1468
			! $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...
1469
		) {
1470
			$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...
1471
1472
			if( "{$wpdb->prefix}give_donormeta" === $new_table ) {
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...
1473
				$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...
1474
			}
1475
		}
1476
	}
1477
1478
	$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...
1479
1480
	// No more forms found, finish up.
1481
	give_set_upgrade_complete( 'v20_rename_donor_tables' );
1482
1483
	// Re initiate donor classes.
1484
	Give()->donors     = new Give_DB_Donors();
1485
	Give()->donor_meta = new Give_DB_Donor_Meta();
1486
}
1487
1488