Completed
Push — fix/4.4.1-typos ( 3db521 )
by
unknown
25s
created

utility-functions.php ➔ videopress_update_meta_data()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 26
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 12
nc 3
nop 1
dl 0
loc 26
rs 8.5806
c 0
b 0
f 0
1
<?php
2
/**
3
 * We won't have any videos less than sixty pixels wide. That would be silly.
4
 */
5
defined( 'VIDEOPRESS_MIN_WIDTH' ) or define( 'VIDEOPRESS_MIN_WIDTH', 60 );
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
6
7
/**
8
 * Validate user-supplied guid values against expected inputs
9
 *
10
 * @since 1.1
11
 * @param string $guid video identifier
12
 * @return bool true if passes validation test
13
 */
14
function videopress_is_valid_guid( $guid ) {
15
	if ( ! empty( $guid ) && strlen( $guid ) === 8 && ctype_alnum( $guid ) ) {
16
		return true;
17
	}
18
	return false;
19
}
20
21
/**
22
 * Get details about a specific video by GUID:
23
 *
24
 * @param $guid string
25
 * @return object
26
 */
27
function videopress_get_video_details( $guid ) {
28
	if ( ! videopress_is_valid_guid( $guid ) ) {
29
		return new WP_Error( 'bad-guid-format', __( 'Invalid Video GUID!', 'jetpack' ) );
30
	}
31
32
	$version  = '1.1';
33
	$endpoint = sprintf( '/videos/%1$s', $guid );
34
	$response = wp_remote_get( sprintf( 'https://public-api.wordpress.com/rest/v%1$s%2$s', $version, $endpoint ) );
35
	$data     = json_decode( wp_remote_retrieve_body( $response ) );
36
37
	/**
38
	 * Allow functions to modify fetched video details.
39
	 *
40
	 * This filter allows third-party code to modify the return data
41
	 * about a given video.  It may involve swapping some data out or
42
	 * adding new parameters.
43
	 *
44
	 * @since 4.0.0
45
	 *
46
	 * @param object $data The data returned by the WPCOM API. See: https://developer.wordpress.com/docs/api/1.1/get/videos/%24guid/
47
	 * @param string $guid The GUID of the VideoPress video in question.
48
	 */
49
	return apply_filters( 'videopress_get_video_details', $data, $guid );
50
}
51
52
53
/**
54
 * Get an attachment ID given a URL.
55
 *
56
 * Modified from http://wpscholar.com/blog/get-attachment-id-from-wp-image-url/
57
 *
58
 * @todo: Add some caching in here.
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
59
 *
60
 * @param string $url
61
 *
62
 * @return int|bool Attachment ID on success, false on failure
63
 */
64
function videopress_get_attachment_id_by_url( $url ) {
65
	$wp_upload_dir = wp_upload_dir();
66
	// Strip out protocols, so it doesn't fail because searching for http: in https: dir.
67
	$dir = set_url_scheme( trailingslashit( $wp_upload_dir['baseurl'] ), 'relative' );
68
69
	// Is URL in uploads directory?
70
	if ( false !== strpos( $url, $dir ) ) {
71
72
		$file = basename( $url );
73
74
		$query_args = array(
75
			'post_type'   => 'attachment',
76
			'post_status' => 'inherit',
77
			'fields'      => 'ids',
78
			'meta_query'  => array(
79
				array(
80
					'key'     => '_wp_attachment_metadata',
81
					'compare' => 'LIKE',
82
					'value'   => $file,
83
				),
84
			)
85
		);
86
87
		$query = new WP_Query( $query_args );
88
89
		if ( $query->have_posts() ) {
90
			foreach ( $query->posts as $attachment_id ) {
91
				$meta          = wp_get_attachment_metadata( $attachment_id );
92
				$original_file = basename( $meta['file'] );
93
				$cropped_files = wp_list_pluck( $meta['sizes'], 'file' );
94
95
				if ( $original_file === $file || in_array( $file, $cropped_files ) ) {
96
					return (int) $attachment_id;
97
				}
98
			}
99
		}
100
101
	}
102
103
	return false;
104
}
105
106
/**
107
 * Similar to `media_sideload_image` -- but returns an ID.
108
 *
109
 * @param $url
110
 * @param $attachment_id
111
 *
112
 * @return int|mixed|object|WP_Error
113
 */
114
function videopress_download_poster_image( $url, $attachment_id ) {
115
	// Set variables for storage, fix file filename for query strings.
116
	preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $url, $matches );
117
	if ( ! $matches ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $matches of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
118
		return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL', 'jetpack' ) );
119
	}
120
121
	$file_array = array();
122
	$file_array['name']     = basename( $matches[0] );
123
	$file_array['tmp_name'] = download_url( $url );
124
125
	// If error storing temporarily, return the error.
126
	if ( is_wp_error( $file_array['tmp_name'] ) ) {
127
		return $file_array['tmp_name'];
128
	}
129
130
	// Do the validation and storage stuff.
131
	$thumbnail_id = media_handle_sideload( $file_array, $attachment_id, null );
132
133
	// Flag it as poster image, so we can exclude it from display.
134
	update_post_meta( $thumbnail_id, 'videopress_poster_image', 1 );
135
136
	return $thumbnail_id;
137
}
138
139
/**
140
 * Creates a local media library item of a remote VideoPress video.
141
 *
142
 * @param $guid
143
 * @param int $parent_id
144
 *
145
 * @return int|object
146
 */
147
function create_local_media_library_for_videopress_guid( $guid, $parent_id = 0 ) {
148
	$vp_data = videopress_get_video_details( $guid );
149
	if ( ! $vp_data || is_wp_error( $vp_data ) ) {
150
		return $vp_data;
151
	}
152
153
	$args = array(
154
		'post_date'      => $vp_data->upload_date,
155
		'post_title'     => wp_kses( $vp_data->title, array() ),
156
		'post_content'   => wp_kses( $vp_data->description, array() ),
157
		'post_mime_type' => 'video/videopress',
158
		'guid'           => sprintf( 'https://videopress.com/v/%s', $guid ),
159
	);
160
161
	$attachment_id = wp_insert_attachment( $args, null, $parent_id );
162
163
	if ( ! is_wp_error( $attachment_id ) ) {
164
		update_post_meta( $attachment_id, 'videopress_guid', $guid );
165
		wp_update_attachment_metadata( $attachment_id, array(
166
			'width'  => $vp_data->width,
167
			'height' => $vp_data->height,
168
		) );
169
170
		$thumbnail_id = videopress_download_poster_image( $vp_data->poster, $attachment_id );
171
		update_post_meta( $attachment_id, '_thumbnail_id', $thumbnail_id );
172
	}
173
174
	return $attachment_id;
175
}
176
177
/**
178
 * Helper that will look for VideoPress media items that are more than 30 minutes old,
179
 * that have not had anything attached to them by a wpcom upload and deletes the ghost
180
 * attachment.
181
 *
182
 * These happen primarily because of failed upload attempts.
183
 *
184
 * @return int The number of items that were cleaned up.
185
 */
186
function videopress_cleanup_media_library() {
187
	$query_args = array(
188
		'post_type'      => 'attachment',
189
		'post_status'    => 'inherit',
190
		'post_mime_type' => 'video/videopress',
191
		'meta_query'     => array(
192
			array(
193
				'key'   => 'videopress_status',
194
				'value' => 'new',
195
			),
196
		)
197
	);
198
199
	$query = new WP_Query( $query_args );
200
201
	$cleaned = 0;
202
203
	$now = current_time( 'timestamp' );
204
205
	if ( $query->have_posts() ) {
206
		foreach ( $query->posts as $post ) {
207
			$post_time = strtotime( $post->post_date_gmt );
208
209
			// If the post is older than 30 minutes, it is safe to delete it.
210
			if ( $now - $post_time > MINUTE_IN_SECONDS * 30 ) {
211
				// Force delete the attachment, because we don't want it appearing in the trash.
212
				wp_delete_attachment( $post->ID, true );
213
214
				$cleaned++;
215
			}
216
		}
217
	}
218
219
	return $cleaned;
220
}
221
222
/**
223
 * Return an absolute URI for a given filename and guid on the CDN.
224
 * No check is performed to ensure the guid exists or the file is present. Simple centralized string builder.
225
 *
226
 * @param string $guid     VideoPress identifier
227
 * @param string $filename name of file associated with the guid (video file name or thumbnail file name)
228
 *
229
 * @return string Absolute URL of VideoPress file for the given guid.
230
 */
231
function videopress_cdn_file_url( $guid, $filename ) {
232
	return "https://videos.files.wordpress.com/{$guid}/{$filename}";
233
}
234
235
/**
236
 * Get an array of the transcoding status for the given video post.
237
 *
238
 * @since 4.4
239
 * @param int $post_id
240
 * @return array|bool Returns an array of statuses if this is a VideoPress post, otherwise it returns false.
241
 */
242
function videopress_get_transcoding_status( $post_id ) {
243
	$meta = wp_get_attachment_metadata( $post_id );
244
245
	// If this has not been processed by videopress, we can skip the rest.
246
	if ( !$meta || ! isset( $meta['videopress'] ) ) {
247
		return false;
248
	}
249
250
	$info = (object) $meta['videopress'];
251
252
	$status = array(
253
		'std_mp4' => isset( $info->files_status['std']['mp4'] ) ? $info->files_status['std']['mp4'] : null,
254
		'std_ogg' => isset( $info->files_status['std']['ogg'] ) ? $info->files_status['std']['ogg'] : null,
255
		'dvd_mp4' => isset( $info->files_status['dvd']['mp4'] ) ? $info->files_status['dvd']['mp4'] : null,
256
		'hd_mp4'  => isset( $info->files_status['hd']['mp4'] )  ? $info->files_status['hd']['mp4']  : null,
257
	);
258
259
	return $status;
260
}
261
262
/**
263
 * Get the direct url to the video.
264
 *
265
 * @since 4.4
266
 * @param string $guid
267
 * @return string
268
 */
269
function videopress_build_url( $guid ) {
270
	return 'https://videopress.com/v/' . $guid;
271
}
272
273
/**
274
 * Create an empty videopress media item that will be filled out later by an xmlrpc
275
 * callback from the VideoPress servers.
276
 *
277
 * @since 4.4
278
 * @param string $title
279
 * @return int|WP_Error
280
 */
281
function videopress_create_new_media_item( $title ) {
282
	$post = array(
283
		'post_type'      => 'attachment',
284
		'post_mime_type' => 'video/videopress',
285
		'post_title'     => $title,
286
		'post_content'   => '',
287
	);
288
289
	$media_id = wp_insert_post( $post );
290
291
	add_post_meta( $media_id, 'videopress_status', 'new' );
292
293
	return $media_id;
294
}
295
296
297
/**
298
 * Check to see if a video has completed processing.
299
 *
300
 * @since 4.4
301
 * @param int $post_id
302
 * @return bool
303
 */
304
function videopress_is_finished_processing( $post_id ) {
305
	$post = get_post( $post_id );
306
307
	if ( is_wp_error( $post ) ) {
308
		return false;
309
	}
310
311
	$meta = wp_get_attachment_metadata( $post->ID );
312
313
	if ( ! isset( $meta['videopress'] ) || ! is_array( $meta['videopress'] ) ) {
314
		return false;
315
	}
316
317
	// These are explicitly declared to avoid doing unnecessary loops across two levels of arrays.
318 View Code Duplication
	if ( isset( $meta['videopress']['files_status']['hd'] ) && $meta['videopress']['files_status']['hd'] != 'DONE' ) {
319
		return false;
320
	}
321
322 View Code Duplication
	if ( isset( $meta['videopress']['files_status']['dvd'] ) && $meta['videopress']['files_status']['dvd'] != 'DONE' ) {
323
		return false;
324
	}
325
326 View Code Duplication
	if ( isset( $meta['videopress']['files_status']['std']['mp4'] ) && $meta['videopress']['files_status']['std']['mp4'] != 'DONE' ) {
327
		return false;
328
	}
329
330 View Code Duplication
	if ( isset( $meta['videopress']['files_status']['std']['ogg'] ) && $meta['videopress']['files_status']['std']['ogg'] != 'DONE' ) {
331
		return false;
332
	}
333
334
	return true;
335
}
336
337
338
/**
339
 * Update the meta information  status for the given video post.
340
 *
341
 * @since 4.4
342
 * @param int $post_id
343
 * @return bool
344
 */
345
function videopress_update_meta_data( $post_id ) {
346
347
	$meta = wp_get_attachment_metadata( $post_id );
348
349
	// If this has not been processed by VideoPress, we can skip the rest.
350
	if ( ! $meta || ! isset( $meta['videopress'] ) ) {
351
		return false;
352
	}
353
354
	$info = (object) $meta['videopress'];
355
356
	$result = wp_remote_get( videopress_make_video_get_path( $info->guid ) );
357
358
	if ( is_wp_error( $result ) ) {
359
		return false;
360
	}
361
362
	$response = json_decode( $result['body'], true );
363
364
	// Update the attachment metadata.
365
	$meta['videopress'] = $response;
366
367
	wp_update_attachment_metadata( $post_id, $meta );
368
369
	return true;
370
}
371
372
373
374
/**
375
 * Get the video update path
376
 *
377
 * @since 4.4
378
 * @param string $guid
379
 * @return string
380
 */
381
function videopress_make_video_get_path( $guid ) {
382
	return sprintf(
383
		'%s://%s/rest/v%s/videos/%s',
384
		'https',
385
		JETPACK__WPCOM_JSON_API_HOST,
386
		Jetpack_Client::WPCOM_JSON_API_VERSION,
387
		$guid
388
	);
389
}
390
391
/**
392
 * Get the upload api path.
393
 *
394
 * @since 4.4
395
 * @param int $blog_id The id of the blog we're uploading to.
396
 * @return string
397
 */
398
function videopress_make_media_upload_path( $blog_id ) {
399
	return sprintf(
400
		'https://%s/rest/v1.1/sites/%s/videos/new',
401
		JETPACK__WPCOM_JSON_API_HOST,
402
		$blog_id
403
	);
404
}