Completed
Push — master ( ab284c...4fdc7c )
by Justin
07:07
created

misc.functions.php ➔ nzshpcrt_display_preview_image()   F

Complexity

Conditions 46
Paths > 20000

Size

Total Lines 219
Code Lines 156

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 46
eloc 156
nc 3489410
nop 0
dl 0
loc 219
rs 2

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
 * WP eCommerce misc functions
5
 *
6
 * These are the WPSC miscellaneous functions
7
 *
8
 * @package wp-e-commerce
9
 * @since 3.7
10
 */
11
12
/**
13
 * WPSC find purchlog status name looks through the wpsc_purchlog_statuses variable to find the name of the given status
14
 *
15
 * @since 3.8
16
 * $param int $id the id for the region
17
 * @param string $return_value either 'name' or 'code' depending on what you want returned
0 ignored issues
show
Bug introduced by
There is no parameter named $return_value. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
18
 */
19
function wpsc_find_purchlog_status_name( $purchlog_status ) {
20
	global $wpsc_purchlog_statuses;
21
22
	$status_name = '';
23
24
	foreach ( $wpsc_purchlog_statuses as $status ) {
25
		if ( $status['order'] == $purchlog_status ) {
26
			$status_name = $status['label'];
27
		} else {
28
			continue;
29
		}
30
	}
31
	return $status_name;
32
}
33
34
/**
35
 * WPSC get state by id function, gets either state code or state name depending on param
36
*
37
 * @since 3.7
38
 * $param int $id the id for the region
39
 * @param string $return_value either 'name' or 'code' depending on what you want returned
40
 */
41
function wpsc_get_state_by_id( $id, $return_value ) {
42
43
	$region = new WPSC_Region( WPSC_Countries::get_country_id_by_region_id( $id ), $id );
44
45
	$value = '';
46
47
	if ( $return_value == 'name' ) {
48
		$value = $region->get_name();
49
	} elseif ( $return_value == 'code' ) {
50
		$value = $region->get_code();
51
	}
52
53
	return $value;
54
}
55
56
function wpsc_country_has_state( $country_code ){
57
58
	$country_data = WPSC_Countries::get_country( $country_code, true ); // TODO this function does not seem to do what it's name indicates? What's up with that.
59
	return $country_data;
60
}
61
62
/**
63
 * Convert time interval to seconds.
64
 *
65
 * Takes a number an unit of time (hour/day/week) and converts it to seconds.
66
 * It allows decimal intervals like 1.5 days.
67
 *
68
 * @since   3.8.14
69
 * @access  public
70
 *
71
 * @param   int  $time      Stock keeping time.
72
 * @param   int  $interval  Stock keeping interval unit (hour/day/week).
73
 * @return  int             Seconds.
74
 *
75
 * @uses  MINUTE_IN_SECONDS, HOUR_IN_SECONDS, DAY_IN_SECONDS, WEEK_IN_SECONDS, YEAR_IN_SECONDS
76
 */
77
function wpsc_convert_time_interval_to_seconds( $time, $interval ) {
78
	$convert = array(
79
		'minute' => MINUTE_IN_SECONDS,
80
		'hour'   => HOUR_IN_SECONDS,
81
		'day'    => DAY_IN_SECONDS,
82
		'week'   => WEEK_IN_SECONDS,
83
		'year'   => YEAR_IN_SECONDS,
84
	);
85
	return floor( $time * $convert[ $interval ] );
86
}
87
88
/**
89
 * WPSC add new user function, validates and adds a new user, for the
90
 *
91
 * @since 3.7
92
 *
93
 * @param string $user_login The user's username.
94
 * @param string $password The user's password.
0 ignored issues
show
Bug introduced by
There is no parameter named $password. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
95
 * @param string $user_email The user's email (optional).
96
 * @return int The new user's ID.
97
 */
98
function wpsc_add_new_user( $user_login, $user_pass, $user_email ) {
99
	$errors = new WP_Error();
100
	$user_login = sanitize_user( $user_login );
101
	$user_email = apply_filters( 'user_registration_email', $user_email );
102
103
	// Check the username
104
	if ( $user_login == '' ) {
105
		$errors->add( 'empty_username', __( '<strong>ERROR</strong>: Please enter a username.', 'wp-e-commerce' ) );
106
	} elseif ( !validate_username( $user_login ) ) {
107
		$errors->add( 'invalid_username', __( '<strong>ERROR</strong>: This username is invalid.  Please enter a valid username.', 'wp-e-commerce' ) );
108
		$user_login = '';
109
	} elseif ( username_exists( $user_login ) ) {
110
		$errors->add( 'username_exists', __( '<strong>ERROR</strong>: This username is already registered, please choose another one.', 'wp-e-commerce' ) );
111
	}
112
113
	// Check the e-mail address
114
	if ( $user_email == '' ) {
115
		$errors->add( 'empty_email', __( '<strong>ERROR</strong>: Please type your e-mail address.', 'wp-e-commerce' ) );
116
	} elseif ( !is_email( $user_email ) ) {
117
		$errors->add( 'invalid_email', __( '<strong>ERROR</strong>: The email address isn&#8217;t correct.', 'wp-e-commerce' ) );
118
		$user_email = '';
119
	} elseif ( email_exists( $user_email ) ) {
120
		$errors->add( 'email_exists', __( '<strong>ERROR</strong>: This email is already registered, please choose another one.', 'wp-e-commerce' ) );
121
	}
122
123
	if ( $errors->get_error_code() ) {
124
		return $errors;
125
	}
126
	$user_id = wp_create_user( $user_login, $user_pass, $user_email );
127
	if ( !$user_id ) {
128
		$errors->add( 'registerfail', sprintf( __( '<strong>ERROR</strong>: Couldn&#8217;t register you... please contact the <a href="mailto:%s">webmaster</a> !', 'wp-e-commerce' ), get_option( 'admin_email' ) ) );
129
		return $errors;
130
	}
131
132
	$user = wp_signon( array( 'user_login' => $user_login, 'user_password' => $user_pass, 'remember' => true ) );
133
	wp_set_current_user( $user->ID );
134
135
	return $user;
136
}
137
138
139
function wpsc_set_aioseop_keywords( $data ) {
140
	global $wpdb, $wp_query, $wpsc_title_data, $aioseop_options;
141
142
	if ( isset( $wp_query->query_vars['product_url_name'] ) ) {
143
		$product_name = $wp_query->query_vars['product_url_name'];
144
		$product_id = $wpdb->get_var( "SELECT `product_id` FROM `" . WPSC_TABLE_PRODUCTMETA . "` WHERE `meta_key` IN ( 'url_name' ) AND `meta_value` IN ( '{$wp_query->query_vars['product_url_name']}' ) ORDER BY `id` DESC LIMIT 1" );
145
146
		$replacement_data = '';
147
		$replacement_data_array = array( );
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
148
		if ( $aioseop_options['aiosp_use_categories'] ) {
149
			$category_list = $wpdb->get_col( "SELECT `categories`.`name` FROM `" . WPSC_TABLE_ITEM_CATEGORY_ASSOC . "` AS `assoc` , `" . WPSC_TABLE_PRODUCT_CATEGORIES . "` AS `categories` WHERE `assoc`.`product_id` IN ('{$product_id}') AND `assoc`.`category_id` = `categories`.`id` AND `categories`.`active` IN('1')" );
150
			$replacement_data_array += $category_list;
151
		}
152
		$replacement_data_array += wpsc_get_product_terms( $product_id, 'product_tag', 'name' );
153
		$replacement_data .= implode( ",", $replacement_data_array );
154
		if ( $replacement_data != '' ) {
155
			$data = strtolower( $replacement_data );
156
		}
157
	}
158
159
	return $data;
160
}
161
162
add_filter( 'aioseop_keywords', 'wpsc_set_aioseop_keywords' );
163
164
function wpsc_get_country_form_id_by_type($type){
165
	global $wpdb;
166
	$sql = $wpdb->prepare( 'SELECT `id` FROM `'.WPSC_TABLE_CHECKOUT_FORMS.'` WHERE `type`= %s LIMIT 1', $type );
167
	$id = $wpdb->get_var($sql);
168
	return $id;
169
}
170
171
function wpsc_get_country( $country_code ) {
172
	$wpsc_country = new WPSC_Country( $country_code );
173
	return $wpsc_country->get_name();
174
}
175
176
function wpsc_get_region( $region_id ) {
177
	$country_id = WPSC_Countries::get_country_id_by_region_id( $region_id );
178
	$wpsc_region = new WPSC_Region( $country_id, $region_id );
179
	return $wpsc_region->get_name();
180
}
181
182
function nzshpcrt_display_preview_image() {
183
	global $wpdb;
184
	if ( (isset( $_GET['wpsc_request_image'] ) && ($_GET['wpsc_request_image'] == 'true'))
185
			|| (isset( $_GET['productid'] ) && is_numeric( $_GET['productid'] ))
186
			|| (isset( $_GET['image_id'] ) && is_numeric( $_GET['image_id'] ))
187
			|| (isset( $_GET['image_name'] ))
188
	) {
189
190
		if ( function_exists( "getimagesize" ) ) {
191
192
			$imagepath   = '';
193
			$category_id = 0;
194
195
			if ( $_GET['image_name'] ) {
196
				$image = basename( $_GET['image_name'] );
197
				$imagepath = WPSC_USER_UPLOADS_DIR . $image;
198
			} else if ( $_GET['category_id'] ) {
199
				$category_id = absint( $_GET['category_id'] );
200
				$image = $wpdb->get_var( $wpdb->prepare( "SELECT `image` FROM `" . WPSC_TABLE_PRODUCT_CATEGORIES . "` WHERE `id` = %d LIMIT 1", $category_id ) );
201
				if ( $image != '' ) {
202
					$imagepath = WPSC_CATEGORY_DIR . $image;
203
				}
204
			}
205
206
			if ( ! is_file( $imagepath ) ) {
207
				$imagepath = WPSC_FILE_PATH . "/images/no-image-uploaded.gif";
208
			}
209
210
			$image_size = @getimagesize( $imagepath );
0 ignored issues
show
Coding Style introduced by
Silencing errors is discouraged
Loading history...
211
			if ( is_numeric( $_GET['height'] ) && is_numeric( $_GET['width'] ) ) {
212
				$height = (int)$_GET['height'];
213
				$width = (int)$_GET['width'];
214
			} else {
215
				$width = $image_size[0];
216
				$height = $image_size[1];
217
			}
218
			if ( !(($height > 0) && ($height <= 1024) && ($width > 0) && ($width <= 1024)) ) {
219
				$width = $image_size[0];
220
				$height = $image_size[1];
221
			}
222
223
			$product_id = (int) $_GET['productid'];
224
			$image_id   = (int) $_GET['image_id'];
225
226
			if ( $product_id > 0 ) {
227
				$cache_filename = basename( "product_{$product_id}_{$height}x{$width}" );
228
			} else if ( $category_id > 0 ) {
229
				$cache_filename = basename( "category_{$category_id}_{$height}x{$width}" );
230
			} else {
231
				$cache_filename = basename( "product_img_{$image_id}_{$height}x{$width}" );
232
			}
233
234
			$imagetype = @getimagesize( $imagepath );
0 ignored issues
show
Coding Style introduced by
Silencing errors is discouraged
Loading history...
235
			$use_cache = false;
236
			switch ( $imagetype[2] ) {
237
				case IMAGETYPE_GIF:
238
					$extension = ".gif";
239
					break;
240
241
				case IMAGETYPE_PNG:
242
					$extension = ".png";
243
					break;
244
245
				case IMAGETYPE_JPEG:
246
				default:
247
					$extension = ".jpg";
248
					break;
249
250
			}
251
			if ( file_exists( WPSC_CACHE_DIR . $cache_filename . $extension ) ) {
252
				$original_modification_time = filemtime( $imagepath );
253
				$cache_modification_time = filemtime( WPSC_CACHE_DIR . $cache_filename . $extension );
254
				if ( $original_modification_time < $cache_modification_time ) {
255
					$use_cache = true;
256
				}
257
			}
258
259
			if ( $use_cache === true ) {
260
				$cache_url = set_url_scheme( WPSC_CACHE_URL );
261
				header( "Location: " . $cache_url . $cache_filename . $extension );
262
				exit( '' );
263
			} else {
264
				switch ( $imagetype[2] ) {
265
					case IMAGETYPE_JPEG:
266
						$src_img = imagecreatefromjpeg( $imagepath );
267
						$pass_imgtype = true;
268
						break;
269
270
					case IMAGETYPE_GIF:
271
						$src_img = imagecreatefromgif( $imagepath );
272
						$pass_imgtype = true;
273
						break;
274
275
					case IMAGETYPE_PNG:
276
						$src_img = imagecreatefrompng( $imagepath );
277
						$pass_imgtype = true;
278
						break;
279
280
					default:
281
						$src_img      = false;
282
						$pass_imgtype = false;
283
						break;
284
				}
285
286
				if ( $pass_imgtype === true && $src_img ) {
287
					$source_w = imagesx( $src_img );
288
					$source_h = imagesy( $src_img );
289
290
					//Temp dimensions to crop image properly
291
					$temp_w = $width;
292
					$temp_h = $height;
293
294
					// select our scaling method
295
					$scaling_method = apply_filters( 'wpsc_preview_image_cropping_method', 'cropping' );
296
297
					// set both offsets to zero
298
					$offset_x = $offset_y = 0;
299
300
					// Here are the scaling methods, non-cropping causes black lines in tall images, but doesnt crop images.
301
					switch ( $scaling_method ) {
302
						case 'cropping':
303
							// if the image is wider than it is high and at least as wide as the target width.
304
							if ( ($source_h <= $source_w ) ) {
305
								if ( $height < $width ) {
306
									$temp_h = ($width / $source_w) * $source_h;
307
								} else {
308
									$temp_w = ($height / $source_h) * $source_w;
309
								}
310
							} else {
311
								$temp_h = ($width / $source_w) * $source_h;
312
							}
313
							break;
314
315
						case 'non-cropping':
316
						default:
317
							if ( $height < $width ) {
318
								$temp_h = ($width / $source_w) * $source_h;
319
							} else {
320
								$temp_w = ($height / $source_h) * $source_w;
321
							}
322
							break;
323
					}
324
325
					// Create temp resized image
326
					$bgcolor_default = apply_filters( 'wpsc_preview_image_bgcolor', array( 255, 255, 255 ) );
327
					$temp_img = ImageCreateTrueColor( $temp_w, $temp_h );
328
					$bgcolor = ImageColorAllocate( $temp_img, $bgcolor_default[0], $bgcolor_default[1], $bgcolor_default[2] ) ;
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
329
					ImageFilledRectangle( $temp_img, 0, 0, $temp_w, $temp_h, $bgcolor );
330
					ImageAlphaBlending( $temp_img, TRUE );
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected true, but found TRUE.
Loading history...
331
					ImageCopyResampled( $temp_img, $src_img, 0, 0, 0, 0, $temp_w, $temp_h, $source_w, $source_h );
332
333
					$dst_img = ImageCreateTrueColor( $width, $height );
334
					$bgcolor = ImageColorAllocate( $dst_img, $bgcolor_default[0], $bgcolor_default[1], $bgcolor_default[2] );
335
					ImageFilledRectangle( $dst_img, 0, 0, $width, $height, $bgcolor );
336
					ImageAlphaBlending( $dst_img, TRUE );
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected true, but found TRUE.
Loading history...
337
338
					// X & Y Offset to crop image properly
339
					if ( $temp_w < $width ) {
340
						$w1 = ($width / 2) - ($temp_w / 2);
341
					} else if ( $temp_w == $width ) {
342
						$w1 = 0;
343
					} else {
344
						$w1 = ($width / 2) - ($temp_w / 2);
345
					}
346
347
					if ( $temp_h < $height ) {
348
						$h1 = ($height / 2) - ($temp_h / 2);
349
					} else if ( $temp_h == $height ) {
350
						$h1 = 0;
351
					} else {
352
						$h1 = ($height / 2) - ($temp_h / 2);
353
					}
354
355
					switch ( $scaling_method ) {
356
						case 'cropping':
357
							ImageCopy( $dst_img, $temp_img, $w1, $h1, 0, 0, $temp_w, $temp_h );
358
							break;
359
360
						case 'non-cropping':
361
						default:
362
							ImageCopy( $dst_img, $temp_img, 0, 0, 0, 0, $temp_w, $temp_h );
363
							break;
364
					}
365
366
					$image_quality = wpsc_image_quality();
367
368
					ImageAlphaBlending( $dst_img, false );
369
					switch ( $imagetype[2] ) {
370
						case IMAGETYPE_JPEG:
371
							header( "Content-type: image/jpeg" );
372
							imagejpeg( $dst_img );
373
							imagejpeg( $dst_img, WPSC_CACHE_DIR . $cache_filename . '.jpg', $image_quality );
374
							@ chmod( WPSC_CACHE_DIR . $cache_filename . ".jpg", 0775 );
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...
introduced by
Filesystem writes are forbidden, you should not be using chmod()
Loading history...
375
							break;
376
377
						case IMAGETYPE_GIF:
378
							header( "Content-type: image/gif" );
379
							ImagePNG( $dst_img );
380
							ImagePNG( $dst_img, WPSC_CACHE_DIR . $cache_filename . ".gif" );
381
							@ chmod( WPSC_CACHE_DIR . $cache_filename . ".gif", 0775 );
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...
introduced by
Filesystem writes are forbidden, you should not be using chmod()
Loading history...
382
							break;
383
384
						case IMAGETYPE_PNG:
385
							header( "Content-type: image/png" );
386
							ImagePNG( $dst_img );
387
							ImagePNG( $dst_img, WPSC_CACHE_DIR . $cache_filename . ".png" );
388
							@ chmod( WPSC_CACHE_DIR . $cache_filename . ".png", 0775 );
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...
introduced by
Filesystem writes are forbidden, you should not be using chmod()
Loading history...
389
							break;
390
391
						default:
392
							$pass_imgtype = false;
393
							break;
394
					}
395
					exit();
396
				}
397
			}
398
		}
399
	}
400
}
401
402
add_action( 'init', 'nzshpcrt_display_preview_image' );
403
404
function wpsc_list_dir( $dirname ) {
405
	/*
406
	  lists the provided directory, was nzshpcrt_listdir
407
	 */
408
	$dir = @opendir( $dirname );
0 ignored issues
show
Coding Style introduced by
Silencing errors is discouraged
Loading history...
409
	$num = 0;
410
	$dirlist = array();
411
412
	while ( ($file = @readdir( $dir )) !== false ) {
0 ignored issues
show
Coding Style introduced by
Silencing errors is discouraged
Loading history...
413
		//filter out the dots and any backup files, dont be tempted to correct the "spelling mistake", its to filter out a previous spelling mistake.
414
		if ( ($file != "..") && ($file != ".") && !stristr( $file, "~" ) && !stristr( $file, "Chekcout" ) && !stristr( $file, "error_log" ) && !( strpos( $file, "." ) === 0 ) ) {
415
			$dirlist[$num] = $file;
416
			$num++;
417
		}
418
	}
419
	return $dirlist;
420
}
421
422
/**
423
 * wpsc_recursive_copy function, copied from here and renamed: http://nz.php.net/copy
424
 * Why doesn't PHP have one of these built in?
425
 */
426
function wpsc_recursive_copy( $src, $dst ) {
427
	$dir = opendir( $src );
428
	@mkdir( $dst );
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...
introduced by
Filesystem writes are forbidden, you should not be using mkdir()
Loading history...
429
	while ( false !== ( $file = readdir( $dir )) ) {
430
		if ( ( $file != '.' ) && ( $file != '..' ) ) {
431
			if ( is_dir( $src . '/' . $file ) ) {
432
				wpsc_recursive_copy( $src . '/' . $file, $dst . '/' . $file );
433
			} else {
434
				@ copy( $src . '/' . $file, $dst . '/' . $file );
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...
435
			}
436
		}
437
	}
438
	closedir( $dir );
439
}
440
441
/**
442
 * wpsc_replace_reply_address function,
443
 * Replace the email address for the purchase receipts
444
 */
445
function wpsc_replace_reply_address( $input ) {
446
	$output = get_option( 'return_email' );
447
	if ( $output == '' ) {
448
		$output = $input;
449
	}
450
	return $output;
451
}
452
453
/**
454
 * wpsc_replace_reply_address function,
455
 * Replace the email address for the purchase receipts
456
 */
457
function wpsc_replace_reply_name( $input ) {
458
	$output = get_option( 'return_name' );
459
	if ( $output == '' ) {
460
		$output = $input;
461
	}
462
	return $output;
463
}
464
465
/**
466
 * wpsc_object_to_array, recusively converts an object to an array, for usage with SOAP code
467
 * Copied from here, then modified:
468
 * http://www.phpro.org/examples/Convert-Object-To-Array-With-PHP.html
469
 */
470
function wpsc_object_to_array( $object ) {
471
	if ( !is_object( $object ) && !is_array( $object ) ) {
472
		return $object;
473
	} else if ( is_object( $object ) ) {
474
		$object = get_object_vars( $object );
475
	}
476
	return array_map( 'wpsc_object_to_array', $object );
477
}
478
479
function wpsc_readfile_chunked( $filename, $retbytes = true ) {
480
	$chunksize = 1 * (1024 * 1024); // how many bytes per chunk
481
	$buffer = '';
482
	$cnt = 0;
483
	$handle = fopen( $filename, 'rb' );
484
	if ( $handle === false ) {
485
		return false;
486
	}
487
	while ( !feof( $handle ) ) {
488
		$buffer = fread( $handle, $chunksize );
489
		echo $buffer;
490
		ob_flush();
491
		flush();
492
		if ( $retbytes ) {
493
			$cnt += strlen( $buffer );
494
		}
495
	}
496
	$status = fclose( $handle );
497
	if ( $retbytes && $status ) {
498
		return $cnt; // return num. bytes delivered like readfile() does.
499
	}
500
	return $status;
501
}
502
503
/**
504
 * Retrieve the list of tags for a product.
505
 *
506
 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
507
 * away from the complexity of the taxonomy layer. Copied from the Wordpress posts code
508
 *
509
 * @since 3.8.0
510
 *
511
 * @uses wp_get_object_terms() Retrieves the tags. Args details can be found here.
512
 *
513
 * @param int $product_id Optional. The Post ID.
514
 * @param array $args Optional. Overwrite the defaults.
515
 * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use stdObject[].

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
516
 */
517
function wp_get_product_tags( $product_id = 0, $args = array( ) ) {
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
518
	$product_id = (int)$product_id;
519
520
	$defaults = array( 'fields' => 'ids' );
521
	$args = wp_parse_args( $args, $defaults );
522
523
	$cats = wpsc_get_product_terms( $product_id, 'product_tag' );
524
	return $cats;
525
}
526
527
/**
528
 * Retrieve the list of categories for a product.
529
 *
530
 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
531
 * away from the complexity of the taxonomy layer. Copied from the Wordpress posts code
532
 *
533
 * @since 3.8.0
534
 *
535
 * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
536
 *
537
 * @param int $post_id Optional. The Post ID.
0 ignored issues
show
Bug introduced by
There is no parameter named $post_id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
538
 * @param array $args Optional. Overwrite the defaults.
539
 * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use stdObject[].

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
540
 */
541
function wp_get_product_categories( $product_id = 0, $args = array( ) ) {
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
542
	$product_id = (int)$product_id;
543
544
	$defaults = array( 'fields' => 'ids' );
545
	$args = wp_parse_args( $args, $defaults );
546
547
	$cats = wpsc_get_product_terms( $product_id, 'wpsc_product_category' );
548
	return $cats;
549
}
550
551
/**
552
 * Set categories for a product.
553
 *
554
 * If the post categories parameter is not set, then the default category is
555
 * going used.  Copied from the Wordpress posts code
556
 *
557
 * @since 3.8.0
558
 *
559
 * @param int $post_ID Post ID.
0 ignored issues
show
Bug introduced by
There is no parameter named $post_ID. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
560
 * @param array $post_categories Optional. List of categories.
561
 * @return bool|mixed
562
 */
563
function wp_set_product_categories( $product_id, $post_categories = array( ) ) {
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
564
	$product_id = (int)$product_id;
565
	// If $post_categories isn't already an array, make it one:
566
	if ( !is_array( $post_categories ) || 0 == count( $post_categories ) || empty( $post_categories ) ) {
567
		return;
568
	} else if ( 1 == count( $post_categories ) && '' == $post_categories[0] ) {
569
		return true;
570
	}
571
572
	$post_categories = array_map( 'intval', $post_categories );
573
	$post_categories = array_unique( $post_categories );
574
575
	return wp_set_object_terms( $product_id, $post_categories, 'wpsc_product_category' );
576
}
577
578
//*/
579
580
/**
581
 * Retrieve product categories. Copied from the corresponding wordpress function
582
 *
583
 * @since 3.8.0
584
 *
585
 * @param int $id Mandatory, the product ID
586
 * @return array
587
 */
588
function get_the_product_category( $id ) {
589
590
	$id = (int)$id;
591
592
	$categories = wpsc_get_product_terms( $id, 'wpsc_product_category' );
593
594
	if ( !empty( $categories ) )
595
		usort( $categories, '_usort_terms_by_name' );
596
	else
597
		$categories = array( );
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
598
599
	foreach ( (array)array_keys( $categories ) as $key ) {
600
		_make_cat_compat( $categories[$key] );
601
	}
602
603
	return $categories;
604
}
605
606
/**
607
 * Check the memory_limit and calculate a recommended memory size
608
 * inspired by nextGenGallery Code
609
 *
610
 * @return string message about recommended image size
611
 */
612
function wpsc_check_memory_limit() {
613
614
	if ( (function_exists( 'memory_get_usage' )) && (ini_get( 'memory_limit' )) ) {
615
616
		// get memory limit
617
		$memory_limit = ini_get( 'memory_limit' );
618
		if ( $memory_limit != '' )
619
			$memory_limit = substr( $memory_limit, 0, -1 ) * 1024 * 1024;
620
621
		// calculate the free memory
622
		$freeMemory = $memory_limit - memory_get_usage();
623
624
		// build the test sizes
625
		$sizes = array( );
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
626
		$sizes[] = array( 'width' => 800, 'height' => 600 );
627
		$sizes[] = array( 'width' => 1024, 'height' => 768 );
628
		$sizes[] = array( 'width' => 1280, 'height' => 960 );  // 1MP
629
		$sizes[] = array( 'width' => 1600, 'height' => 1200 ); // 2MP
630
		$sizes[] = array( 'width' => 2016, 'height' => 1512 ); // 3MP
631
		$sizes[] = array( 'width' => 2272, 'height' => 1704 ); // 4MP
632
		$sizes[] = array( 'width' => 2560, 'height' => 1920 ); // 5MP
633
		// test the classic sizes
634
		foreach ( $sizes as $size ) {
635
			// very, very rough estimation
636
			if ( $freeMemory < round( $size['width'] * $size['height'] * 5.09 ) ) {
637
				$result = sprintf( __( 'Please refrain from uploading images larger than <strong>%d x %d</strong> pixels', 'wp-e-commerce' ), $size['width'], $size['height'] );
638
				return $result;
639
			}
640
		}
641
	}
642
	return;
643
}
644
645
/* Thanks to: http://www.if-not-true-then-false.com/2009/format-bytes-with-php-b-kb-mb-gb-tb-pb-eb-zb-yb-converter */
646
function wpsc_convert_byte($bytes, $unit = "", $decimals = 2) {
647
648
	$units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4,
649
			'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
650
	$value = 0;
651
	if ($bytes > 0) {
652
		// Generate automatic prefix by bytes
653
		// If wrong prefix given
654
		if (!array_key_exists($unit, $units)) {
655
			$pow = floor(log($bytes)/log(1024));
656
			$unit = array_search($pow, $units);
657
		}
658
659
		// Calculate byte value by prefix
660
		$value = ($bytes/pow(1024,floor($units[$unit])));
661
	}
662
663
	// If decimals is not numeric or decimals is less than 0
664
	// then set default value
665
	if (!is_numeric($decimals) || $decimals < 0) {
666
		$decimals = 2;
667
	}
668
669
	// Format output
670
	return sprintf('%.' . $decimals . 'f '.$unit, $value);
671
  }
672
673
/**
674
 * Check whether an integer is odd
675
 * @return bool - true if is odd, false otherwise
676
 */
677
function wpsc_is_odd( $int ) {
678
679
	$int = absint( $int );
680
	return( $int & 1 );
681
}
682
683
/**
684
 * Retrieves extension of file.
685
 * @return string - extension of the passed filename
686
 */
687
function wpsc_get_extension( $str ) {
688
689
	$parts = explode( '.', $str );
690
	return end( $parts );
691
692
}
693
694
/**
695
 * Marks a function as deprecated and informs when it has been used.
696
 *
697
 * There is a hook wpsc_deprecated_function_run that will be called that can be
698
 * used to get the backtrace up to what file and function called the deprecated
699
 * function.
700
 *
701
 * The current behavior is to trigger a user error if WP_DEBUG is true.
702
 *
703
 * This function is to be used in every function that is deprecated.
704
 *
705
 * @since 3.8.10
706
 * @access private
707
 *
708
 * @uses do_action() Calls 'wpsc_deprecated_function_run' and passes the function name, what to use instead,
709
 *   and the version the function was deprecated in.
710
 * @uses apply_filters() Calls 'wpsc_deprecated_function_trigger_error' and expects boolean value of true to do
711
 *   trigger or false to not trigger error.
712
 *
713
 * @param string $function The function that was called
714
 * @param string $version The version of WP eCommerce that deprecated the function
715
 * @param string $replacement Optional. The function that should have been called
0 ignored issues
show
Documentation introduced by
Should the type for parameter $replacement not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
716
 */
717
function _wpsc_deprecated_function( $function, $version, $replacement = null ) {
718
	do_action( 'wpsc_deprecated_function_run', $function, $replacement, $version );
719
720
	// Allow plugin to filter the output error trigger
721
	if ( WP_DEBUG && apply_filters( 'wpsc_deprecated_function_trigger_error', true ) ) {
722
		if ( ! is_null( $replacement ) )
723
			trigger_error(
724
				sprintf( __( '%1$s is <strong>deprecated</strong> since WP eCommerce version %2$s! Use %3$s instead.', 'wp-e-commerce' ),
725
					$function,
726
					$version,
727
					$replacement
728
				)
729
			);
730
		else
731
			trigger_error(
732
				sprintf( __( '%1$s is <strong>deprecated</strong> since WP eCommerce version %2$s with no alternative available.', 'wp-e-commerce' ),
733
					$function,
734
					$version
735
				)
736
			);
737
	}
738
}
739
740
/**
741
 * Marks a file as deprecated and informs when it has been used.
742
 *
743
 * There is a hook wpsc_deprecated_file_included that will be called that can be
744
 * used to get the backtrace up to what file and function included the
745
 * deprecated file.
746
 *
747
 * The current behavior is to trigger a user error if WP_DEBUG is true.
748
 *
749
 * This function is to be used in every file that is deprecated.
750
 *
751
 * @since 3.8.10
752
 * @access private
753
 *
754
 * @uses do_action() Calls 'wpsc_deprecated_file_included' and passes the file name, what to use instead,
755
 *   the version in which the file was deprecated, and any message regarding the change.
756
 * @uses apply_filters() Calls 'wpsc_deprecated_file_trigger_error' and expects boolean value of true to do
757
 *   trigger or false to not trigger error.
758
 *
759
 * @param string $file The file that was included
760
 * @param string $version The version of WP eCommerce that deprecated the file
761
 * @param string $replacement Optional. The file that should have been included based on ABSPATH
0 ignored issues
show
Documentation introduced by
Should the type for parameter $replacement not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
762
 * @param string $message Optional. A message regarding the change
763
 */
764
function _wpsc_deprecated_file( $file, $version, $replacement = null, $message = '' ) {
765
766
	do_action( 'wpsc_deprecated_file_included', $file, $replacement, $version, $message );
767
768
	// Allow plugin to filter the output error trigger
769
	if ( WP_DEBUG && apply_filters( 'wpsc_deprecated_file_trigger_error', true ) ) {
770
		$message = empty( $message ) ? '' : ' ' . $message;
771
		if ( ! is_null( $replacement ) )
772
			trigger_error(
773
				sprintf( __( '%1$s is <strong>deprecated</strong> since WP eCommerce version %2$s! Use %3$s instead.', 'wp-e-commerce' ),
774
					$file,
775
					$version,
776
					$replacement
777
				) . $message
778
			);
779
		else
780
			trigger_error(
781
				sprintf( __( '%1$s is <strong>deprecated</strong> since WP eCommerce version %2$s with no alternative available.', 'wp-e-commerce' ),
782
					$file,
783
					$version
784
				) . $message
785
			);
786
	}
787
}
788
/**
789
 * Marks a function argument as deprecated and informs when it has been used.
790
 *
791
 * This function is to be used whenever a deprecated function argument is used.
792
 * Before this function is called, the argument must be checked for whether it
793
 * was used by comparing it to its default value or evaluating whether it is
794
 * empty.
795
 *
796
 * For example:
797
 * <code>
798
 * if ( ! empty( $deprecated ) )
799
 * 	_wpsc_deprecated_argument( __FUNCTION__, '3.8.10' );
800
 * </code>
801
 *
802
 * There is a hook wpsc_deprecated_argument_run that will be called that can be
803
 * used to get the backtrace up to what file and function used the deprecated
804
 * argument.
805
 *
806
 * The current behavior is to trigger a user error if WP_DEBUG is true.
807
 *
808
 * @since 3.8.10
809
 * @access private
810
 *
811
 * @uses do_action() Calls 'wpsc_deprecated_argument_run' and passes the function name, a message on the change,
812
 *   and the version in which the argument was deprecated.
813
 * @uses apply_filters() Calls 'wpsc_deprecated_argument_trigger_error' and expects boolean value of true to do
814
 *   trigger or false to not trigger error.
815
 *
816
 * @param string $function The function that was called
817
 * @param string $version The version of WP eCommerce that deprecated the argument used
818
 * @param string $message Optional. A message regarding the change.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $message not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
819
 */
820
function _wpsc_deprecated_argument( $function, $version, $message = null ) {
821
822
	do_action( 'wpsc_deprecated_argument_run', $function, $message, $version );
823
824
	// Allow plugin to filter the output error trigger
825
	if ( WP_DEBUG && apply_filters( 'wpsc_deprecated_argument_trigger_error', true ) ) {
826
		if ( ! is_null( $message ) )
827
			trigger_error(
828
				sprintf(
829
					__( '%1$s was called with an argument that is <strong>deprecated</strong> since WP eCommerce version %2$s! %3$s', 'wp-e-commerce' ),
830
					$function,
831
					$version,
832
					$message
833
				)
834
			);
835
		else
836
			trigger_error(
837
				sprintf(
838
					__( '%1$s was called with an argument that is <strong>deprecated</strong> since WP eCommerce version %2$s with no alternative available.', 'wp-e-commerce' ),
839
					$function,
840
					$version
841
				)
842
			);
843
	}
844
}
845
846
/**
847
 * Marks something as being incorrectly called.
848
 *
849
 * There is a hook wpsc_doing_it_wrong_run that will be called that can be used
850
 * to get the backtrace up to what file and function called the deprecated
851
 * function.
852
 *
853
 * The current behavior is to trigger a user error if WP_DEBUG is true.
854
 *
855
 * @since 3.8.10
856
 * @access private
857
 *
858
 * @uses do_action() Calls 'wpsc_doing_it_wrong_run' and passes the function arguments.
859
 * @uses apply_filters() Calls 'wpsc_doing_it_wrong_trigger_error' and expects boolean value of true to do
860
 *   trigger or false to not trigger error.
861
 *
862
 * @param string $function The function that was called.
863
 * @param string $message A message explaining what has been done incorrectly.
864
 * @param string $version The version of WP eCommerce where the message was added.
865
 */
866
function _wpsc_doing_it_wrong( $function, $message, $version ) {
867
868
	do_action( 'wpsc_doing_it_wrong_run', $function, $message, $version );
869
870
	// Allow plugin to filter the output error trigger
871
	if ( WP_DEBUG && apply_filters( 'wpsc_doing_it_wrong_trigger_error', true ) ) {
872
		$version =   is_null( $version )
0 ignored issues
show
introduced by
Expected 1 space after "="; 3 found
Loading history...
873
		           ? ''
874
		           : sprintf( __( '(This message was added in WP eCommerce version %s.)', 'wp-e-commerce' ), $version );
875
		$message .= ' ' . __( 'Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.', 'wp-e-commerce' );
876
		trigger_error(
877
			sprintf(
878
				__( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s', 'wp-e-commerce' ),
879
				$function,
880
				$message,
881
				$version
882
			)
883
		);
884
	}
885
}
886
887
/**
888
 * Returns the ID of the highest numbered purchase log
889
 *
890
 * Fetches the max_purchase_id transient, or fetches it from the database and sets the transient
891
 *
892
 * @since 3.8.11
893
 *
894
 * @return integer The ID of the highest numbered purchase log in the database
895
 *
896
 * @see wpsc_invalidate_max_purchase_id_transient()
897
 */
898
function wpsc_max_purchase_id() {
899
	global $wpdb;
900
	if ( false === ( $max_purchase_id = get_transient( 'max_purchase_id' ) ) ) {
901
		 $max_purchase_id = $wpdb->get_var( 'SELECT MAX( id ) FROM ' . WPSC_TABLE_PURCHASE_LOGS );
902
		set_transient( 'max_purchase_id', $max_purchase_id, 60 * 60 * 24 ); // day of seconds
903
	}
904
	return (int) $max_purchase_id;
905
}
906
907
/**
908
 * Invalidates transient for highest numbered purchase log id
909
 *
910
 * Used especially with actions wpsc_purchase_log_insert and wpsc_purchase_log_delete
911
 *
912
 * @since 3.8.11
913
 *
914
 * @see wpsc_max_purchase_id()
915
 */
916
917
function wpsc_invalidate_max_purchase_id_transient () {
918
	delete_transient( 'max_purchase_id' );
919
}
920
921
add_action( 'wpsc_purchase_log_insert', 'wpsc_invalidate_max_purchase_id_transient' );
922
add_action( 'wpsc_purchase_log_delete', 'wpsc_invalidate_max_purchase_id_transient' );
923
924
/** Checks to see whether terms and conditions are empty
925
 * @access public
926
 *
927
 * @since 3.8
928
 * @return (boolean) true or false
929
 */
930
function wpsc_has_tnc(){
931
	if('' == get_option('terms_and_conditions'))
0 ignored issues
show
Coding Style introduced by
The if-else statement can be simplified to return !('' == get_optio...erms_and_conditions'));.
Loading history...
932
		return false;
933
	else
934
		return true;
935
}
936
937
if ( isset( $_GET['termsandconds'] ) && 'true' == $_GET['termsandconds'] )
938
	add_action( 'init', 'wpsc_show_terms_and_conditions' );
939
940
function wpsc_show_terms_and_conditions() {
941
	echo wpautop( wp_kses_post( get_option( 'terms_and_conditions' ) ) );
942
	die();
943
}
944
945
/**
946
 * Helper function to display proper spinner icon, depending on WP version used.
947
 * This way, WP 3.8+ users will not feel like they are in a time-warp.
948
 *
949
 * @since 3.8.13
950
 *
951
 * @return void
952
 */
953
function wpsc_get_ajax_spinner() {
954
	global $wp_version;
955
956
	if ( version_compare( $wp_version, '3.8', '<' ) ) {
957
		$url = admin_url( 'images/wpspin_light.gif' );
958
	} else {
959
		$url = admin_url( 'images/spinner.gif' );
960
	}
961
962
	return apply_filters( 'wpsc_get_ajax_spinner', $url );
963
}
964
965
function _wpsc_remove_erroneous_files() {
966
967
	if ( ! wpsc_is_store_admin() ) {
968
		return;
969
	}
970
971
	$files = array(
972
		 WPSC_FILE_PATH . '/wpsc-components/marketplace-core-v1/library/Sputnik/.htaccess',
973
		 WPSC_FILE_PATH . '/wpsc-components/marketplace-core-v1/library/Sputnik/error_log',
974
		 WPSC_FILE_PATH . '/wpsc-components/marketplace-core-v1/library/Sputnik/functions.php',
975
		 WPSC_FILE_PATH . '/wpsc-components/marketplace-core-v1/library/Sputnik/admin-functions.php',
976
		 WPSC_FILE_PATH . '/wpsc-components/marketplace-core-v1/library/Sputnik/advanced-cache.php'
977
	);
978
979
	foreach ( $files as $file ) {
980
		if ( is_file( $file ) ) {
981
			@unlink( $file );
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...
introduced by
Filesystem writes are forbidden, you should not be using unlink()
Loading history...
982
		}
983
	}
984
985
	update_option( 'wpsc_38131_file_check', false );
986
}
987
988
if ( get_option( 'wpsc_38131_file_check', true ) ) {
989
	add_action( 'admin_init', '_wpsc_remove_erroneous_files' );
990
}
991
992
993
/**
994
 * Store a WP eCommerce Transient
995
 * Wrapper function to cover WordPress' set transient function.
996
 * Note: Initial reason for implmenting this was unusual derserialization errors coming from the APC
997
 * component when APC tries to deserialize a transient containing nested objects. This wrapper function
998
 * encodes the transient contents so that APC will not try to deserialize it into component objects.
999
 *
1000
 * @since 3.9.3
1001
 * @param string $transient  Transient name. Expected to not be SQL-escaped. Must be
1002
 *                           45 characters or fewer in length.
1003
 * @param mixed  $value      Transient value. Must be serializable if non-scalar.
1004
 *                           Expected to not be SQL-escaped.
1005
 * @param int    $expiration Optional. Time until expiration in seconds. Default 0.
1006
 * @return bool  false if value was not set and true if value was set.*
1007
 */
1008
function _wpsc_set_transient(  $transient, $value, $expiration = 0 )  {
1009
	$serialized_value = serialize( $value );
1010
	$encoded_value = base64_encode( $serialized_value );
1011
	return set_transient( $transient, $encoded_value, $expiration );
1012
}
1013
1014
/**
1015
 * Retrieve a WP eCommerce Transient
1016
 * Wrapper function to cover WordPress' get transient function.
1017
 * Note: Initial reason for implmenting this was unusual derserialization errors coming from the APC
1018
 * component when APC tries to deserialize a transient containing nested objects. This wrapper function
1019
 * decodes the transient contents that were encoded so that APC will would try to deserialize it into
1020
 * component objects. If the transient contents can not be decoded, the transient is deleted and the
1021
 * function will return false as if the tranient never existed.
1022
 *
1023
 * @since 3.9.3
1024
 * @param string $transient Transient name. Expected to not be SQL-escaped.
1025
 * @return mixed value of transient, false if transient did not exist
1026
 */
1027
function _wpsc_get_transient( $transient )  {
1028
	$encoded_value = get_transient( $transient );
1029
	$value = false;
1030
1031
	if ( false !== $encoded_value ) {
1032
		if ( ! empty( $encoded_value ) && is_string( $encoded_value ) ) {
1033
			$serialized_value = @base64_decode( $encoded_value );
0 ignored issues
show
Coding Style introduced by
Silencing errors is discouraged
Loading history...
1034
			if ( is_string( $serialized_value ) ) {
1035
				$value = unserialize( $serialized_value );
1036
			} else {
1037
				$value = false;
1038
			}
1039
1040
			// if there was a transient, but it could not be decoded, we delete the transient to get back
1041
			// to a working state
1042
			if ( false === $value ) {
1043
				_wpsc_delete_transient( $transient );
1044
			}
1045
		}
1046
	}
1047
1048
	return $value;
1049
}
1050
1051
/**
1052
 * Delete a WP eCommerce Transient
1053
 * Wrapper function to cover WordPress' delete transient function.
1054
 * Note: Initial reason for implmenting this was unusual derserialization errors coming from the APC
1055
 * component when APC tries to deserialize a transient containing nested objects.
1056
 *
1057
 * @since 3.9.3
1058
 * @param string $transient Transient name. Expected to not be SQL-escaped.
1059
 * @return mixed value of transient, false if transient did not exist
1060
 */
1061
function _wpsc_delete_transient( $transient )  {
1062
	return delete_transient( $transient );
1063
}
1064
1065
1066