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 — feature/video-support ( 96814b )
by Brad
05:36
created

FooGallery_Pro_Video_Import::handle_import()   C

Complexity

Conditions 9
Paths 11

Size

Total Lines 59
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 37
nc 11
nop 1
dl 0
loc 59
rs 6.9133
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() {
0 ignored issues
show
Coding Style introduced by
get_args uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
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() {
0 ignored issues
show
Coding Style introduced by
get_videos_arg uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
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
			);
61
62
			$video_types = array(
63
				'youtube',
64
				'vimeo',
65
				'wistia-inc',
66
				'dailymotion'
67
			);
68
69
			foreach ( $videos as $video ) {
70
				//set the default type to "video"
71
				$video["type"] = 'embed';
72
73
				if ( in_array( $video['provider'], $video_types ) ) {
74
					$video["type"] = 'video';
75
				}
76
77
				if ( isset( $video["urls"] ) ) {
78
					// handle self-hosted import
79
					$video["type"] = 'video';
80
					$url = "";
81
					foreach ( $video["urls"] as $type => $value ) {
82
						if ( ! empty( $value ) ) {
83
							if ( ! empty( $url ) ) {
84
								$url .= ",";
85
							}
86
							$url .= $value;
87
						}
88
					}
89
					if ( ! empty( $url ) ) {
90
						$video["url"] = $url;
91
					} else {
92
						$response["failed"][] = $video;
93
						continue;
94
					}
95
				}
96
				$attachment_id = $this->create_attachment( $video );
97
				if ( $attachment_id === false ) {
98
					$response["failed"][] = $video;
99
				} else {
100
					$response["imported"][] = $attachment_id;
101
					// Save alt text in the post meta
102
					update_post_meta( $attachment_id, "_wp_attachment_image_alt", $video["title"] );
103
					// Save the URL that we will be opening
104
					update_post_meta( $attachment_id, "_foogallery_custom_url", $video["url"] );
105
					// Make sure we open in new tab by default
106
					update_post_meta( $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...
107
					//save video object
108
					update_post_meta( $attachment_id, FOOGALLERY_VIDEO_POST_META, $video );
109
				}
110
			}
111
112
			return $response;
113
		}
114
115
		private function create_attachment( &$video ) {
116
			//allow for really big imports that take a really long time!
117
			@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...
118
119
			$video["thumbnail"] = $this->get_thumbnail_url( $video );
120
			$response           = wp_remote_get( $video["thumbnail"] );
121
			if ( is_wp_error( $response ) ) {
122
				return false;
123
			}
124
125
			$thumbnail          = wp_remote_retrieve_body( $response );
126
			$thumbnail_filename = $this->get_thumbnail_filename( $video );
127
128
			$upload = wp_upload_bits( $thumbnail_filename, null, $thumbnail );
129
			$guid   = $upload["url"];
130
			$file   = $upload["file"];
131
132
			// Create attachment
133
			$attachment = array(
134
				'ID'             => 0,
135
				'guid'           => $guid,
136
				'post_title'     => $video["title"],
137
				'post_excerpt'   => $video["title"],
138
				'post_content'   => $video["description"],
139
				'post_date'      => '',
140
				'post_mime_type' => 'image/foogallery'
141
			);
142
143
			// Include image.php so we can call wp_generate_attachment_metadata()
144
			require_once( ABSPATH . 'wp-admin/includes/image.php' );
145
146
			// Insert the attachment
147
			$attachment_id   = wp_insert_attachment( $attachment, $file, 0 );
148
			$attachment_data = wp_generate_attachment_metadata( $attachment_id, $file );
149
			wp_update_attachment_metadata( $attachment_id, $attachment_data );
150
151
			$thumbnail_details  = wp_get_attachment_image_src( $attachment_id, 'thumbnail' ); // Yes we have the data, but get the thumbnail URL anyway, to be safe
152
			$video["thumbnail"] = $thumbnail_details[0];
153
154
			return $attachment_id;
155
		}
156
157
		private function get_thumbnail_url( $video ) {
158
			if ( ! empty( $video["provider"] ) ) {
159
				switch ( $video["provider"] ) {
160
					case "youtube":
161
						$format = "http://img.youtube.com/vi/%1s/%2s.jpg";
162
						/**
163
						 * Possible filenames for images, in order of desirability. Should only ever use first one.
164
						 * @see http://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
165
						 */
166
						$sizes = array(
167
							'maxresdefault',
168
							'hqdefault',
169
							'sddefault',
170
							'default',
171
							'0'
172
						);
173
						foreach ( $sizes as $size ) {
174
							$url = sprintf( $format, $video["id"], $size );
175
							if ( $this->url_exists( $url ) ) {
176
								return $url;
177
							}
178
						}
179
						break;
180
				}
181
			}
182
183
			return $video["thumbnail"];
184
		}
185
186
		private function get_thumbnail_filename( $video ) {
187
			return $video["id"] . '.' . pathinfo( basename( $video["thumbnail"] ), PATHINFO_EXTENSION );
188
		}
189
190
	}
191
192
}