Completed
Pull Request — master (#11372)
by Matty
08:38
created

wc-rest-functions.php ➔ wc_rest_validate_reports_request_arg()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 21
Code Lines 12

Duplication

Lines 6
Ratio 28.57 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 12
nc 5
nop 3
dl 6
loc 21
rs 7.551
c 1
b 0
f 0
1
<?php
2
/**
3
 * WooCommerce REST Functions
4
 *
5
 * Functions for REST specific things.
6
 *
7
 * @author   WooThemes
8
 * @category Core
9
 * @package  WooCommerce/Functions
10
 * @version  2.6.0
11
 */
12
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Parses and formats a MySQL datetime (Y-m-d H:i:s) for ISO8601/RFC3339.
19
 *
20
 * Requered WP 4.4 or later.
21
 * See https://developer.wordpress.org/reference/functions/mysql_to_rfc3339/
22
 *
23
 * @since 2.6.0
24
 * @param  string      $date
25
 * @return string|null       ISO8601/RFC3339 formatted datetime.
26
 */
27
function wc_rest_prepare_date_response( $date ) {
28
	// Check if mysql_to_rfc3339 exists first!
29
	if ( ! function_exists( 'mysql_to_rfc3339' ) ) {
30
		return null;
31
	}
32
33
	// Return null if $date is empty/zeros.
34
	if ( '0000-00-00 00:00:00' === $date ) {
35
		return null;
36
	}
37
38
	// Return the formatted datetime.
39
	return mysql_to_rfc3339( $date );
40
}
41
42
/**
43
 * Upload image from URL.
44
 *
45
 * @since 2.6.0
46
 * @param  string         $image_url
47
 * @return array|WP_Error            Attachment data or error message.
48
 */
49
function wc_rest_upload_image_from_url( $image_url ) {
50
	$file_name   = basename( current( explode( '?', $image_url ) ) );
51
	$wp_filetype = wp_check_filetype( $file_name, null );
52
	$parsed_url  = @parse_url( $image_url );
53
54
	// Check parsed URL.
55
	if ( ! $parsed_url || ! is_array( $parsed_url ) ) {
56
		return new WP_Error( 'woocommerce_rest_invalid_image_url', sprintf( __( 'Invalid URL %s.', 'woocommerce' ), $image_url ), array( 'status' => 400 ) );
57
	}
58
59
	// Ensure url is valid.
60
	$image_url = esc_url_raw( $image_url );
61
62
	// Get the file.
63
	$response = wp_safe_remote_get( $image_url, array(
64
		'timeout' => 10
65
	) );
66
67
	if ( is_wp_error( $response ) ) {
68
		return new WP_Error( 'woocommerce_rest_invalid_remote_image_url', sprintf( __( 'Error getting remote image %s.', 'woocommerce' ), $image_url ) . ' ' . sprintf( __( 'Error: %s.', 'woocommerce' ), $response->get_error_message() ), array( 'status' => 400 ) );
69 View Code Duplication
	} elseif ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
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...
70
		return new WP_Error( 'woocommerce_rest_invalid_remote_image_url', sprintf( __( 'Error getting remote image %s.', 'woocommerce' ), $image_url ), array( 'status' => 400 ) );
71
	}
72
73
	// Ensure we have a file name and type.
74 View Code Duplication
	if ( ! $wp_filetype['type'] ) {
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...
75
		$headers = wp_remote_retrieve_headers( $response );
76
		if ( isset( $headers['content-disposition'] ) && strstr( $headers['content-disposition'], 'filename=' ) ) {
77
			$disposition = end( explode( 'filename=', $headers['content-disposition'] ) );
78
			$disposition = sanitize_file_name( $disposition );
79
			$file_name   = $disposition;
80
		} elseif ( isset( $headers['content-type'] ) && strstr( $headers['content-type'], 'image/' ) ) {
81
			$file_name = 'image.' . str_replace( 'image/', '', $headers['content-type'] );
82
		}
83
		unset( $headers );
84
	}
85
86
	// Upload the file.
87
	$upload = wp_upload_bits( $file_name, '', wp_remote_retrieve_body( $response ) );
88
89
	if ( $upload['error'] ) {
90
		return new WP_Error( 'woocommerce_rest_image_upload_error', $upload['error'], array( 'status' => 400 ) );
91
	}
92
93
	// Get filesize.
94
	$filesize = filesize( $upload['file'] );
95
96
	if ( 0 == $filesize ) {
97
		@unlink( $upload['file'] );
98
		unset( $upload );
99
100
		return new WP_Error( 'woocommerce_rest_image_upload_file_error', __( 'Zero size file downloaded.', 'woocommerce' ), array( 'status' => 400 ) );
101
	}
102
103
	do_action( 'woocommerce_rest_api_uploaded_image_from_url', $upload, $image_url );
104
105
	return $upload;
106
}
107
108
/**
109
 * Set uploaded image as attachment.
110
 *
111
 * @since 2.6.0
112
 * @param  array $upload Upload information from wp_upload_bits.
113
 * @param  int   $id     Post ID. Default to 0.
114
 * @return int           Attachment ID
115
 */
116
function wc_rest_set_uploaded_image_as_attachment( $upload, $id = 0 ) {
117
	$info    = wp_check_filetype( $upload['file'] );
118
	$title   = '';
119
	$content = '';
120
121
	if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) {
122
		include_once( ABSPATH . 'wp-admin/includes/image.php' );
123
	}
124
125
	if ( $image_meta = wp_read_image_metadata( $upload['file'] ) ) {
126
		if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
127
			$title = $image_meta['title'];
128
		}
129
		if ( trim( $image_meta['caption'] ) ) {
130
			$content = $image_meta['caption'];
131
		}
132
	}
133
134
	$attachment = array(
135
		'post_mime_type' => $info['type'],
136
		'guid'           => $upload['url'],
137
		'post_parent'    => $id,
138
		'post_title'     => $title,
139
		'post_content'   => $content,
140
	);
141
142
	$attachment_id = wp_insert_attachment( $attachment, $upload['file'], $id );
143
	if ( ! is_wp_error( $attachment_id ) ) {
144
		wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $upload['file'] ) );
145
	}
146
147
	return $attachment_id;
148
}
149
150
/**
151
 * Validate reports request arguments.
152
 *
153
 * @since 2.6.0
154
 * @param  mixed            $value
155
 * @param  WP_REST_Request  $request
156
 * @param  string           $param
157
 * @return WP_Error|boolean
158
 */
159
function wc_rest_validate_reports_request_arg( $value, $request, $param ) {
160
	$attributes = $request->get_attributes();
161 View Code Duplication
	if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
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...
162
		return true;
163
	}
164
	$args = $attributes['args'][ $param ];
165
166 View Code Duplication
	if ( 'string' === $args['type'] && ! is_string( $value ) ) {
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...
167
		return new WP_Error( 'woocommerce_rest_invalid_param', sprintf( __( '%1$s is not of type %2$s', 'woocommerce' ), $param, 'string' ) );
168
	}
169
170
	if ( 'date' === $args['format'] ) {
171
		$regex = '#^\d{4}-\d{2}-\d{2}$#';
172
173
		if ( ! preg_match( $regex, $value, $matches ) ) {
174
			return new WP_Error( 'woocommerce_rest_invalid_date', __( 'The date you provided is invalid.', 'woocommerce' ) );
175
		}
176
	}
177
178
	return true;
179
}
180
181
/**
182
 * Encodes a value according to RFC 3986.
183
 * Supports multidimensional arrays.
184
 *
185
 * @since 2.6.0
186
 * @param  string|array $value The value to encode.
187
 * @return string|array        Encoded values.
188
 */
189
function wc_rest_urlencode_rfc3986( $value ) {
190
	if ( is_array( $value ) ) {
191
		return array_map( 'wc_rest_urlencode_rfc3986', $value );
192
	} else {
193
		// Percent symbols (%) must be double-encoded.
194
		return str_replace( '%', '%25', rawurlencode( rawurldecode( $value ) ) );
195
	}
196
}
197
198
/**
199
 * Check permissions of posts on REST API.
200
 *
201
 * @since 2.6.0
202
 * @param  string $post_type Post type.
203
 * @param  string $context   Request context.
204
 * @param  int    $object_id Post ID.
205
 * @return bool
206
 */
207
function wc_rest_check_post_permissions( $post_type, $context = 'read', $object_id = 0 ) {
208
	$contexts = array(
209
		'read'   => 'read_private_posts',
210
		'create' => 'publish_posts',
211
		'edit'   => 'edit_post',
212
		'delete' => 'delete_post',
213
		'batch'  => 'edit_others_posts',
214
	);
215
216
	if ( 'revision' === $post_type ) {
217
		$permission = false;
218
	} else {
219
		$cap              = $contexts[ $context ];
220
		$post_type_object = get_post_type_object( $post_type );
221
		$permission       = current_user_can( $post_type_object->cap->$cap, $object_id );
222
	}
223
224
	return apply_filters( 'woocommerce_rest_check_permissions', $permission, $context, $object_id, $post_type );
225
}
226
227
/**
228
 * Check permissions of users on REST API.
229
 *
230
 * @since 2.6.0
231
 * @param  string $context   Request context.
232
 * @param  int    $object_id Post ID.
233
 * @return bool
234
 */
235
function wc_rest_check_user_permissions( $context = 'read', $object_id = 0 ) {
236
	$contexts = array(
237
		'read'   => 'list_users',
238
		'create' => 'edit_users',
239
		'edit'   => 'edit_users',
240
		'delete' => 'delete_users',
241
		'batch'  => 'edit_users',
242
	);
243
244
	$permission = current_user_can( $contexts[ $context ], $object_id );
245
246
	return apply_filters( 'woocommerce_rest_check_permissions', $permission, $context, $object_id, 'user' );
247
}
248
249
/**
250
 * Check permissions of product terms on REST API.
251
 *
252
 * @since 2.6.0
253
 * @param  string $taxonomy  Taxonomy.
254
 * @param  string $context   Request context.
255
 * @param  int    $object_id Post ID.
256
 * @return bool
257
 */
258
function wc_rest_check_product_term_permissions( $taxonomy, $context = 'read', $object_id = 0 ) {
259
	$contexts = array(
260
		'read'   => 'manage_terms',
261
		'create' => 'edit_terms',
262
		'edit'   => 'edit_terms',
263
		'delete' => 'delete_terms',
264
		'batch'  => 'edit_terms',
265
	);
266
267
	$cap             = $contexts[ $context ];
268
	$taxonomy_object = get_taxonomy( $taxonomy );
269
	$permission      = current_user_can( $taxonomy_object->cap->$cap, $object_id );
270
271
	return apply_filters( 'woocommerce_rest_check_permissions', $permission, $context, $object_id, $taxonomy );
272
}
273
274
/**
275
 * Check manager permissions on REST API.
276
 *
277
 * @since 2.6.0
278
 * @param  string $object  Object.
279
 * @param  string $context Request context.
280
 * @return bool
281
 */
282
function wc_rest_check_manager_permissions( $object, $context = 'read' ) {
283
	$objects = array(
284
		'reports'    => 'view_woocommerce_reports',
285
		'settings'   => 'manage_woocommerce',
286
		'attributes' => 'manage_product_terms',
287
	);
288
289
	$permission = current_user_can( $objects[ $object ] );
290
291
	return apply_filters( 'woocommerce_rest_check_permissions', $permission, $context, 0, $object );
292
}
293