Completed
Push — prepare/4.1 ( 0b4dc2...26fe0a )
by Jeremy
279:11 queued 269:16
created

VideoPress_CLI::import()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 5
Ratio 55.56 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 5
loc 9
rs 9.6666
cc 3
eloc 7
nc 2
nop 1
1
<?php
2
3
/**
4
 * Validate user-supplied guid values against expected inputs
5
 *
6
 * @since 1.1
7
 * @param string $guid video identifier
8
 * @return bool true if passes validation test
9
 */
10
function videopress_is_valid_guid( $guid ) {
11
	if ( ! empty( $guid ) && strlen( $guid ) === 8 && ctype_alnum( $guid ) ) {
12
		return true;
13
	}
14
	return false;
15
}
16
17
/**
18
 * Get details about a specific video by GUID:
19
 *
20
 * @param $guid string
21
 * @return object
22
 */
23
function videopress_get_video_details( $guid ) {
24
	if ( ! videopress_is_valid_guid( $guid ) ) {
25
		return new WP_Error( 'bad-guid-format', __( 'Invalid Video GUID!', 'jetpack' ) );
26
	}
27
28
	$version  = '1.1';
29
	$endpoint = sprintf( '/videos/%1$s', $guid );
30
	$response = wp_remote_get( sprintf( 'https://public-api.wordpress.com/rest/v%1$s%2$s', $version, $endpoint ) );
31
	$data     = json_decode( wp_remote_retrieve_body( $response ) );
32
33
	/**
34
	 * Allow functions to modify fetched video details.
35
	 *
36
	 * This filter allows third-party code to modify the return data
37
	 * about a given video.  It may involve swapping some data out or
38
	 * adding new parameters.
39
	 *
40
	 * @since 4.0.0
41
	 *
42
	 * @param object $data The data returned by the WPCOM API. See: https://developer.wordpress.com/docs/api/1.1/get/videos/%24guid/
43
	 * @param string $guid The GUID of the VideoPress video in question.
44
	 */
45
	return apply_filters( 'videopress_get_video_details', $data, $guid );
46
}
47
48
49
/**
50
 * Get an attachment ID given a URL.
51
 *
52
 * Modified from http://wpscholar.com/blog/get-attachment-id-from-wp-image-url/
53
 *
54
 * @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...
55
 *
56
 * @param string $url
57
 *
58
 * @return int|bool Attachment ID on success, false on failure
59
 */
60
function videopress_get_attachment_id_by_url( $url ) {
61
	$wp_upload_dir = wp_upload_dir();
62
	// Strip out protocols, so it doesn't fail because searching for http: in https: dir.
63
	$dir = set_url_scheme( trailingslashit( $wp_upload_dir['baseurl'] ), 'relative' );
64
65
	// Is URL in uploads directory?
66
	if ( false !== strpos( $url, $dir ) ) {
67
68
		$file = basename( $url );
69
70
		$query_args = array(
71
			'post_type'   => 'attachment',
72
			'post_status' => 'inherit',
73
			'fields'      => 'ids',
74
			'meta_query'  => array(
75
				array(
76
					'key'     => '_wp_attachment_metadata',
77
					'compare' => 'LIKE',
78
					'value'   => $file,
79
				),
80
			)
81
		);
82
83
		$query = new WP_Query( $query_args );
84
85
		if ( $query->have_posts() ) {
86
			foreach ( $query->posts as $attachment_id ) {
87
				$meta          = wp_get_attachment_metadata( $attachment_id );
88
				$original_file = basename( $meta['file'] );
89
				$cropped_files = wp_list_pluck( $meta['sizes'], 'file' );
90
91
				if ( $original_file === $file || in_array( $file, $cropped_files ) ) {
92
					return (int) $attachment_id;
93
				}
94
			}
95
		}
96
97
	}
98
	return false;
99
}
100
101
/**
102
 * Similar to `media_sideload_image` -- but returns an ID.
103
 *
104
 * @param $url
105
 * @param $attachment_id
106
 *
107
 * @return int|mixed|object|WP_Error
108
 */
109
function videopress_download_poster_image( $url, $attachment_id ) {
110
	// Set variables for storage, fix file filename for query strings.
111
	preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $url, $matches );
112
	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...
113
		return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL' ) );
114
	}
115
116
	$file_array = array();
117
	$file_array['name']     = basename( $matches[0] );
118
	$file_array['tmp_name'] = download_url( $url );
119
120
	// If error storing temporarily, return the error.
121
	if ( is_wp_error( $file_array['tmp_name'] ) ) {
122
		return $file_array['tmp_name'];
123
	}
124
125
	// Do the validation and storage stuff.
126
	$thumbnail_id = media_handle_sideload( $file_array, $attachment_id, null );
127
128
	// Flag it as poster image, so we can exclude it from display.
129
	update_post_meta( $thumbnail_id, 'videopress_poster_image', 1 );
130
131
	return $thumbnail_id;
132
}
133
134
/**
135
 * Creates a local media library item of a remote VideoPress video.
136
 *
137
 * @param $guid
138
 * @param int $parent_id
139
 *
140
 * @return int|object
141
 */
142
function create_local_media_library_for_videopress_guid( $guid, $parent_id = 0 ) {
143
	$vp_data = videopress_get_video_details( $guid );
144
	if ( ! $vp_data || is_wp_error( $vp_data ) ) {
145
		return $vp_data;
146
	}
147
148
	$args = array(
149
		'post_date'      => $vp_data->upload_date,
150
		'post_title'     => wp_kses( $vp_data->title, array() ),
151
		'post_content'   => wp_kses( $vp_data->description, array() ),
152
		'post_mime_type' => 'video/videopress',
153
		'guid'           => sprintf( 'https://videopress.com/v/%s', $guid ),
154
	);
155
156
	$attachment_id = wp_insert_attachment( $args, null, $parent_id );
157
158
	if ( ! is_wp_error( $attachment_id ) ) {
159
		update_post_meta( $attachment_id, 'videopress_guid', $guid );
160
		wp_update_attachment_metadata( $attachment_id, array(
161
			'width'  => $vp_data->width,
162
			'height' => $vp_data->height,
163
		) );
164
165
		$thumbnail_id = videopress_download_poster_image( $vp_data->poster, $attachment_id );
166
		update_post_meta( $attachment_id, '_thumbnail_id', $thumbnail_id );
167
	}
168
169
	return $attachment_id;
170
}
171
172
if ( defined( 'WP_CLI' ) && WP_CLI ) {
173
	/**
174
	 * Manage and import VideoPress videos.
175
	 */
176
	class VideoPress_CLI extends WP_CLI_Command {
177
		/**
178
		 * Import a VideoPress Video
179
		 *
180
		 * ## OPTIONS
181
		 *
182
		 * <guid>: Import the video with the specified guid
183
		 *
184
		 * ## EXAMPLES
185
		 *
186
		 * wp videopress import kUJmAcSf
187
		 *
188
		 */
189
		public function import( $args ) {
190
			$guid = $args[0];
191
			$attachment_id = create_local_media_library_for_videopress_guid( $guid );
192 View Code Duplication
			if ( $attachment_id && ! is_wp_error( $attachment_id ) ) {
193
				WP_CLI::success( sprintf( __( 'The video has been imported as Attachment ID %d', 'jetpack' ), $attachment_id ) );
194
			} else {
195
				WP_CLI::error( __( 'An error has been encountered.', 'jetpack' ) );
196
			}
197
		}
198
	}
199
	WP_CLI::add_command( 'videopress', 'VideoPress_CLI' );
200
}
201