MediaInternetYouTubeHandler.inc in Media: YouTube 7
File
includes/MediaInternetYouTubeHandler.inc
View source
<?php
class MediaInternetYouTubeHandler extends MediaInternetBaseHandler {
public function parse($embedCode) {
$patterns = array(
'@youtube\\.com/watch[#\\?].*?v=([^"\\& ]+)@i',
'@youtube\\.com/embed/([^"\\&\\? ]+)@i',
'@youtube\\.com/v/([^"\\&\\? ]+)@i',
'@youtube\\.com/\\?v=([^"\\& ]+)@i',
'@youtu.be/([^"\\&\\? ]+)@i',
);
foreach ($patterns as $pattern) {
preg_match($pattern, $embedCode, $matches);
if (isset($matches[1]) && $this
->valid_id($matches[1])) {
return file_stream_wrapper_uri_normalize('youtube://v/' . $matches[1]);
}
}
}
public function valid_id($id) {
$url = 'http://gdata.youtube.com/feeds/api/videos/' . $id;
$response = drupal_http_request($url, array(
'method' => 'HEAD',
));
if ($response->code == 401) {
throw new MediaInternetValidationException("Embedding has been disabled for this video.");
}
elseif ($response->code != 200) {
throw new MediaInternetValidationException("The YouTube video ID is invalid or the video was deleted.");
}
return TRUE;
}
public function claim($embedCode) {
if ($this
->parse($embedCode)) {
return TRUE;
}
}
public function getFileObject() {
$uri = $this
->parse($this->embedCode);
$file = file_uri_to_object($uri, TRUE);
if (empty($file->fid) && ($info = $this
->getOEmbed())) {
$file->filename = truncate_utf8($info['title'], 255);
}
return $file;
}
public function getMRSS() {
$uri = $this
->parse($this->embedCode);
$video_id = arg(1, file_uri_target($uri));
$rss_url = url('http://gdata.youtube.com/feeds/api/videos/' . $video_id, array(
'query' => array(
'v' => '2',
),
));
$entry = simplexml_load_file($rss_url);
return $entry;
}
public function getOEmbed() {
$uri = $this
->parse($this->embedCode);
$external_url = drupal_realpath($uri);
$oembed_url = url('http://www.youtube.com/oembed', array(
'query' => array(
'url' => $external_url,
'format' => 'json',
),
));
$response = drupal_http_request($oembed_url);
if (!isset($response->error)) {
return drupal_json_decode($response->data);
}
}
}