summaryrefslogtreecommitdiff
blob: 947f7552660050735a7abe3c6288da03f0e0559f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
<?php

/**
 * We won't have any videos less than sixty pixels wide. That would be silly.
 */
defined( 'VIDEOPRESS_MIN_WIDTH' ) or define( 'VIDEOPRESS_MIN_WIDTH', 60 );

/**
 * Validate user-supplied guid values against expected inputs
 *
 * @since 1.1
 * @param string $guid video identifier
 * @return bool true if passes validation test
 */
function videopress_is_valid_guid( $guid ) {
	if ( ! empty( $guid ) && is_string( $guid ) && strlen( $guid ) === 8 && ctype_alnum( $guid ) ) {
		return true;
	}
	return false;
}

/**
 * Get details about a specific video by GUID:
 *
 * @param $guid string
 * @return object
 */
function videopress_get_video_details( $guid ) {
	if ( ! videopress_is_valid_guid( $guid ) ) {
		return new WP_Error( 'bad-guid-format', __( 'Invalid Video GUID!', 'jetpack' ) );
	}

	$version  = '1.1';
	$endpoint = sprintf( '/videos/%1$s', $guid );
	$query_url = sprintf(
		'https://public-api.wordpress.com/rest/v%1$s%2$s',
		$version,
		$endpoint
	);

	// Look for data in our transient. If nothing, let's make a new query.
	$data_from_cache = get_transient( 'jetpack_videopress_' . $guid );
	if ( false === $data_from_cache ) {
		$response = wp_remote_get( esc_url_raw( $query_url ) );
		$data     = json_decode( wp_remote_retrieve_body( $response ) );

		// Cache the response for an hour.
		set_transient( 'jetpack_videopress_' . $guid, $data, HOUR_IN_SECONDS );
	} else {
		$data = $data_from_cache;
	}

	/**
	 * Allow functions to modify fetched video details.
	 *
	 * This filter allows third-party code to modify the return data
	 * about a given video.  It may involve swapping some data out or
	 * adding new parameters.
	 *
	 * @since 4.0.0
	 *
	 * @param object $data The data returned by the WPCOM API. See: https://developer.wordpress.com/docs/api/1.1/get/videos/%24guid/
	 * @param string $guid The GUID of the VideoPress video in question.
	 */
	return apply_filters( 'videopress_get_video_details', $data, $guid );
}


/**
 * Get an attachment ID given a URL.
 *
 * Modified from http://wpscholar.com/blog/get-attachment-id-from-wp-image-url/
 *
 * @todo: Add some caching in here.
 *
 * @param string $url
 *
 * @return int|bool Attachment ID on success, false on failure
 */
function videopress_get_attachment_id_by_url( $url ) {
	$wp_upload_dir = wp_upload_dir();
	// Strip out protocols, so it doesn't fail because searching for http: in https: dir.
	$dir = set_url_scheme( trailingslashit( $wp_upload_dir['baseurl'] ), 'relative' );

	// Is URL in uploads directory?
	if ( false !== strpos( $url, $dir ) ) {

		$file = basename( $url );

		$query_args = array(
			'post_type'   => 'attachment',
			'post_status' => 'inherit',
			'fields'      => 'ids',
			'meta_query'  => array(
				array(
					'key'     => '_wp_attachment_metadata',
					'compare' => 'LIKE',
					'value'   => $file,
				),
			)
		);

		$query = new WP_Query( $query_args );

		if ( $query->have_posts() ) {
			foreach ( $query->posts as $attachment_id ) {
				$meta          = wp_get_attachment_metadata( $attachment_id );
				$original_file = basename( $meta['file'] );
				$cropped_files = wp_list_pluck( $meta['sizes'], 'file' );

				if ( $original_file === $file || in_array( $file, $cropped_files ) ) {
					return (int) $attachment_id;
				}
			}
		}

	}

	return false;
}

/**
 * Similar to `media_sideload_image` -- but returns an ID.
 *
 * @param $url
 * @param $attachment_id
 *
 * @return int|mixed|object|WP_Error
 */
function videopress_download_poster_image( $url, $attachment_id ) {
	// Set variables for storage, fix file filename for query strings.
	preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $url, $matches );
	if ( ! $matches ) {
		return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL', 'jetpack' ) );
	}

	$file_array = array();
	$file_array['name']     = basename( $matches[0] );
	$file_array['tmp_name'] = download_url( $url );

	// If error storing temporarily, return the error.
	if ( is_wp_error( $file_array['tmp_name'] ) ) {
		return $file_array['tmp_name'];
	}

	// Do the validation and storage stuff.
	$thumbnail_id = media_handle_sideload( $file_array, $attachment_id, null );

	// Flag it as poster image, so we can exclude it from display.
	update_post_meta( $thumbnail_id, 'videopress_poster_image', 1 );

	return $thumbnail_id;
}

/**
 * Creates a local media library item of a remote VideoPress video.
 *
 * @param $guid
 * @param int $parent_id
 *
 * @return int|object
 */
function create_local_media_library_for_videopress_guid( $guid, $parent_id = 0 ) {
	$vp_data = videopress_get_video_details( $guid );
	if ( ! $vp_data || is_wp_error( $vp_data ) ) {
		return $vp_data;
	}

	$args = array(
		'post_date'      => $vp_data->upload_date,
		'post_title'     => wp_kses( $vp_data->title, array() ),
		'post_content'   => wp_kses( $vp_data->description, array() ),
		'post_mime_type' => 'video/videopress',
		'guid'           => sprintf( 'https://videopress.com/v/%s', $guid ),
	);

	$attachment_id = wp_insert_attachment( $args, null, $parent_id );

	if ( ! is_wp_error( $attachment_id ) ) {
		update_post_meta( $attachment_id, 'videopress_guid', $guid );
		wp_update_attachment_metadata( $attachment_id, array(
			'width'  => $vp_data->width,
			'height' => $vp_data->height,
		) );

		$thumbnail_id = videopress_download_poster_image( $vp_data->poster, $attachment_id );
		update_post_meta( $attachment_id, '_thumbnail_id', $thumbnail_id );
	}

	return $attachment_id;
}

/**
 * Helper that will look for VideoPress media items that are more than 30 minutes old,
 * that have not had anything attached to them by a wpcom upload and deletes the ghost
 * attachment.
 *
 * These happen primarily because of failed upload attempts.
 *
 * @return int The number of items that were cleaned up.
 */
function videopress_cleanup_media_library() {

	// Disable this job for now.
	return 0;
	$query_args = array(
		'post_type'      => 'attachment',
		'post_status'    => 'inherit',
		'post_mime_type' => 'video/videopress',
		'meta_query'     => array(
			array(
				'key'   => 'videopress_status',
				'value' => 'new',
			),
		)
	);

	$query = new WP_Query( $query_args );

	$cleaned = 0;

	$now = current_time( 'timestamp' );

	if ( $query->have_posts() ) {
		foreach ( $query->posts as $post ) {
			$post_time = strtotime( $post->post_date_gmt );

			// If the post is older than 30 minutes, it is safe to delete it.
			if ( $now - $post_time > MINUTE_IN_SECONDS * 30 ) {
				// Force delete the attachment, because we don't want it appearing in the trash.
				wp_delete_attachment( $post->ID, true );

				$cleaned++;
			}
		}
	}

	return $cleaned;
}

/**
 * Return an absolute URI for a given filename and guid on the CDN.
 * No check is performed to ensure the guid exists or the file is present. Simple centralized string builder.
 *
 * @param string $guid     VideoPress identifier
 * @param string $filename name of file associated with the guid (video file name or thumbnail file name)
 *
 * @return string Absolute URL of VideoPress file for the given guid.
 */
function videopress_cdn_file_url( $guid, $filename ) {
	return "https://videos.files.wordpress.com/{$guid}/{$filename}";
}

/**
 * Get an array of the transcoding status for the given video post.
 *
 * @since 4.4
 * @param int $post_id
 * @return array|bool Returns an array of statuses if this is a VideoPress post, otherwise it returns false.
 */
function videopress_get_transcoding_status( $post_id ) {
	$meta = wp_get_attachment_metadata( $post_id );

	// If this has not been processed by videopress, we can skip the rest.
	if ( ! $meta || ! isset( $meta['file_statuses'] ) ) {
		return false;
	}

	$info = (object) $meta['file_statuses'];

	$status = array(
		'std_mp4' => isset( $info->mp4 ) ? $info->mp4 : null,
		'std_ogg' => isset( $info->ogg ) ? $info->ogg : null,
		'dvd_mp4' => isset( $info->dvd ) ? $info->dvd : null,
		'hd_mp4'  => isset( $info->hd )  ? $info->hd : null,
	);

	return $status;
}

/**
 * Get the direct url to the video.
 *
 * @since 4.4
 * @param string $guid
 * @return string
 */
function videopress_build_url( $guid ) {

	// No guid, no videopress url.
	if ( ! $guid ) {
		return '';
	}

	return 'https://videopress.com/v/' . $guid;
}

/**
 * Create an empty videopress media item that will be filled out later by an xmlrpc
 * callback from the VideoPress servers.
 *
 * @since 4.4
 * @param string $title
 * @return int|WP_Error
 */
function videopress_create_new_media_item( $title, $guid = null ) {
	$post = array(
		'post_type'      => 'attachment',
		'post_mime_type' => 'video/videopress',
		'post_title'     => $title,
		'post_content'   => '',
		'guid'           => videopress_build_url( $guid ),
	);

	$media_id = wp_insert_post( $post );

	add_post_meta( $media_id, 'videopress_status', 'initiated' );

	add_post_meta( $media_id, 'videopress_guid', $guid );

	return $media_id;
}


/**
 * @param array $current_status
 * @param array $new_meta
 * @return array
 */
function videopress_merge_file_status( $current_status, $new_meta ) {
	$new_statuses = array();

	if ( isset( $new_meta['videopress']['files_status']['hd'] ) ) {
		$new_statuses['hd'] = $new_meta['videopress']['files_status']['hd'];
	}

	if ( isset( $new_meta['videopress']['files_status']['dvd'] ) ) {
		$new_statuses['dvd'] = $new_meta['videopress']['files_status']['dvd'];
	}

	if ( isset( $new_meta['videopress']['files_status']['std']['mp4'] ) ) {
		$new_statuses['mp4'] = $new_meta['videopress']['files_status']['std']['mp4'];
	}

	if ( isset( $new_meta['videopress']['files_status']['std']['ogg'] ) ) {
		$new_statuses['ogg'] = $new_meta['videopress']['files_status']['std']['ogg'];
	}

	foreach ( $new_statuses as $format => $status ) {
		if ( ! isset( $current_status[ $format ] ) ) {
			$current_status[ $format ] = $status;
			continue;
		}

		if ( $current_status[ $format ] !== 'DONE' ) {
			$current_status[ $format ] = $status;
		}
	}

	return $current_status;
}

/**
 * Check to see if a video has completed processing.
 *
 * @since 4.4
 * @param int $post_id
 * @return bool
 */
function videopress_is_finished_processing( $post_id ) {
	$post = get_post( $post_id );

	if ( is_wp_error( $post ) ) {
		return false;
	}

	$meta = wp_get_attachment_metadata( $post->ID );

	if ( ! isset( $meta['file_statuses'] ) || ! is_array( $meta['file_statuses'] ) ) {
		return false;
	}

	$check_statuses = array( 'hd', 'dvd', 'mp4', 'ogg' );

	foreach ( $check_statuses as $status ) {
		if ( ! isset( $meta['file_statuses'][ $status ] ) || $meta['file_statuses'][ $status ] != 'DONE' ) {
			return false;
		}
	}

	return true;
}


/**
 * Update the meta information  status for the given video post.
 *
 * @since 4.4
 * @param int $post_id
 * @return bool
 */
function videopress_update_meta_data( $post_id ) {

	$meta = wp_get_attachment_metadata( $post_id );

	// If this has not been processed by VideoPress, we can skip the rest.
	if ( ! $meta || ! isset( $meta['videopress'] ) ) {
		return false;
	}

	$info = (object) $meta['videopress'];

	$args = array(
		// 'sslverify' => false,
	);

	$result = wp_remote_get( videopress_make_video_get_path( $info->guid ), $args );

	if ( is_wp_error( $result ) ) {
		return false;
	}

	$response = json_decode( $result['body'], true );

	// Update the attachment metadata.
	$meta['videopress'] = $response;

	wp_update_attachment_metadata( $post_id, $meta );

	return true;
}

/**
 * Check to see if this is a VideoPress post that hasn't had a guid set yet.
 *
 * @param int $post_id
 * @return bool
 */
function videopress_is_attachment_without_guid( $post_id ) {
	$post = get_post( $post_id );

	if ( is_wp_error( $post ) ) {
		return false;
	}

	if ( $post->post_mime_type !== 'video/videopress' ) {
		return false;
	}

	$videopress_guid = get_post_meta( $post_id, 'videopress_guid', true );

	if ( $videopress_guid ) {
		return false;
	}

	return true;
}

/**
 * Check to see if this is a VideoPress attachment.
 *
 * @param int $post_id
 * @return bool
 */
function is_videopress_attachment( $post_id ) {
	$post = get_post( $post_id );

	if ( is_wp_error( $post ) ) {
		return false;
	}

	if ( $post->post_mime_type !== 'video/videopress' ) {
		return false;
	}

	return true;
}

/**
 * Get the video update path
 *
 * @since 4.4
 * @param string $guid
 * @return string
 */
function videopress_make_video_get_path( $guid ) {
	return sprintf(
		'%s://%s/rest/v%s/videos/%s',
		'https',
		JETPACK__WPCOM_JSON_API_HOST,
		Jetpack_Client::WPCOM_JSON_API_VERSION,
		$guid
	);
}

/**
 * Get the upload api path.
 *
 * @since 4.4
 * @param int $blog_id The id of the blog we're uploading to.
 * @return string
 */
function videopress_make_media_upload_path( $blog_id ) {
	return sprintf(
		'https://public-api.wordpress.com/rest/v1.1/sites/%s/media/new',
		$blog_id
	);
}

/**
 * This is a mock of the internal VideoPress method, which is meant to duplicate the functionality
 * of the WPCOM API, so that the Jetpack REST API returns the same data with no modifications.
 *
 * @param int $blog_id Blog ID.
 * @param int $post_id Post ID.
 * @return bool|stdClass
 */
function video_get_info_by_blogpostid( $blog_id, $post_id ) {
	$post = get_post( $post_id );

	$video_info = new stdClass();
	$video_info->post_id = $post_id;
	$video_info->blog_id = $blog_id;
	$video_info->guid = null;
	$video_info->finish_date_gmt = '0000-00-00 00:00:00';

	if ( is_wp_error( $post ) ) {
		return $video_info;
	}

	if ( 'video/videopress' !== $post->post_mime_type ) {
		return $video_info;
	}

	// Since this is a VideoPress post, lt's fill out the rest of the object.
	$video_info->guid = get_post_meta( $post_id, 'videopress_guid', true );

	if ( videopress_is_finished_processing( $post_id ) ) {
		$video_info->finish_date_gmt = date( 'Y-m-d H:i:s' );
	}

	return $video_info;
}


/**
 * Check that a VideoPress video format has finished processing.
 *
 * This uses the info object, because that is what the WPCOM endpoint
 * uses, however we don't have a complete info object in the same way
 * WPCOM does, so we pull the meta information out of the post
 * options instead.
 *
 * Note: This mimics the WPCOM function of the same name and helps the media
 * API endpoint add all needed VideoPress data.
 *
 * @param stdClass $info
 * @param string $format
 * @return bool
 */
function video_format_done( $info, $format ) {

	// Avoids notice when a non-videopress item is found.
	if ( ! is_object( $info ) ) {
		return false;
	}

	$post_id = $info->post_id;

	if ( get_post_mime_type( $post_id ) !== 'video/videopress' ) {
		return false;
	}

	$post = get_post( $post_id );

	if ( is_wp_error( $post ) ) {
		return false;
	}

	$meta = wp_get_attachment_metadata( $post->ID );

	switch ( $format ) {
		case 'fmt_hd':
			return isset( $meta['videopress']['files']['hd']['mp4'] );
			break;

		case 'fmt_dvd':
			return isset( $meta['videopress']['files']['dvd']['mp4'] );
			break;

		case 'fmt_std':
			return isset( $meta['videopress']['files']['std']['mp4'] );
			break;

		case 'fmt_ogg':
			return isset( $meta['videopress']['files']['std']['ogg'] );
			break;
	}

	return false;
}

/**
 * Get the image URL for the given VideoPress GUID
 *
 * We look up by GUID, because that is what WPCOM does and this needs to be
 * parameter compatible with that.
 *
 * Note: This mimics the WPCOM function of the same name and helps the media
 * API endpoint add all needed VideoPress data.
 *
 * @param string $guid
 * @param string $format
 * @return string
 */
function video_image_url_by_guid( $guid, $format ) {

	$post = video_get_post_by_guid( $guid );

	if ( is_wp_error( $post ) ) {
		return null;
	}

	$meta = wp_get_attachment_metadata( $post->ID );

	// We add ssl => 1 to make sure that the videos.files.wordpress.com domain is parsed as photon.
	$poster = apply_filters( 'jetpack_photon_url', $meta['videopress']['poster'], array( 'ssl' => 1 ), 'https' );

	return $poster;
}

/**
 * Using a GUID, find a post.
 *
 * @param string $guid
 * @return WP_Post
 */
function video_get_post_by_guid( $guid ) {
	$args = array(
		'post_type' 	 => 'attachment',
		'post_mime_type' => 'video/videopress',
		'post_status' 	 => 'inherit',
		'meta_query' 	 => array(
			array(
				'key' 	  => 'videopress_guid',
				'value'   => $guid,
				'compare' => '=',
			)
		)
	);

	$query = new WP_Query( $args );

	$post = $query->next_post();

	return $post;
}

/**
 * From the given VideoPress post_id, return back the appropriate attachment URL.
 *
 * When the MP4 hasn't been processed yet or this is not a VideoPress video, this will return null.
 *
 * @param int $post_id
 * @return string|null
 */
function videopress_get_attachment_url( $post_id ) {

	// We only handle VideoPress attachments.
	if ( get_post_mime_type( $post_id ) !== 'video/videopress' ) {
		return null;
	}

	$meta = wp_get_attachment_metadata( $post_id );

	if ( ! isset( $meta['videopress']['files']['hd']['mp4'] ) ) {
		// Use the original file as the url if it isn't transcoded yet.
		if ( isset( $meta['original'] ) ) {
			return $meta['original'];
		}

		// Otherwise, there isn't much we can do.
		return null;
	}

	return $meta['videopress']['file_url_base']['https'] . $meta['videopress']['files']['hd']['mp4'];
}