Test Failed
Push — issues/1944 ( f13954...e5d7bc )
by Ravinder
05:26
created

upgrade-functions.php ➔ give_v1818_upgrades()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Upgrade Functions
4
 *
5
 * @package     Give
6
 * @subpackage  Admin/Upgrades
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 * @since       1.0
10
 *
11
 * NOTICE: When adding new upgrade notices, please be sure to put the action into the upgrades array during install:
12
 * /includes/install.php @ Appox Line 156
13
 */
14
15
// Exit if accessed directly.
16
if ( ! defined( 'ABSPATH' ) ) {
17
	exit;
18
}
19
20
/**
21
 * Perform automatic database upgrades when necessary.
22
 *
23
 * @since  1.6
24
 * @return void
25
 */
26
function give_do_automatic_upgrades() {
27
	$did_upgrade  = false;
28
	$give_version = preg_replace( '/[^0-9.].*/', '', get_option( 'give_version' ) );
29
30
	if ( ! $give_version ) {
31
		// 1.0 is the first version to use this option so we must add it.
32
		$give_version = '1.0';
33
	}
34
35
	switch ( true ) {
36
37
		case version_compare( $give_version, '1.6', '<' ) :
38
			give_v16_upgrades();
39
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
40
41
		case version_compare( $give_version, '1.7', '<' ) :
42
			give_v17_upgrades();
43
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
44
45
		case version_compare( $give_version, '1.8', '<' ) :
46
			give_v18_upgrades();
47
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
48
49
		case version_compare( $give_version, '1.8.7', '<' ) :
50
			give_v187_upgrades();
51
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
52
53
		case version_compare( $give_version, '1.8.8', '<' ) :
54
			give_v188_upgrades();
55
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
56
57
		case version_compare( $give_version, '1.8.9', '<' ) :
58
			give_v189_upgrades();
59
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
60
61
		case version_compare( $give_version, '1.8.12', '<' ) :
62
			give_v1812_upgrades();
63
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
64
65
		case version_compare( $give_version, '1.8.13', '<' ) :
66
			give_v1813_upgrades();
67
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
68
69
		case version_compare( $give_version, '1.8.17', '<' ) :
70
			give_v1817_upgrades();
71
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
72
73
		case version_compare( $give_version, '1.8.18', '<' ) :
74
			give_v1818_upgrades();
75
			$did_upgrade = true;
0 ignored issues
show
Unused Code introduced by
$did_upgrade is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

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