3 * Gallery - a web based photo album viewer and editor
4 * Copyright (C) 2000-2007 Bharat Mediratta
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or (at
9 * your option) any later version.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
22 * This plugin will handle the addition of embedded video objects
24 * @subpackage UserInterface
25 * @author Alan Pippin <apippin@pippins.net>
26 * @version $Revision: 1.1 $
28 class ItemAddEmbedVideo extends ItemAddPlugin {
31 * @see ItemAddPlugin::handleRequest
33 function handleRequest($form, &$item) {
36 $status = $error = array();
38 if (isset($form['action']['addEmbedVideoPage'])) {
40 $platform =& $gallery->getPlatform();
42 if (empty($extraHeaders)) {
43 $extraHeaders = array('Referer' => str_replace('&', '&', $url));
46 if(isset($form['webPage']['URL'])) {
48 /* Load any stored/set Parameters */
49 list ($ret, $params) =
50 GalleryCoreApi::fetchAllPluginParameters('module', 'embedvideo');
52 return array($ret, null, null);
54 foreach (array('default', 'override') as $type) {
55 $ItemAddUploadApplet[$type] = array();
56 if (!empty($params['embedvideo' . $type . 'Variables'])) {
57 $variablesArray = explode('|', $params['embedvideo' . $type . 'Variables']);
58 foreach ($variablesArray as $variable) {
59 list ($name, $value) = explode('=', $variable);
60 $ItemAddEmbedVideo[$type][$name] = $value;
61 /* print "type: $type name: $name value: $value <br>"; */
66 /* Store any Parameters into some simpler, shorter, local variables */
67 global $debugOutput, $useInternalFlvPlayer, $youtubeDevId;
68 global $width, $height, $externalFlvPlayer, $externalFlvPlayerVars;
71 $debugOutput = $this->getParameter($ItemAddEmbedVideo, 'debugOutput');
72 $useInternalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'useInternalFlvPlayer');
73 $youtubeDevId = $this->getParameter($ItemAddEmbedVideo, 'youtubeDevId');
74 $width = $this->getParameter($ItemAddEmbedVideo, 'width');
75 $height = $this->getParameter($ItemAddEmbedVideo, 'height');
76 $externalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayer');
77 $externalFlvPlayerVars = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayerVars');
78 $flvThumbnail = $this->getParameter($ItemAddEmbedVideo, 'flvThumbnail');
80 /* Store other string constants we'll use later */
81 $youtubeUrlPattern="youtube.com";
82 $youtubeApiUrl="http://www.youtube.com/api2_rest";
83 $googleUrlPattern="video.google.com";
84 $googlePlayer="http://video.google.com/googleplayer.swf";
86 /* Gallery2 specific paths and variables */
87 $urlGenerator =& $gallery->getUrlGenerator();
88 $gallery2_url = $urlGenerator->getCurrentUrlDir();
89 $gallery2_flv_thumbnail = "modules/thumbnail/images/G2video.jpg";
90 $gallery2_flv_player = "modules/flashvideo/lib/G2flv.swf";
92 /* Store the passed URL in a shorter local variable */
93 $url = $form['webPage']['URL'];
96 *****************************
97 * Embed a Youtube Video
98 *****************************
100 if(preg_match("/$youtubeUrlPattern/",$url)) {
102 /* Make sure we can find a video_id in the URL */
103 if(preg_match("/watch\?v=(.*)/",$url,$matches)) {
104 $video_id = $matches[1];
106 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
107 "Unable to extract video id from url: $url"),null,null);
110 /* Make sure we have a valid youtube developer id */
111 $dev_id = $youtubeDevId;
112 if(!preg_match("/\w+/",$dev_id)) {
113 return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
114 "Invalid/missing YouTube developer ID: $dev_id"),null,null);
117 /* Youtube api feed */
118 $feed = $youtubeApiUrl.'?method=youtube.videos.get_details';
119 $feed.= "&dev_id=$dev_id&video_id=$video_id";
121 /* Get the youtube xml feed as a string data source */
122 list ($successfullyCopied, $xml, $response, $headers) =
123 GalleryCoreApi::fetchWebPage($feed, $extraHeaders);
124 if (!$successfullyCopied) {
125 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
126 "Unable to get video information at url: $url - $response"),null,null);
130 if(!strcmp($debugOutput,"true")) {
134 /* Extract certain information from the xml feed */
135 preg_match_all("/\<title\>(.+?)\<\/title\>/smi",$xml, $title);
136 preg_match_all("/\<description\>(.+?)\<\/description\>/smi",$xml, $description);
137 preg_match_all("/\<thumbnail_url\>(.+?)\<\/thumbnail_url\>/smi",$xml, $thumbnail);
140 array_shift($thumbnail);
141 array_shift($description);
143 /* Replace html characters. More can be added but this seems to work */
144 for($i=0;$i<count($description[0]);$i++){
145 $description[0][$i] = preg_replace("/</","<",$description[0][$i]);
146 $description[0][$i] = html_entity_decode($description[0][$i],ENT_QUOTES);
149 /* Store the information found in some local variables */
150 $title = $title[0][0];
151 $summary = $description[0][0];
152 $thumbnail = $thumbnail[0][0];
154 /* Format the description to hold a reference to the embedded video */
155 $description = '<object width="'.$width.'" height="'.$height.'">';
156 $description.= '<param name="movie" ';
157 $description.= 'value="http://www.youtube.com/v/'.$video_id.'"></param>';
158 $description.= '<param name="wmode" value="transparent"></param>';
159 $description.= '<embed src="http://www.youtube.com/v/'.$video_id.'" ';
160 $description.= 'type="application/x-shockwave-flash" wmode="transparent" ';
161 $description.= 'width="'.$width.'" height="'.$height.'"></embed></object>';
162 $description.= "<br>$summary";
165 **********************************
166 * Embed a Google Video
167 **********************************
169 } else if(preg_match("/$googleUrlPattern/",$url)) {
171 /* Make sure we can extract a docID */
172 if(preg_match("/docid=(.*)/",$url,$matches)) {
173 $doc_id = $matches[1];
175 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
176 "Unable to extract doc id from url: $url"),null,null);
179 /* Grab the contents of the webpage used to display the video on video.google.com */
180 list ($successfullyCopied, $contents, $response, $headers) =
181 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
182 if (!$successfullyCopied) {
183 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
184 "Unable to get video information at url: $url - $response"),NULL,NULL);
187 /* Extract the summary from the webpage contents */
188 preg_match('/<meta content="(.+?)\. \w+ \d+, \d+.*" name="description">/i',
189 $contents, $matches);
190 $summary=$matches[1];
192 /* Extract the title from the webpage contents */
194 if(preg_match('/<title>(.+?)\s+- Google Video<\/title>/i', $contents, $matches)) {
196 } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
200 /* Extract the thumbnail URL from the webpage contents */
201 preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
202 $contents, $matches);
203 $thumbnail=$matches[1];
204 $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
206 /* Format the description to hold a reference to the embedded video */
207 $description = '<embed FlashVars="autoPlay=true" ';
208 $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
209 $description.= 'type="application/x-shockwave-flash" ';
210 $description.= 'src="'.$googlePlayer.'?docId='.$doc_id.'"> ';
211 $description.= '</embed>';
212 $description.= "<br>$summary";
215 **********************************
216 * Embed a remote .flv file
217 **********************************
219 } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
221 /* Set the title and summary to the name of the file */
222 $title = $matches[1];
223 $summary = $matches[1];
226 * Set the thumbnail to some generic jpg image,
227 * since we can't extract it from the remote flv file.
228 * If no parameter is set, set it to a default value.
230 if(preg_match("/\w+/", $flvThumbnail)) {
231 $thumbnail = $flvThumbnail;
233 $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
237 * Check to make sure the URL to the remote flv file is valid
238 * (That the file exists at the URL given)
240 list ($successfullyCopied, $response, $headers) =
241 $this->fetchWebFileHeaders($url, $extraHeaders);
242 if (!$successfullyCopied) {
243 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
244 "Unable to find the video at url: $url - $response"),NULL,NULL);
248 * Format the description to hold a reference to the embedded video
249 * This reference will be embedded using the G2 internal player,
250 * or an external player if provided by the user.
252 if(!strcmp($useInternalFlvPlayer,"false")) {
255 * The user has indicated they want to use an external flv player
256 * Make sure one is defined!
258 if(!preg_match("/\w+/",$externalFlvPlayer)) {
259 return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
260 "Invalid/missing external player parameter"),null,null);
263 /* Format the description to hold a reference to the embedded video */
264 $description ='<embed src="'.$externalFlvPlayer.'" ';
265 $description.= 'width="'.$width.'" height="'.$height.'" ';
266 $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
267 $description.= 'type="application/x-shockwave-flash" ';
268 $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
269 $description.= 'flashvars="file='.$url;
270 $description.= '&fullscreenpage='.$thumbnail;
271 $description.= '&linktarget=_Blank&image='.$thumbnail;
273 if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
274 /* Format the flashvars for the internal G2 flv player */
275 $description.= '&showdigits=true&autostart=false&showfsbutton=true&';
276 $description.= '&repeat=false&lightcolor=0x9999FF';
277 $description.= '&backcolor=0x888888&frontcolor=0x000000"';
279 /* Format the flashvars for the external G2 flv player */
280 $description.= '&'.$externalFlvPlayerVars;
282 $description.= ' /> </p>';
284 /* Internal FLV player */
286 /* Format the description to hold a reference to the embedded video */
287 $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
288 $description = '<script type="text/javascript">'."\n";
289 $description.= '// <![CDATA['."\n";
290 $description.= 'function divResize(id, nw, nh) {'."\n";
291 $description.= 'var obj = document.getElementById(id);'."\n";
292 $description.= 'obj.style.width = nw + "px";'."\n";
293 $description.= 'obj.style.height = nh + "px";'."\n";
294 $description.= '}'."\n";
295 $description.= '// ]]>'."\n";
296 $description.= '</script>'."\n";
297 $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
298 $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
299 $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
300 $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
301 $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
302 $description.= '<param name="FlashVars" value="flvUrl='.$url;
303 $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
304 $description.= '&allowDl=true&thumbUrl='.$thumbnail;
305 $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
306 $description.= '<param name="quality" value="high"/>';
307 $description.= '<param name="scale" value="noscale"/>';
308 $description.= '<param name="salign" value="lt"/>';
309 $description.= '<param name="wmode" value="transparent"/>';
310 $description.= '<param name="allowScriptAccess" value="always"/>';
311 $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
312 $description.= 'flashvars="flvUrl='.$url;
313 $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
314 $description.= '&allowDl=true&thumbUrl='.$thumbnail;
315 $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
316 $description.= 'type="application/x-shockwave-flash" ';
317 $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
318 $description.= 'wmode="transparent" allowScriptAccess="always" ';
319 $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
320 $description.= '</object></div>';
324 **********************************
325 * Unsupported URL to embed
326 **********************************
329 return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
330 "Unable to embed video from: $url"),null,null);
335 **********************************
336 * Add the video to Gallery
337 **********************************
340 /* Get a local tmp file to save the thumbnail URL to */
341 $tmpDir = $gallery->getConfig('data.gallery.tmp');
342 $tmpFile = $platform->tempnam($tmpDir, 'add');
345 if(!strcmp($debugOutput,"true")) {
346 print "thumbnail: $thumbnail <br>";
349 /* Fetch the thumbnail and save it to a local file */
350 list ($successfullyCopied, $response, $headers) =
351 GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
352 if (!$successfullyCopied) {
353 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
354 "Unable to copy thumbnail from url: $url - $response"),null,null);
357 /* Obtain the mimeType of the thumbnail */
358 list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
360 /* Set the filename for the item we want to add */
362 $fileName = preg_replace("/\s+/","_",$fileName);
363 $fileName = preg_replace("/'/","",$fileName);
364 $fileName = preg_replace("/\"/","",$fileName);
365 $fileName = preg_replace("/&#\d+;/","",$fileName);
367 /* General debug output */
368 if(!strcmp($debugOutput,"true")) {
369 print "<p><a href=\"".$title."\" target=\"_blank\">";
370 print "<img src=\"".$thumbnail."\">\n</a>".$summary."</p>";
371 print "<p>$description</p>";
372 print "thumbnail: $tmpFile <br>";
373 print "mimeType: $mimeType <br>";
374 print "fileName: $fileName <br>";
375 print "<br><br><b>Video Successfully Added to your Gallery Album</b><br><br>";
378 /* Make the gallery2 call to add this item to the album */
379 list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($tmpFile,
388 return array($ret, null, null);
391 $status['addedFiles'][] = array('fileName' => $url,
392 'id' => $newItem->getId(),
393 'warnings' => array());
395 @$platform->unlink($tmpFile);
398 return array(null, $error, $status);
402 * A simple function to resolve the value of a parameter from
403 * the default or override value if it exists.
405 function getParameter($params, $name) {
406 if(isset($params['override'][$name])) {
407 return($params['override'][$name]);
409 return($params['default'][$name]);
414 * A simple function to get the headers only (no body) for a given URL
417 function fetchWebFileHeaders($url, $requestHeaders=array()) {
420 $requestMethod='GET';
422 /* Convert illegal characters */
423 $url = str_replace(' ', '%20', $url);
425 /* Unescape ampersands, since if the URL comes from form input it will be escaped */
426 $url = str_replace('&', '&', $url);
428 $platform =& $gallery->getPlatform();
430 $urlComponents = parse_url($url);
431 if (empty($urlComponents['port'])) {
432 $urlComponents['port'] = 80;
434 if (empty($urlComponents['path'])) {
435 $urlComponents['path'] = '/';
438 $handle = @$platform->fsockopen(
439 $urlComponents['host'], $urlComponents['port'], $errno, $errstr, 5);
440 if (empty($handle)) {
441 $gallery->debug("Error $errno: '$errstr' requesting $url");
442 return array(null, null, null);
445 $requestUri = $urlComponents['path'];
446 if (!empty($urlComponents['query'])) {
447 $requestUri .= '?' . $urlComponents['query'];
449 $headerLines = array('Host: ' . $urlComponents['host']);
450 foreach ($requestHeaders as $key => $value) {
451 $headerLines[] = $key . ': ' . $value;
454 $success = $platform->fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s",
457 implode("\r\n", $headerLines),
460 /* Zero bytes written or false was returned */
462 "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''));
463 return array(null, null, null);
465 $platform->fflush($handle);
469 * Read the status line. fgets stops after newlines. The first line is the protocol
470 * version followed by a numeric status code and its associated textual phrase.
472 $responseStatus = trim($platform->fgets($handle, 4096));
473 if (empty($responseStatus)) {
474 $gallery->debug('Empty http response code, maybe timeout');
475 return array(null, null, null);
478 /* Read the headers */
479 $responseHeaders = array();
480 while (!$platform->feof($handle)) {
481 $line = trim($platform->fgets($handle, 4096));
486 /* Normalize the line endings */
487 $line = str_replace("\r", '', $line);
489 list ($key, $value) = explode(':', $line, 2);
490 if (isset($responseHeaders[$key])) {
491 if (!is_array($responseHeaders[$key])) {
492 $responseHeaders[$key] = array($responseHeaders[$key]);
494 $responseHeaders[$key][] = trim($value);
496 $responseHeaders[$key] = trim($value);
499 $platform->fclose($handle);
501 if(preg_match("/Not found/i", $responseStatus)) {
505 //print "success: $success <br>responseStatus: $responseStatus <br>responseHeaders: $responseHeaders <br>";
507 return array($success, $responseStatus, $responseHeaders);
511 * @see ItemAdd:loadTemplate
513 function loadTemplate(&$template, &$form, $item) {
516 if ($form['formName'] != 'ItemAddEmbedVideo') {
517 /* First time around, load the form with item data */
518 $form['webPage'] = '';
519 $form['formName'] = 'ItemAddEmbedVideo';
522 $session =& $gallery->getSession();
524 $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
527 'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
528 'modules_embedvideo');
532 * @see ItemAddPlugin::getTitle
534 function getTitle() {
535 list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
537 return array($ret, null);
540 return array(null, $module->translate('Embed Video'));