youtube.php
9.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<?php
/*
Plugin Name: YouTube API
Description: Check links to YouTube videos and playlists using the YouTube API.
Version: 3
Author: Janis Elsts
ModuleID: youtube-checker
ModuleCategory: checker
ModuleContext: on-demand
ModuleLazyInit: true
ModuleClassName: blcYouTubeChecker
ModulePriority: 100
ModuleCheckerUrlPattern: @^https?://(?:([\w\d]+\.)*youtube\.[^/]+/watch\?.*v=[^/#]|youtu\.be/[^/#\?]+|(?:[\w\d]+\.)*?youtube\.[^/]+/(playlist|view_play_list)\?[^/#]{15,}?)@i
*/
class blcYouTubeChecker extends blcChecker {
var $api_grace_period = 0.3; //How long to wait between YouTube API requests.
var $last_api_request = 0; //Timestamp of the last request.
function can_check( $url, $parsed ) {
return true;
}
function check( $url ) {
//Throttle API requests to avoid getting blocked due to quota violation.
$delta = microtime_float() - $this->last_api_request;
if ( $delta < $this->api_grace_period ) {
usleep( ( $this->api_grace_period - $delta ) * 1000000 );
}
$result = array(
'final_url' => $url,
'redirect_count' => 0,
'timeout' => false,
'broken' => false,
'log' => "<em>(Using YouTube API)</em>\n\n",
'result_hash' => '',
);
$components = @parse_url( $url );
if ( isset( $components['query'] ) ) {
parse_str( $components['query'], $query );
} else {
$query = array();
}
//Extract the video or playlist ID from the URL
$video_id = null;
$playlist_id = null;
if ( strtolower( $components['host'] ) === 'youtu.be' ) {
$video_id = trim( $components['path'], '/' );
} elseif ( ( strpos( $components['path'], 'watch' ) !== false ) && isset( $query['v'] ) ) {
$video_id = $query['v'];
} elseif ( '/playlist' == $components['path'] ) {
$playlist_id = $query['list'];
} elseif ( '/view_play_list' == $components['path'] ) {
$playlist_id = $query['p'];
}
if ( empty( $playlist_id ) && empty( $video_id ) ) {
$result['status_text'] = 'Unsupported URL Syntax';
$result['status_code'] = BLC_LINK_STATUS_UNKNOWN;
return $result;
}
//Fetch video or playlist from the YouTube API
if ( ! empty( $video_id ) ) {
$api_url = $this->get_video_resource_url( $video_id );
} else {
$api_url = $this->get_playlist_resource_url( $playlist_id );
}
$conf = blc_get_configuration();
$args = array( 'timeout' => $conf->options['timeout'] );
$start = microtime_float();
$response = wp_remote_get( $api_url, $args );
$result['request_duration'] = microtime_float() - $start;
$this->last_api_request = $start;
//Got anything?
if ( is_wp_error( $response ) ) {
$result['log'] .= "Error.\n" . $response->get_error_message();
//WP doesn't make it easy to distinguish between different internal errors.
$result['broken'] = true;
$result['http_code'] = 0;
} else {
$result['http_code'] = intval( $response['response']['code'] );
if ( ! empty( $video_id ) ) {
$result = $this->check_video( $response, $result );
} else {
$result = $this->check_playlist( $response, $result );
}
}
//The hash should contain info about all pieces of data that pertain to determining if the
//link is working.
$result['result_hash'] = implode(
'|',
array(
'youtube',
$result['http_code'],
$result['broken'] ? 'broken' : '0',
$result['timeout'] ? 'timeout' : '0',
isset( $result['state_name'] ) ? $result['state_name'] : '-',
isset( $result['state_reason'] ) ? $result['state_reason'] : '-',
)
);
return $result;
}
/**
* Check API response for a single video.
*
* @param array $response WP HTTP API response.
* @param array $result Current result array.
* @return array New result array.
*/
protected function check_video( $response, $result ) {
$api = json_decode( $response['body'], true );
$videoFound = ( 200 == $result['http_code'] ) && isset( $api['items'], $api['items'][0] );
if ( isset( $api['error'] ) && ( 404 !== $result['http_code'] ) ) { //404's are handled later.
$result['status_code'] = BLC_LINK_STATUS_WARNING;
$result['warning'] = true;
if ( isset( $api['error']['errors'] ) ) {
$result['status_text'] = $api['error']['errors'][0]['reason'];
} else {
$result['status_text'] = __( 'Unknown Error', 'broken-link-checker' );
}
$result['log'] .= $this->format_api_error( $response, $api );
} elseif ( $videoFound ) {
$result['log'] .= __( 'Video OK', 'broken-link-checker' );
$result['status_text'] = _x( 'OK', 'link status', 'broken-link-checker' );
$result['status_code'] = BLC_LINK_STATUS_OK;
$result['http_code'] = 0;
//Add the video title to the log, purely for information.
if ( isset( $api['items'][0]['snippet']['title'] ) ) {
$title = $api['items'][0]['snippet']['title'];
$result['log'] .= "\n\nTitle : \"" . htmlentities( $title ) . '"';
}
} else {
$result['log'] .= __( 'Video Not Found', 'broken-link-checker' );
$result['broken'] = true;
$result['http_code'] = 0;
$result['status_text'] = __( 'Video Not Found', 'broken-link-checker' );
$result['status_code'] = BLC_LINK_STATUS_ERROR;
}
return $result;
}
/**
* Check a YouTube API response that contains a single playlist.
*
* @param array $response
* @param array $result
* @return array
*/
protected function check_playlist( $response, $result ) {
$api = json_decode( $response['body'], true );
if ( 404 === $result['http_code'] ) {
//Not found.
$result['log'] .= __( 'Playlist Not Found', 'broken-link-checker' );
$result['broken'] = true;
$result['http_code'] = 0;
$result['status_text'] = __( 'Playlist Not Found', 'broken-link-checker' );
$result['status_code'] = BLC_LINK_STATUS_ERROR;
} elseif ( 403 === $result['http_code'] ) {
//Forbidden. We're unlikely to see this code for playlists, but lets allow it.
$result['log'] .= htmlentities( $response['body'] );
$result['broken'] = true;
$result['status_text'] = __( 'Playlist Restricted', 'broken-link-checker' );
$result['status_code'] = BLC_LINK_STATUS_ERROR;
} elseif ( ( 200 === $result['http_code'] ) && isset( $api['items'] ) && is_array( $api['items'] ) ) {
//The playlist exists.
if ( empty( $api['items'] ) ) {
//An empty playlist. It is possible that all of the videos have been deleted.
$result['log'] .= __( 'This playlist has no entries or all entries have been deleted.', 'broken-link-checker' );
$result['status_text'] = _x( 'Empty Playlist', 'link status', 'broken-link-checker' );
$result['status_code'] = BLC_LINK_STATUS_WARNING;
$result['http_code'] = 0;
$result['broken'] = true;
} else {
//Treat the playlist as broken if at least one video is inaccessible.
foreach ( $api['items'] as $video ) {
$is_private = isset( $video['status']['privacyStatus'] ) && ( 'private' == $video['status']['privacyStatus'] );
if ( $is_private ) {
$result['log'] .= sprintf(
__( 'Video status : %1$s%2$s', 'broken-link-checker' ),
$video['status']['privacyStatus'],
''
);
$result['broken'] = true;
$result['status_text'] = __( 'Video Restricted', 'broken-link-checker' );
$result['status_code'] = BLC_LINK_STATUS_WARNING;
$result['http_code'] = 0;
break;
}
}
if ( ! $result['broken'] ) {
//All is well.
$result['log'] .= __( 'Playlist OK', 'broken-link-checker' );
$result['status_text'] = _x( 'OK', 'link status', 'broken-link-checker' );
$result['status_code'] = BLC_LINK_STATUS_OK;
$result['http_code'] = 0;
}
}
} else {
//Some other error.
$result['status_code'] = BLC_LINK_STATUS_WARNING;
$result['warning'] = true;
if ( isset( $api['error']['message'] ) ) {
$result['status_text'] = $api['error']['message'];
} else {
$result['status_text'] = __( 'Unknown Error', 'broken-link-checker' );
}
$result['log'] .= $this->format_api_error( $response, $api );
}
return $result;
}
protected function get_video_resource_url( $video_id ) {
$params = array(
'part' => 'status,snippet',
'id' => $video_id,
'key' => $this->get_youtube_api_key(),
);
$params = array_map( 'urlencode', $params );
return 'https://www.googleapis.com/youtube/v3/videos?' . build_query( $params );
}
protected function get_playlist_resource_url( $playlist_id ) {
$params = array(
'key' => $this->get_youtube_api_key(),
'id' => $playlist_id,
'part' => 'snippet,status',
'maxResults' => 10, //Playlists can be big. Lets just check the first few videos.
);
$query = build_query( array_map( 'urlencode', $params ) );
return 'https://youtube.googleapis.com/youtube/v3/playlists?' . $query;
}
protected function format_api_error( $response, $api ) {
$log = $response['response']['code'] . ' ' . $response['response']['message'];
$log .= "\n" . __( 'Unknown YouTube API response received.' );
//Log error details.
if ( isset( $api['error']['errors'] ) && is_array( $api['error']['errors'] ) ) {
foreach ( $api['error']['errors'] as $error ) {
$log .= "\n---\n";
if ( is_array( $error ) ) {
foreach ( $error as $key => $value ) {
$log .= sprintf(
"%s: %s\n",
htmlentities( $key ),
htmlentities( $value )
);
}
}
}
}
return $log;
}
public function get_youtube_api_key() {
$conf = blc_get_configuration();
$api_key = ! empty( $conf->options['youtube_api_key'] ) ? $conf->options['youtube_api_key'] : '';
return apply_filters( 'blc_youtube_api_key', $conf->options['youtube_api_key'] );
}
}