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 ( b3ee5f...a83cd4 )
by Brad
06:08 queued 03:01
created

FooGallery_Pro_Video_Import::create_attachment()   C

Complexity

Conditions 10
Paths 9

Size

Total Lines 83

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
nc 9
nop 1
dl 0
loc 83
rs 6.5042
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
			$response = wp_remote_get( $video["thumbnail"] );
124
125
			if ( is_wp_error( $response ) ) {
126
				return array(
127
					"type" => "error",
128
					"message" => $response->get_error_message()
129
				);
130
			}
131
132
			$response_code = wp_remote_retrieve_response_code( $response );
133
			if ( 200 !== $response_code ) {
134
				return array(
135
					"type" => "error",
136
					"message" => "Unable to retrieve thumbnail due to error " . $response_code
137
				);
138
			}
139
140
			$thumbnail          = wp_remote_retrieve_body( $response );
141
			if ( empty($thumbnail) ) {
142
				return array(
143
					"type" => "error",
144
					"message" => "Unable to retrieve response body for thumbnail."
145
				);
146
			}
147
148
			$filetype = wp_check_filetype( $video["thumbnail"], null );
149
			$thumbnail_filename = $video["id"] . '.' . $filetype['ext'];
150
151
			$upload = wp_upload_bits( $thumbnail_filename, null, $thumbnail );
152
			if ($upload["error"] !== false){
153
				return array(
154
					"type" => "error",
155
					"message" => $upload["error"] === true ? "Unknown error uploading thumbnail image." : $upload["error"]
156
				);
157
			}
158
159
			$guid   = $upload["url"];
160
			$file   = $upload["file"];
161
162
			// Create attachment
163
			$attachment = array(
164
				'ID'             => 0,
165
				'guid'           => $guid,
166
				'post_title'     => $video["title"],
167
				'post_excerpt'   => $video["title"],
168
				'post_content'   => $video["description"],
169
				'post_date'      => '',
170
				'post_mime_type' => 'image/foogallery'
171
			);
172
173
			// Include image.php so we can call wp_generate_attachment_metadata()
174
			require_once( ABSPATH . 'wp-admin/includes/image.php' );
175
176
			// Insert the attachment
177
			$attachment_id   = wp_insert_attachment( $attachment, $file, 0 );
178
			if ($attachment_id == 0 || is_wp_error($attachment_id)){
179
				return array(
180
					"type" => "error",
181
					"message" => is_wp_error($attachment_id) ? $attachment_id->get_error_message() : "Failed to insert the attachment."
182
				);
183
			}
184
			$attachment_data = wp_generate_attachment_metadata( $attachment_id, $file );
185
			wp_update_attachment_metadata( $attachment_id, $attachment_data );
186
187
			$thumbnail_details  = wp_get_attachment_image_src( $attachment_id, 'thumbnail' ); // Yes we have the data, but get the thumbnail URL anyway, to be safe
188
			if ($thumbnail_details === false){
189
				return array(
190
					"type" => "error",
191
					"message" => "Unable to retrieve thumbnail details."
192
				);
193
			}
194
			$video["thumbnail"] = $thumbnail_details[0];
195
196
			return array(
197
				"type" => "success",
198
				"attachment_id" => $attachment_id
199
			);
200
		}
201
202
		private function get_thumbnail_url( $video ) {
203
			if ( ! empty( $video["provider"] ) ) {
204
				switch ( $video["provider"] ) {
205
					case "youtube":
206
						$format = "http://img.youtube.com/vi/%1s/%2s.jpg";
207
						/**
208
						 * Possible filenames for images, in order of desirability. Should only ever use first one.
209
						 * @see http://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
210
						 */
211
						$sizes = array(
212
							'maxresdefault',
213
							'hqdefault',
214
							'sddefault',
215
							'default',
216
							'0'
217
						);
218
						foreach ( $sizes as $size ) {
219
							$url = sprintf( $format, $video["id"], $size );
220
							if ( $this->url_exists( $url ) ) {
221
								return $url;
222
							}
223
						}
224
						break;
225
				}
226
			}
227
228
			return $video["thumbnail"];
229
		}
230
	}
231
}
232