Completed
Pull Request — master (#986)
by Rami
20:36
created

upgrade-functions.php ➔ give_upgrade_addon_license_data()   C

Complexity

Conditions 9
Paths 27

Size

Total Lines 81
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 41
nc 27
nop 0
dl 0
loc 81
ccs 0
cts 0
cp 0
crap 90
rs 5.5727
c 1
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 27 and the first side effect is on line 17.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Upgrade Functions
4
 *
5
 * @package     Give
6
 * @subpackage  Admin/Upgrades
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     http://opensource.org/licenses/gpl-2.0.php 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
15
// Exit if accessed directly
16
if ( ! defined( 'ABSPATH' ) ) {
17
	exit;
18
}
19
20
21
/**
22
 * Perform automatic database upgrades when necessary
23
 *
24
 * @since 1.6
25
 * @return void
26
 */
27
function give_do_automatic_upgrades() {
28
	$did_upgrade  = false;
29
	$give_version = preg_replace( '/[^0-9.].*/', '', get_option( 'give_version' ) );
30
31
	if ( ! $give_version ) {
32
		// 1.0 is the first version to use this option so we must add it.
33
		$give_version = '1.0';
34
	}
35
36
	switch ( true ) {
37
38
		case version_compare( $give_version, '1.6', '<' ) :
39
			give_v16_upgrades();
40
			$did_upgrade = true;
41
42
		case version_compare( $give_version, '1.7', '<' ) :
43
			give_v17_upgrades();
44
			$did_upgrade = true;
45
	}
46
47
	if ( $did_upgrade ) {
48
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
49
	}
50
}
51
52
add_action( 'admin_init', 'give_do_automatic_upgrades' );
53
54
/**
55
 * Display Upgrade Notices
56
 *
57
 * @since 1.0
58
 * @return void
59
 */
60
function give_show_upgrade_notices() {
61
62
	if ( isset( $_GET['page'] ) && $_GET['page'] == 'give-upgrades' ) {
63
		return;
64
	} // Don't show notices on the upgrades page
65
66
	$give_version = get_option( 'give_version' );
67
68
	if ( ! $give_version ) {
69
		// 1.0 is the first version to use this option so we must add it
70
		$give_version = '1.0';
71
	}
72
73
	$give_version = preg_replace( '/[^0-9.].*/', '', $give_version );
74
75
	/*
76
	 *  NOTICE:
77
	 *
78
	 *  When adding new upgrade notices, please be sure to put the action into the upgrades array during install:
79
	 *  /includes/install.php @ Appox Line 156
80
	 *
81
	 */
82
83
	//v1.3.2 Upgrades
84
	if ( version_compare( $give_version, '1.3.2', '<' ) || ! give_has_upgrade_completed( 'upgrade_give_payment_customer_id' ) ) {
85
		printf(
86
		/* translators: %s: upgrade URL */
87
			'<div class="updated"><p>' . __( 'Give needs to upgrade the donor database, click <a href="%s">here</a> to start the upgrade.', 'give' ) . '</p></div>',
88
			esc_url( admin_url( 'index.php?page=give-upgrades&give-upgrade=upgrade_give_payment_customer_id' ) )
89
		);
90
	}
91
92
	//v1.3.4 Upgrades //ensure the user has gone through 1.3.4
93
	if ( version_compare( $give_version, '1.3.4', '<' ) || ( ! give_has_upgrade_completed( 'upgrade_give_offline_status' ) && give_has_upgrade_completed( 'upgrade_give_payment_customer_id' ) ) ) {
94
		printf(
95
		/* translators: %s: upgrade URL */
96
			'<div class="updated"><p>' . __( 'Give needs to upgrade the donations database, click <a href="%s">here</a> to start the upgrade.', 'give' ) . '</p></div>',
97
			esc_url( admin_url( 'index.php?page=give-upgrades&give-upgrade=upgrade_give_offline_status' ) )
98
		);
99
	}
100
101
102
	// End 'Stepped' upgrade process notices
103
104
105
}
106
107
add_action( 'admin_notices', 'give_show_upgrade_notices' );
108
109
/**
110
 * Triggers all upgrade functions
111
 *
112
 * This function is usually triggered via AJAX
113
 *
114
 * @since 1.0
115
 * @return void
116
 */
117 1
function give_trigger_upgrades() {
118
119
	if ( ! current_user_can( 'manage_give_settings' ) ) {
120
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array( 'response' => 403 ) );
121 1
	}
122
123 1
	$give_version = get_option( 'give_version' );
124
125
	if ( ! $give_version ) {
126
		// 1.0 is the first version to use this option so we must add it
127
		$give_version = '1.0';
128
		add_option( 'give_version', $give_version );
129
	}
130
131
	update_option( 'give_version', GIVE_VERSION );
132
133
	if ( DOING_AJAX ) {
134
		die( 'complete' );
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_trigger_upgrades() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
135
	} // Let AJAX know that the upgrade is complete
136
}
137
138 1
add_action( 'wp_ajax_give_trigger_upgrades', 'give_trigger_upgrades' );
139
140
/**
141
 * Check if the upgrade routine has been run for a specific action
142 1
 *
143 1
 * @since  1.0
144
 *
145
 * @param  string $upgrade_action The upgrade action to check completion for
146 1
 *
147
 * @return bool                   If the action has been added to the completed actions array
148 1
 */
149
function give_has_upgrade_completed( $upgrade_action = '' ) {
150
151
	if ( empty( $upgrade_action ) ) {
152
		return false;
153
	}
154
155
	$completed_upgrades = give_get_completed_upgrades();
156
157
	return in_array( $upgrade_action, $completed_upgrades );
158
159 1
}
160
161 1
/**
162
 * Adds an upgrade action to the completed upgrades array
163
 *
164
 * @since  1.0
165 1
 *
166
 * @param  string $upgrade_action The action to add to the completed upgrades array
167
 *
168
 * @return bool                   If the function was successfully added
169
 */
170
function give_set_upgrade_complete( $upgrade_action = '' ) {
171
172
	if ( empty( $upgrade_action ) ) {
173
		return false;
174
	}
175
176
	$completed_upgrades   = give_get_completed_upgrades();
177
	$completed_upgrades[] = $upgrade_action;
178
179
	// Remove any blanks, and only show uniques
180
	$completed_upgrades = array_unique( array_values( $completed_upgrades ) );
181
182
	return update_option( 'give_completed_upgrades', $completed_upgrades );
183
}
184
185
/**
186
 * Get's the array of completed upgrade actions
187
 *
188
 * @since  1.0
189
 * @return array The array of completed upgrades
190
 */
191
function give_get_completed_upgrades() {
192
193
	$completed_upgrades = get_option( 'give_completed_upgrades' );
194
195
	if ( false === $completed_upgrades ) {
196
		$completed_upgrades = array();
197
	}
198
199
	return $completed_upgrades;
200
201
}
202
203
/**
204
 * Upgrades the
205
 *
206
 * Standardizes the discrepancies between two metakeys `_give_payment_customer_id` and `_give_payment_donor_id`
207
 *
208
 * @since      1.3.2
209
 *
210
 */
211
function give_v132_upgrade_give_payment_customer_id() {
212
	global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
213
	if ( ! current_user_can( 'manage_give_settings' ) ) {
214
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array( 'response' => 403 ) );
215
	}
216
217
	ignore_user_abort( true );
218
219
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
220
		@set_time_limit( 0 );
221
	}
222
223
	//UPDATE DB METAKEYS
224
	$sql   = "UPDATE $wpdb->postmeta SET meta_key = '_give_payment_customer_id' WHERE meta_key = '_give_payment_donor_id'";
225
	$query = $wpdb->query( $sql );
226
227
	update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
228
	give_set_upgrade_complete( 'upgrade_give_payment_customer_id' );
229
	delete_option( 'give_doing_upgrade' );
230
	wp_redirect( admin_url() );
231
	exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_v132_upgrade_give_payment_customer_id() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
232
233
234
}
235
236
add_action( 'give_upgrade_give_payment_customer_id', 'give_v132_upgrade_give_payment_customer_id' );
237
238
/**
239
 * Upgrades the Offline Status
240
 *
241
 * Reverses the issue where offline donations in "pending" status where inappropriately marked as abandoned
242
 *
243
 * @since      1.3.4
244
 *
245
 */
246
function give_v134_upgrade_give_offline_status() {
247
248
	global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
249
250
	if ( ! current_user_can( 'manage_give_settings' ) ) {
251
		wp_die( esc_html__( 'You do not have permission to do Give upgrades.', 'give' ), esc_html__( 'Error', 'give' ), array( 'response' => 403 ) );
252
	}
253
254
	ignore_user_abort( true );
255
256
	if ( ! give_is_func_disabled( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
257
		@set_time_limit( 0 );
258
	}
259
260
	// Get abandoned offline payments
261
	$select = "SELECT ID FROM $wpdb->posts p ";
262
	$join   = "LEFT JOIN $wpdb->postmeta m ON p.ID = m.post_id ";
263
	$where  = "WHERE p.post_type = 'give_payment' ";
264
	$where .= "AND ( p.post_status = 'abandoned' )";
265
	$where .= "AND ( m.meta_key = '_give_payment_gateway' AND m.meta_value = 'offline' )";
266
267
	$sql            = $select . $join . $where;
268
	$found_payments = $wpdb->get_col( $sql );
269
270
271
	foreach ( $found_payments as $payment ) {
272
273
		//Only change ones marked abandoned since our release last week
274
		//because the admin may have marked some abandoned themselves
275
		$modified_time = get_post_modified_time( 'U', false, $payment );
276
277
		//1450124863 =  12/10/2015 20:42:25
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
278
		if ( $modified_time >= 1450124863 ) {
279
280
			give_update_payment_status( $payment, 'pending' );
281
282
		}
283
284
	}
285
286
	update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
287
	give_set_upgrade_complete( 'upgrade_give_offline_status' );
288
	delete_option( 'give_doing_upgrade' );
289
	wp_redirect( admin_url() );
290
	exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_v134_upgrade_give_offline_status() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
291
292
293
}
294
295
add_action( 'give_upgrade_give_offline_status', 'give_v134_upgrade_give_offline_status' );
296
297
/**
298
 * Cleanup User Roles
299
 *
300
 * This upgrade routine removes unused roles and roles with typos
301
 *
302
 * @since      1.5.2
303
 */
304
function give_v152_cleanup_users() {
305
306
	$give_version = get_option( 'give_version' );
307
308
	if ( ! $give_version ) {
309
		// 1.0 is the first version to use this option so we must add it
310
		$give_version = '1.0';
311
	}
312
313
	$give_version = preg_replace( '/[^0-9.].*/', '', $give_version );
314
315
	//v1.5.2 Upgrades
316
	if ( version_compare( $give_version, '1.5.2', '<' ) || ! give_has_upgrade_completed( 'upgrade_give_user_caps_cleanup' ) ) {
317
318
		//Delete all caps with "ss"
319
		//Also delete all unused "campaign" roles
320
		$delete_caps = array(
321
			'delete_give_formss',
322
			'delete_others_give_formss',
323
			'delete_private_give_formss',
324
			'delete_published_give_formss',
325
			'read_private_forms',
326
			'edit_give_formss',
327
			'edit_others_give_formss',
328
			'edit_private_give_formss',
329
			'edit_published_give_formss',
330
			'publish_give_formss',
331
			'read_private_give_formss',
332
			'assign_give_campaigns_terms',
333
			'delete_give_campaigns',
334
			'delete_give_campaigns_terms',
335
			'delete_give_campaignss',
336
			'delete_others_give_campaignss',
337
			'delete_private_give_campaignss',
338
			'delete_published_give_campaignss',
339
			'edit_give_campaigns',
340
			'edit_give_campaigns_terms',
341
			'edit_give_campaignss',
342
			'edit_others_give_campaignss',
343
			'edit_private_give_campaignss',
344
			'edit_published_give_campaignss',
345
			'manage_give_campaigns_terms',
346
			'publish_give_campaignss',
347
			'read_give_campaigns',
348
			'read_private_give_campaignss',
349
			'view_give_campaigns_stats',
350
			'delete_give_paymentss',
351
			'delete_others_give_paymentss',
352
			'delete_private_give_paymentss',
353
			'delete_published_give_paymentss',
354
			'edit_give_paymentss',
355
			'edit_others_give_paymentss',
356
			'edit_private_give_paymentss',
357
			'edit_published_give_paymentss',
358
			'publish_give_paymentss',
359
			'read_private_give_paymentss',
360
		);
361
362
		global $wp_roles;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
363
		foreach ( $delete_caps as $cap ) {
364
			foreach ( array_keys( $wp_roles->roles ) as $role ) {
365
				$wp_roles->remove_cap( $role, $cap );
366
			}
367
		}
368
369
		// Create Give plugin roles
370
		$roles = new Give_Roles();
371
		$roles->add_roles();
372
		$roles->add_caps();
373
374
		//The Update Ran
375
		update_option( 'give_version', preg_replace( '/[^0-9.].*/', '', GIVE_VERSION ) );
376
		give_set_upgrade_complete( 'upgrade_give_user_caps_cleanup' );
377
		delete_option( 'give_doing_upgrade' );
378
379
	}
380
381
}
382
383
add_action( 'admin_init', 'give_v152_cleanup_users' );
384
385
/**
386
 * 1.6 Upgrade routine to create the customer meta table.
387
 *
388
 * @since  1.6
389
 * @return void
390
 */
391
function give_v16_upgrades() {
392
	@Give()->customers->create_table();
393
	@Give()->customer_meta->create_table();
394
}
395
396
/**
397
 * 1.7 Upgrade.
398
 *   a. Update license api data for plugin addons.
399
 *
400
 * @since  1.7
401
 * @return void
402
 */
403
function give_v17_upgrades() {
404
	// Upgrade license data.
405
	give_upgrade_addon_license_data();
406
}
407
408
/**
409
 * Upgrade license data
410
 *
411
 * @since 1.7
412
 */
413
function give_upgrade_addon_license_data(){
414
    global $give_options;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
415
416
    $api_url = 'https://givewp.com/give-sl-api/';
417
418
    // Get addons license key.
419
    $addons = array();
420
    foreach ( $give_options as $key => $value ) {
421
        if( false !== strpos( $key, '_license_key' ) ) {
422
            $addons[$key] = $value;
423
        }
424
    }
425
426
    // Bailout: We do not have any addon license data to upgrade.
427
    if( empty( $addons ) ) {
428
        return false;
429
    }
430
    
431
    foreach ( $addons as $key => $addon_license ) {
432
433
        // Get addon shortname.
434
        $shortname = str_replace( '_license_key', '', $key );
435
436
        // Addon license option name.
437
        $addon_license_option_name = $shortname . '_license_active';
438
439
        // bailout if license is empty.
440
        if( empty( $addon_license ) ) {
441
            delete_option( $addon_license_option_name );
442
            continue;
443
        }
444
445
        // Get addon name.
446
        $addon_name = array();
447
        $addon_name_parts = explode( '_', str_replace( 'give_', '', $shortname ) );
448
        foreach ( $addon_name_parts as $name_part ) {
449
450
            // Fix addon name
451
            switch ( $name_part ) {
452
                case 'authorizenet' :
453
                    $name_part = 'authorize.net';
454
                    break;
455
            }
456
457
            $addon_name[] = ucfirst( $name_part );
458
        }
459
460
        $addon_name = implode( ' ', $addon_name );
461
462
        // Data to send to the API
463
        $api_params = array(
464
            'edd_action' => 'activate_license', //never change from "edd_" to "give_"!
465
            'license'    => $addon_license,
466
            'item_name'  => urlencode( $addon_name ),
467
            'url'        => home_url()
468
        );
469
470
        // Call the API
471
        $response = wp_remote_post(
472
            $api_url,
473
            array(
474
                'timeout'   => 15,
475
                'sslverify' => false,
476
                'body'      => $api_params
477
            )
478
        );
479
480
        // Make sure there are no errors
481
        if ( is_wp_error( $response ) ) {
482
            delete_option( $addon_license_option_name );
483
            continue;
484
        }
485
486
        // Tell WordPress to look for updates
487
        set_site_transient( 'update_plugins', null );
488
489
        // Decode license data
490
        $license_data = json_decode( wp_remote_retrieve_body( $response ) );
491
        update_option( $addon_license_option_name, $license_data );
492
    }
493
}