GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 9c0c8a...f2b063 )
by Brad
05:17 queued 02:45
created

FooGallery_Pro_Video_Import::handle_import()   B

Complexity

Conditions 9
Paths 11

Size

Total Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
nc 11
nop 1
dl 0
loc 62
rs 7.2735
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 14 and the first side effect is on line 12.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
/**
4
 * Created by PhpStorm.
5
 * User: steve
6
 * Date: 4/17/2018
7
 * Time: 10:09 PM
8
 */
9
10
if ( ! class_exists( "FooGallery_Pro_Video_Import" ) ) {
11
12
	require_once dirname( __FILE__ ) . '/class-foogallery-pro-video-base.php';
13
14
	class FooGallery_Pro_Video_Import extends FooGallery_Pro_Video_Base {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
15
16
		function __construct() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
17
18
			add_action( 'wp_ajax_fgi_import', array( $this, 'ajax' ) );
19
20
		}
21
22
		public function get_args() {
23
			return array(
24
				"videos" => $this->get_videos_arg(),
25
				"nonce"  => ! empty( $_POST["fgi_nonce"] ) ? $_POST["fgi_nonce"] : null
26
			);
27
		}
28
29
		private function get_videos_arg() {
30
			$videos = array();
31
			if ( empty( $_POST["videos"] ) ) {
32
				return $videos;
33
			}
34
			foreach ( $_POST["videos"] as $video ) {
35
				$videos[] = is_array( $video ) ? $video : json_decode( stripslashes( $video ), true );
36
			}
37
38
			return $videos;
39
		}
40
41
		public function ajax() {
42
			$args = $this->get_args();
43
			if ( wp_verify_nonce( $args["nonce"], "fgi_nonce" ) ) {
44
				if ( empty( $args["videos"] ) || ! is_array( $args["videos"] ) ) {
45
					wp_send_json_error( "The 'videos' argument is required and must be an array." );
46
47
					return;
48
				}
49
				$response = $this->handle_import( $args["videos"] );
50
				wp_send_json_success( $response );
51
			}
52
			die();
53
		}
54
55
		public function handle_import( $videos ) {
56
			$response = array(
57
				"mode"     => "import-result",
58
				"imported" => array(),
59
				"failed"   => array(),
60
				"errors"	 => array()
61
			);
62
63
			$video_types = array(
64
				'youtube',
65
				'vimeo',
66
				'wistia-inc',
67
				'dailymotion'
68
			);
69
70
			foreach ( $videos as $video ) {
71
				//set the default type to "video"
72
				$video["type"] = 'embed';
73
74
				if ( in_array( $video['provider'], $video_types ) ) {
75
					$video["type"] = 'video';
76
				}
77
78
				if ( isset( $video["urls"] ) ) {
79
					// handle self-hosted import
80
					$video["type"] = 'video';
81
					$url = "";
82
					foreach ( $video["urls"] as $type => $value ) {
83
						if ( ! empty( $value ) ) {
84
							if ( ! empty( $url ) ) {
85
								$url .= ",";
86
							}
87
							$url .= $value;
88
						}
89
					}
90
					if ( empty( $url ) ) {
91
						$response["failed"][] = $video;
92
						$response["errors"][] = "No urls provided.";
93
						continue;
94
					} else {
95
						$video["url"] = $url;
96
					}
97
				}
98
				$result = $this->create_attachment( $video );
99
				if ( $result["type"] === "error" ) {
100
					$response["failed"][] = $video;
101
					$response["errors"][] =  $result["message"];
102
				} else {
103
					$response["imported"][] = $result["attachment_id"];
104
					// Save alt text in the post meta
105
					update_post_meta( $result["attachment_id"], "_wp_attachment_image_alt", $video["title"] );
106
					// Save the URL that we will be opening
107
					update_post_meta( $result["attachment_id"], "_foogallery_custom_url", $video["url"] );
108
					// Make sure we open in new tab by default
109
					update_post_meta( $result["attachment_id"], "_foogallery_custom_target", foogallery_get_setting( "video_default_target", "_blank" ) );
0 ignored issues
show
Documentation introduced by
'_blank' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
110
					//save video object
111
					update_post_meta( $result["attachment_id"], FOOGALLERY_VIDEO_POST_META, $video );
112
				}
113
			}
114
115
			return $response;
116
		}
117
118
		private function create_attachment( &$video ) {
119
			//allow for really big imports that take a really long time!
120
			@set_time_limit( 300 );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
121
122
			$video["thumbnail"] = $this->get_thumbnail_url( $video );
123
124
			$thumbnail = file_get_contents( $video["thumbnail"] );
125
			$filetype = wp_check_filetype( $video["thumbnail"], null );
126
127
			$thumbnail_filename = $video["id"] . '.' . $filetype['ext'];
128
129
//			$response = wp_remote_get( $video["thumbnail"] );
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
130
//
131
//			if ( is_wp_error( $response ) ) {
132
//				return array(
133
//					"type" => "error",
134
//					"message" => $response->get_error_message()
135
//				);
136
//			}
137
//
138
//			$response_code = wp_remote_retrieve_response_code( $response );
139
//			if ( 200 !== $response_code ) {
140
//				return array(
141
//					"type" => "error",
142
//					"message" => "Unable to retrieve thumbnail due to error " . $response_code
143
//				);
144
//			}
145
//
146
//			$thumbnail          = wp_remote_retrieve_body( $response );
147
//			if ( empty($thumbnail) ) {
148
//				return array(
149
//					"type" => "error",
150
//					"message" => "Unable to retrieve response body for thumbnail."
151
//				);
152
//			}
153
//
154
//			$thumbnail_filename = $this->get_thumbnail_filename( $video, $response );
155
//			if ($thumbnail_filename === false){
156
//				return array(
157
//					"type" => "error",
158
//					"message" => "Unable to generate thumbnail filename from response."
159
//				);
160
//			}
161
162
			$upload = wp_upload_bits( $thumbnail_filename, null, $thumbnail );
163
			if ($upload["error"] !== false){
164
				return array(
165
					"type" => "error",
166
					"message" => $upload["error"] === true ? "Unknown error uploading thumbnail image." : $upload["error"]
167
				);
168
			}
169
170
			$guid   = $upload["url"];
171
			$file   = $upload["file"];
172
173
			// Create attachment
174
			$attachment = array(
175
				'ID'             => 0,
176
				'guid'           => $guid,
177
				'post_title'     => $video["title"],
178
				'post_excerpt'   => $video["title"],
179
				'post_content'   => $video["description"],
180
				'post_date'      => '',
181
				'post_mime_type' => 'image/foogallery'
182
			);
183
184
			// Include image.php so we can call wp_generate_attachment_metadata()
185
			require_once( ABSPATH . 'wp-admin/includes/image.php' );
186
187
			// Insert the attachment
188
			$attachment_id   = wp_insert_attachment( $attachment, $file, 0 );
189
			if ($attachment_id == 0 || is_wp_error($attachment_id)){
190
				return array(
191
					"type" => "error",
192
					"message" => is_wp_error($attachment_id) ? $attachment_id->get_error_message() : "Failed to insert the attachment."
193
				);
194
			}
195
			$attachment_data = wp_generate_attachment_metadata( $attachment_id, $file );
196
			wp_update_attachment_metadata( $attachment_id, $attachment_data );
197
198
			$thumbnail_details  = wp_get_attachment_image_src( $attachment_id, 'thumbnail' ); // Yes we have the data, but get the thumbnail URL anyway, to be safe
199
			if ($thumbnail_details === false){
200
				return array(
201
					"type" => "error",
202
					"message" => "Unable to retrieve thumbnail details."
203
				);
204
			}
205
			$video["thumbnail"] = $thumbnail_details[0];
206
207
			return array(
208
				"type" => "success",
209
				"attachment_id" => $attachment_id
210
			);
211
		}
212
213
		private function get_thumbnail_url( $video ) {
214
			if ( ! empty( $video["provider"] ) ) {
215
				switch ( $video["provider"] ) {
216
					case "youtube":
217
						$format = "http://img.youtube.com/vi/%1s/%2s.jpg";
218
						/**
219
						 * Possible filenames for images, in order of desirability. Should only ever use first one.
220
						 * @see http://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
221
						 */
222
						$sizes = array(
223
							'maxresdefault',
224
							'hqdefault',
225
							'sddefault',
226
							'default',
227
							'0'
228
						);
229
						foreach ( $sizes as $size ) {
230
							$url = sprintf( $format, $video["id"], $size );
231
							if ( $this->url_exists( $url ) ) {
232
								return $url;
233
							}
234
						}
235
						break;
236
				}
237
			}
238
239
			return $video["thumbnail"];
240
		}
241
242
		private $image_mimes = array(
243
			"png" => array("image/png", "image/x-png"),
244
			"bmp" => array("image/bmp", "image/x-bmp", "image/x-bitmap", "image/x-xbitmap", "image/x-win-bitmap", "image/x-windows-bmp", "image/ms-bmp", "image/x-ms-bmp", "application/bmp", "application/x-bmp","application/x-win-bitmap"),
245
			"gif" => array("image/bmp", "image/x-bmp"),
246
			"jpeg" => array("image/jpeg", "image/pjpeg"),
247
			"svg" => array("image/svg+xml"),
248
			"jp2" => array("image/jp2", "image/jpx", "image/jpm"),
249
			"tiff" => array("image/tiff"),
250
			"ico" => array("image/x-icon", "image/x-ico", "image/vnd.microsoft.icon")
251
		);
252
253
		private function mime2ext($mime){
254
			foreach ($this->image_mimes as $key => $value) {
255
				if(array_search($mime,$value) !== false) return $key;
256
			}
257
			return false;
258
		}
259
260
		private function url2ext($url){
261
			$parts = parse_url($url);
262
			$ext = pathinfo( basename( $parts["path"] ), PATHINFO_EXTENSION );
263
			return array_key_exists($ext, $this->image_mimes) ? $ext : false;
264
		}
265
266
		private function get_thumbnail_filename( $video, $response ) {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
267
			$headers = $response["headers"];
268
			if ( isset($headers["content-type"]) ){
269
				$ext = $this->mime2ext($headers["content-type"]);
270
			} else {
271
				$ext = $this->url2ext($video["thumbnail"]);
272
			}
273
			return $ext === false ? false : $video["id"] . '.' . $ext;
274
		}
275
	}
276
}
277