Test Failed
Push — master ( 76928d...4654fc )
by Devin
09:23
created

misc-functions.php ➔ give_license_key_callback()   F

Complexity

Conditions 35
Paths 10752

Size

Total Lines 226

Duplication

Lines 46
Ratio 20.35 %

Importance

Changes 0
Metric Value
cc 35
nc 10752
nop 2
dl 46
loc 226
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
2
3
/**
4
 * Gets a number of posts and displays them as options
5
 *
6
 * @param  array $query_args Optional. Overrides defaults.
7
 * @param  bool  $force      Force the pages to be loaded even if not on settings
8
 *
9
 * @see: https://github.com/WebDevStudios/CMB2/wiki/Adding-your-own-field-types
10
 * @return array An array of options that matches the CMB2 options array
11
 */
12
function give_cmb2_get_post_options( $query_args, $force = false ) {
13
14
	$post_options = array( '' => '' ); // Blank option
15
16
	if ( ( ! isset( $_GET['page'] ) || 'give-settings' != $_GET['page'] ) && ! $force ) {
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
17
		return $post_options;
18
	}
19
20
	$args = wp_parse_args(
21
		$query_args, array(
22
			'post_type'   => 'page',
23
			'numberposts' => 10,
24
		)
25
	);
26
27
	$posts = get_posts( $args );
28
29
	if ( $posts ) {
30
		foreach ( $posts as $post ) {
31
32
			$post_options[ $post->ID ] = $post->post_title;
33
34
		}
35
	}
36
37
	return $post_options;
38
}
39
40
41
/**
42
 * Featured Image Sizes
43
 *
44
 * Outputs an array for the "Featured Image Size" option found under Settings > Display Options.
45
 *
46
 * @since 1.4
47
 *
48
 * @global $_wp_additional_image_sizes
49
 *
50
 * @return array $sizes
51
 */
52
function give_get_featured_image_sizes() {
53
	global $_wp_additional_image_sizes;
54
55
	$sizes            = array();
56
	$get_sizes        = get_intermediate_image_sizes();
57
	$core_image_sizes = array( 'thumbnail', 'medium', 'medium_large', 'large' );
58
59
	// This will help us to filter special characters from a string
60
	$filter_slug_items = array( '_', '-' );
61
62
	foreach ( $get_sizes as $_size ) {
63
64
		// Converting image size slug to title case
65
		$sizes[ $_size ] = give_slug_to_title( $_size, $filter_slug_items );
66
67
		if ( in_array( $_size, $core_image_sizes ) ) {
68
			$sizes[ $_size ] .= ' (' . get_option( "{$_size}_size_w" ) . 'x' . get_option( "{$_size}_size_h" );
69
		} elseif ( isset( $_wp_additional_image_sizes[ $_size ] ) ) {
70
			$sizes[ $_size ] .= " ({$_wp_additional_image_sizes[ $_size ]['width']} x {$_wp_additional_image_sizes[ $_size ]['height']}";
71
		}
72
73
		// Based on the above image height check, label the respective resolution as responsive
74
		if ( ( array_key_exists( $_size, $_wp_additional_image_sizes ) && ! $_wp_additional_image_sizes[ $_size ]['crop'] ) || ( in_array( $_size, $core_image_sizes ) && ! get_option( "{$_size}_crop" ) ) ) {
75
			$sizes[ $_size ] .= ' - responsive';
76
		}
77
78
		$sizes[ $_size ] .= ')';
79
80
	}
81
82
	return apply_filters( 'give_get_featured_image_sizes', $sizes );
83
}
84
85
86
/**
87
 *  Slug to Title
88
 *
89
 *  Converts a string with hyphen(-) or underscores(_) or any special character to a string with Title case
90
 *
91
 * @since 1.8.8
92
 *
93
 * @param string $string
94
 * @param array  $filters
95
 *
96
 * @return string $string
97
 */
98
function give_slug_to_title( $string, $filters = array() ) {
99
100
	foreach ( $filters as $filter_item ) {
101
		$string = str_replace( $filter_item, ' ', $string );
102
	}
103
104
	// Return updated string after converting it to title case
105
	return ucwords( $string );
106
107
}
108
109
110
/**
111
 * Give License Key Callback
112
 *
113
 * Registers the license field callback for EDD's Software Licensing.
114
 *
115
 * @since       1.0
116
 * @since       2.0 Removed cmb2 param backward compatibility
117
 *
118
 * @param array $field
119
 * @param mixed $value
120
 *
121
 * @return void
122
 */
123
function give_license_key_callback( $field, $value ) {
124
	$id                 = $field['id'];
125
	$field_description  = $field['desc'];
126
	$license            = $field['options']['license'];
127
	$license_key        = $value;
128
	$is_license_key     = apply_filters( 'give_is_license_key', ( is_object( $license ) && ! empty( $license ) ) );
129
	$is_valid_license   = apply_filters( 'give_is_valid_license', ( $is_license_key && property_exists( $license, 'license' ) && 'valid' === $license->license ) );
130
	$shortname          = $field['options']['shortname'];
131
	$field_classes      = 'regular-text give-license-field';
132
	$type               = empty( $escaped_value ) || ! $is_valid_license ? 'text' : 'password';
133
	$custom_html        = '';
134
	$messages           = array();
135
	$class              = '';
0 ignored issues
show
Unused Code introduced by
$class 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...
136
	$account_page_link  = $field['options']['account_url'];
137
	$checkout_page_link = $field['options']['checkout_url'];
138
	$addon_name         = $field['options']['item_name'];
139
	$license_status     = null;
0 ignored issues
show
Unused Code introduced by
$license_status 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...
140
	$is_in_subscription = null;
141
142
	// By default query on edd api url will return license object which contain status and message property, this can break below functionality.
143
	// To combat that check if status is set to error or not, if yes then set $is_license_key to false.
144
	if ( $is_license_key && property_exists( $license, 'status' ) && 'error' === $license->status ) {
145
		$is_license_key = false;
146
	}
147
148
	// Check if current license is part of subscription or not.
149
	$subscriptions = get_option( 'give_subscriptions' );
150
151
	if ( $is_license_key && $subscriptions ) {
152
		foreach ( $subscriptions as $subscription ) {
153
			if ( in_array( $license_key, $subscription['licenses'] ) ) {
154
				$is_in_subscription = $subscription['id'];
155
				break;
156
			}
157
		}
158
	}
159
160
	if ( $is_license_key ) {
161
162
		if ( empty( $license->success ) && property_exists( $license, 'error' ) ) {
163
164
			// activate_license 'invalid' on anything other than valid, so if there was an error capture it
165
			switch ( $license->error ) {
166
				case 'expired':
167
					$class          = $license->error;
168
					$messages[]     = sprintf(
169
						__( 'Your license key expired on %1$s. Please <a href="%2$s" target="_blank" title="Renew your license key">renew your license key</a>.', 'give' ),
170
						date_i18n( get_option( 'date_format' ), strtotime( $license->expires, current_time( 'timestamp' ) ) ),
171
						$checkout_page_link . '?edd_license_key=' . $license_key . '&utm_campaign=admin&utm_source=licenses&utm_medium=expired'
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$license_key'
Loading history...
172
					);
173
					$license_status = 'license-' . $class;
174
					break;
175
176 View Code Duplication
				case 'missing':
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...
177
					$class          = $license->error;
178
					$messages[]     = sprintf(
179
						__( 'Invalid license. Please <a href="%s" target="_blank" title="Visit account page">visit your account page</a> and verify it.', 'give' ),
180
						$account_page_link . '?utm_campaign=admin&utm_source=licenses&utm_medium=missing'
181
					);
182
					$license_status = 'license-' . $class;
183
					break;
184
185 View Code Duplication
				case 'invalid':
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...
186
					$class          = $license->error;
187
					$messages[]     = sprintf(
188
						__( 'Your %1$s is not active for this URL. Please <a href="%2$s" target="_blank" title="Visit account page">visit your account page</a> to manage your license key URLs.', 'give' ),
189
						$addon_name,
190
						$account_page_link . '?utm_campaign=admin&utm_source=licenses&utm_medium=invalid'
191
					);
192
					$license_status = 'license-' . $class;
193
					break;
194
195 View Code Duplication
				case 'site_inactive':
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...
196
					$class          = $license->error;
197
					$messages[]     = sprintf(
198
						__( 'Your %1$s is not active for this URL. Please <a href="%2$s" target="_blank" title="Visit account page">visit your account page</a> to manage your license key URLs.', 'give' ),
199
						$addon_name,
200
						$account_page_link . '?utm_campaign=admin&utm_source=licenses&utm_medium=invalid'
201
					);
202
					$license_status = 'license-' . $class;
203
					break;
204
205 View Code Duplication
				case 'item_name_mismatch':
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...
206
					$class          = $license->error;
207
					$messages[]     = sprintf( __( 'This license %1$s does not belong to %2$s.', 'give' ), $license_key, $addon_name );
208
					$license_status = 'license-' . $class;
209
					break;
210
211 View Code Duplication
				case 'no_activations_left':
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...
212
					$class          = $license->error;
213
					$messages[]     = sprintf( __( 'Your license key has reached it\'s activation limit. <a href="%s">View possible upgrades</a> now.', 'give' ), $account_page_link );
214
					$license_status = 'license-' . $class;
215
					break;
216
217 View Code Duplication
				default:
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...
218
					$class          = $license->error;
0 ignored issues
show
Unused Code introduced by
$class 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...
219
					$messages[]     = sprintf(
220
						__( 'Your license is not activated. Please <a href="%3$s" target="_blank" title="Visit account page">visit your account page</a> to manage your license key URLs. %2$sError Code: %1$s.', 'give' ),
221
						$license->error,
222
						'<br/>',
223
						"{$account_page_link}?utm_campaign=admin&utm_source=licenses&utm_medium={$license->error}"
224
					);
225
					$license_status = 'license-error';
226
					break;
227
			}
228
		} elseif ( $is_in_subscription ) {
229
230
			$subscription_expires = strtotime( $subscriptions[ $is_in_subscription ]['expires'] );
231
			$subscription_status  = __( 'renew', 'give' );
232
233
			if ( ( 'active' !== $subscriptions[ $is_in_subscription ]['status'] ) ) {
234
				$subscription_status = __( 'expire', 'give' );
235
			}
236
237
			if ( $subscription_expires < current_time( 'timestamp', 1 ) ) {
238
				$messages[]     = sprintf(
239
					__( 'Your subscription (<a href="%1$s" target="_blank">#%2$d</a>) expired. Please <a href="%3$s" target="_blank" title="Renew your license key">renew your license key</a>', 'give' ),
240
					urldecode( $subscriptions[ $is_in_subscription ]['invoice_url'] ),
241
					$subscriptions[ $is_in_subscription ]['payment_id'],
242
					$checkout_page_link . '?edd_license_key=' . $subscriptions[ $is_in_subscription ]['license_key'] . '&utm_campaign=admin&utm_source=licenses&utm_medium=expired'
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$subscriptions'
Loading history...
243
				);
244
				$license_status = 'license-expired';
245
			} elseif ( strtotime( '- 7 days', $subscription_expires ) < current_time( 'timestamp', 1 ) ) {
246
				$messages[]     = sprintf(
247
					__( 'Your subscription (<a href="%1$s" target="_blank">#%2$d</a>) will %3$s in %4$s.', 'give' ),
248
					urldecode( $subscriptions[ $is_in_subscription ]['invoice_url'] ),
249
					$subscriptions[ $is_in_subscription ]['payment_id'],
250
					$subscription_status,
251
					human_time_diff( current_time( 'timestamp', 1 ), strtotime( $subscriptions[ $is_in_subscription ]['expires'] ) )
252
				);
253
				$license_status = 'license-expires-soon';
254
			} else {
255
				$messages[]     = sprintf(
256
					__( 'Your subscription (<a href="%1$s" target="_blank">#%2$d</a>) will %3$s on %4$s.', 'give' ),
257
					urldecode( $subscriptions[ $is_in_subscription ]['invoice_url'] ),
258
					$subscriptions[ $is_in_subscription ]['payment_id'],
259
					$subscription_status,
260
					date_i18n( get_option( 'date_format' ), strtotime( $subscriptions[ $is_in_subscription ]['expires'], current_time( 'timestamp' ) ) )
261
				);
262
				$license_status = 'license-expiration-date';
263
			}
264
		} elseif ( empty( $license->success ) ) {
265
			$class          = 'invalid';
266
			$messages[]     = sprintf(
267
				__( 'Your %1$s is not active for this URL. Please <a href="%2$s" target="_blank" title="Visit account page">visit your account page</a> to manage your license key URLs.', 'give' ),
268
				$addon_name,
269
				$account_page_link . '?utm_campaign=admin&utm_source=licenses&utm_medium=invalid'
270
			);
271
			$license_status = 'license-' . $class;
272
273
		} else {
274
			switch ( $license->license ) {
275
				case 'valid':
276
				default:
277
					$class      = 'valid';
0 ignored issues
show
Unused Code introduced by
$class 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...
278
					$now        = current_time( 'timestamp' );
279
					$expiration = strtotime( $license->expires, current_time( 'timestamp' ) );
280
281
					if ( 'lifetime' === $license->expires ) {
282
						$messages[]     = __( 'License key never expires.', 'give' );
283
						$license_status = 'license-lifetime-notice';
284
					} elseif ( $expiration > $now && $expiration - $now < ( DAY_IN_SECONDS * 30 ) ) {
285
						$messages[]     = sprintf(
286
							__( 'Your license key expires soon! It expires on %1$s. <a href="%2$s" target="_blank" title="Renew license">Renew your license key</a>.', 'give' ),
287
							date_i18n( get_option( 'date_format' ), strtotime( $license->expires, current_time( 'timestamp' ) ) ),
288
							$checkout_page_link . '?edd_license_key=' . $license_key . '&utm_campaign=admin&utm_source=licenses&utm_medium=renew'
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$license_key'
Loading history...
289
						);
290
						$license_status = 'license-expires-soon';
291
					} else {
292
						$messages[]     = sprintf(
293
							__( 'Your license key expires on %s.', 'give' ),
294
							date_i18n( get_option( 'date_format' ), strtotime( $license->expires, current_time( 'timestamp' ) ) )
295
						);
296
						$license_status = 'license-expiration-date';
297
					}
298
					break;
299
			}
300
		}
301
	} else {
302
		$messages[]     = sprintf(
303
			__( 'To receive updates, please enter your valid %s license key.', 'give' ),
304
			$addon_name
305
		);
306
		$license_status = 'inactive';
307
	}
308
309
	// Add class for input field if license is active.
310
	if ( $is_valid_license ) {
311
		$field_classes .= ' give-license-active';
312
	}
313
314
	// Get input field html.
315
	$input_field_html = "<input type=\"{$type}\" name=\"{$id}\" class=\"{$field_classes}\" value=\"{$license_key}\">";
316
317
	// If license is active so show deactivate button.
318
	if ( $is_valid_license ) {
319
		// Get input field html.
320
		$input_field_html = "<input type=\"{$type}\" name=\"{$id}\" class=\"{$field_classes}\" value=\"{$license_key}\" readonly=\"readonly\">";
321
322
		$custom_html = '<input type="submit" class="button button-small give-license-deactivate" name="' . $id . '_deactivate" value="' . esc_attr__( 'Deactivate License', 'give' ) . '"/>';
323
324
	}
325
326
	// Field description.
327
	$custom_html .= '<label for="give_settings[' . $id . ']"> ' . $field_description . '</label>';
328
329
	// If no messages found then inform user that to get updated in future register yourself.
330
	if ( empty( $messages ) ) {
331
		$messages[] = apply_filters( "{$shortname}_default_addon_notice", __( 'To receive updates, please enter your valid license key.', 'give' ) );
332
	}
333
334
	foreach ( $messages as $message ) {
335
		$custom_html .= '<div class="give-license-status-notice give-' . $license_status . '">';
336
		$custom_html .= '<p>' . $message . '</p>';
337
		$custom_html .= '</div>';
338
	}
339
340
	// Field html.
341
	$custom_html = apply_filters( 'give_license_key_field_html', $input_field_html . $custom_html, $field );
342
343
	// Nonce.
344
	wp_nonce_field( $id . '-nonce', $id . '-nonce' );
345
346
	// Print field html.
347
	echo "<div class=\"give-license-key\"><label for=\"{$id}\">{$addon_name }</label></div><div class=\"give-license-block\">{$custom_html}</div>";
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '"<div class=\"give-license-key\"><label for=\"{$id}\">{$addon_name }</label></div><div class=\"give-license-block\">{$custom_html}</div>"'
Loading history...
348
}
349
350
351
/**
352
 * Display the API Keys
353
 *
354
 * @since       1.0
355
 * @return      void
356
 */
357
function give_api_callback() {
358
359
	if ( ! current_user_can( 'manage_give_settings' ) ) {
360
		return;
361
	}
362
363
	/**
364
	 * Fires before displaying API keys.
365
	 *
366
	 * @since 1.0
367
	 */
368
	do_action( 'give_tools_api_keys_before' );
369
370
	require_once GIVE_PLUGIN_DIR . 'includes/admin/class-api-keys-table.php';
371
372
	$api_keys_table = new Give_API_Keys_Table();
373
	$api_keys_table->prepare_items();
374
	$api_keys_table->display();
375
	?>
376
	<span class="cmb2-metabox-description api-description">
377
		<?php
378
		echo sprintf(
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'sprintf'
Loading history...
379
		/* translators: 1: http://docs.givewp.com/api 2: http://docs.givewp.com/addon-zapier */
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 12 spaces, but found 8.
Loading history...
380
			__( 'You can create API keys for individual users within their profile edit screen. API keys allow users to use the <a href="%1$s" target="_blank">Give REST API</a> to retrieve donation data in JSON or XML for external applications or devices, such as <a href="%2$s" target="_blank">Zapier</a>.', 'give' ),
381
			esc_url( 'http://docs.givewp.com/api' ),
382
			esc_url( 'http://docs.givewp.com/addon-zapier' )
383
		);
384
		?>
385
	</span>
386
	<?php
387
388
	/**
389
	 * Fires after displaying API keys.
390
	 *
391
	 * @since 1.0
392
	 */
393
	do_action( 'give_tools_api_keys_after' );
394
}
395