Completed
Push — revert/videopress-uploader ( 93d651 )
by
unknown
08:30
created

utility-functions.php ➔ videopress_get_transcoding_status()   B

Complexity

Conditions 7
Paths 17

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 11
nc 17
nop 1
dl 0
loc 19
rs 8.2222
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 ) {
0 ignored issues
show
Best Practice introduced by
The function videopress_is_valid_guid() has been defined more than once; this definition is ignored, only the first definition in modules/videopress-v2/utility-functions.php (L15-20) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
15 View Code Duplication
	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 ) {
0 ignored issues
show
Best Practice introduced by
The function videopress_get_video_details() has been defined more than once; this definition is ignored, only the first definition in modules/videopress-v2/utility-functions.php (L28-66) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
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 View Code Duplication
function videopress_get_attachment_id_by_url( $url ) {
0 ignored issues
show
Best Practice introduced by
The function videopress_get_attachment_id_by_url() has been defined more than once; this definition is ignored, only the first definition in modules/videopress-v2/utility-functions.php (L80-120) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
Duplication introduced by
This function seems to be duplicated in 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...
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
	return false;
103
}
104
105
/**
106
 * Similar to `media_sideload_image` -- but returns an ID.
107
 *
108
 * @param $url
109
 * @param $attachment_id
110
 *
111
 * @return int|mixed|object|WP_Error
112
 */
113 View Code Duplication
function videopress_download_poster_image( $url, $attachment_id ) {
0 ignored issues
show
Best Practice introduced by
The function videopress_download_poster_image() has been defined more than once; this definition is ignored, only the first definition in modules/videopress-v2/utility-functions.php (L130-153) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
Duplication introduced by
This function seems to be duplicated in 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...
114
	// Set variables for storage, fix file filename for query strings.
115
	preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $url, $matches );
116
	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...
117
		return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL' ) );
118
	}
119
120
	$file_array = array();
121
	$file_array['name']     = basename( $matches[0] );
122
	$file_array['tmp_name'] = download_url( $url );
123
124
	// If error storing temporarily, return the error.
125
	if ( is_wp_error( $file_array['tmp_name'] ) ) {
126
		return $file_array['tmp_name'];
127
	}
128
129
	// Do the validation and storage stuff.
130
	$thumbnail_id = media_handle_sideload( $file_array, $attachment_id, null );
131
132
	// Flag it as poster image, so we can exclude it from display.
133
	update_post_meta( $thumbnail_id, 'videopress_poster_image', 1 );
134
135
	return $thumbnail_id;
136
}
137
138
/**
139
 * Creates a local media library item of a remote VideoPress video.
140
 *
141
 * @param $guid
142
 * @param int $parent_id
143
 *
144
 * @return int|object
145
 */
146 View Code Duplication
function create_local_media_library_for_videopress_guid( $guid, $parent_id = 0 ) {
0 ignored issues
show
Best Practice introduced by
The function create_local_media_library_for_videopress_guid() has been defined more than once; this definition is ignored, only the first definition in modules/videopress-v2/utility-functions.php (L163-191) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
Duplication introduced by
This function seems to be duplicated in 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...
147
	$vp_data = videopress_get_video_details( $guid );
148
	if ( ! $vp_data || is_wp_error( $vp_data ) ) {
149
		return $vp_data;
150
	}
151
152
	$args = array(
153
		'post_date'      => $vp_data->upload_date,
154
		'post_title'     => wp_kses( $vp_data->title, array() ),
155
		'post_content'   => wp_kses( $vp_data->description, array() ),
156
		'post_mime_type' => 'video/videopress',
157
		'guid'           => sprintf( 'https://videopress.com/v/%s', $guid ),
158
	);
159
160
	$attachment_id = wp_insert_attachment( $args, null, $parent_id );
161
162
	if ( ! is_wp_error( $attachment_id ) ) {
163
		update_post_meta( $attachment_id, 'videopress_guid', $guid );
164
		wp_update_attachment_metadata( $attachment_id, array(
165
			'width'  => $vp_data->width,
166
			'height' => $vp_data->height,
167
		) );
168
169
		$thumbnail_id = videopress_download_poster_image( $vp_data->poster, $attachment_id );
170
		update_post_meta( $attachment_id, '_thumbnail_id', $thumbnail_id );
171
	}
172
173
	return $attachment_id;
174
}
175
176
if ( defined( 'WP_CLI' ) && WP_CLI ) {
177
	/**
178
	 * Manage and import VideoPress videos.
179
	 */
180
	class VideoPress_CLI extends WP_CLI_Command {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The type VideoPress_CLI has been defined more than once; this definition is ignored, only the first definition in modules/videopress-v2/class.videopress-cli.php (L8-169) is considered.

This check looks for classes that have been defined more than once.

If you can, we would recommend to use standard object-oriented programming techniques. For example, to avoid multiple types, it might make sense to create a common interface, and then multiple, different implementations for that interface.

This also has the side-effect of providing you with better IDE auto-completion, static analysis and also better OPCode caching from PHP.

Loading history...
181
		/**
182
		 * Import a VideoPress Video
183
		 *
184
		 * ## OPTIONS
185
		 *
186
		 * <guid>: Import the video with the specified guid
187
		 *
188
		 * ## EXAMPLES
189
		 *
190
		 * wp videopress import kUJmAcSf
191
		 *
192
		 */
193 View Code Duplication
		public function import( $args ) {
194
			$guid = $args[0];
195
			$attachment_id = create_local_media_library_for_videopress_guid( $guid );
196
			if ( $attachment_id && ! is_wp_error( $attachment_id ) ) {
197
				WP_CLI::success( sprintf( __( 'The video has been imported as Attachment ID %d', 'jetpack' ), $attachment_id ) );
198
			} else {
199
				WP_CLI::error( __( 'An error has been encountered.', 'jetpack' ) );
200
			}
201
		}
202
	}
203
	WP_CLI::add_command( 'videopress', 'VideoPress_CLI' );
204
}
205