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 */
83 $youtubeUrlPattern="youtube.com";
84 $youtubeApiUrl="http://www.youtube.com/api2_rest";
87 $googleUrlPattern="video.google.com";
88 $googlePlayer="http://video.google.com/googleplayer.swf";
91 $yahooUrlPattern="video.yahoo.com";
92 $yahooThumbnailUrl="http://thmg01.video.search.yahoo.com/image/";
95 $metacafeUrlPattern="metacafe.com";
96 $metacafeThumbnailUrl="http://www.metacafe.com/thumb/";
98 /* Gallery2 specific paths and variables */
99 $urlGenerator =& $gallery->getUrlGenerator();
100 $gallery2_url = $urlGenerator->getCurrentUrlDir();
101 $gallery2_flv_thumbnail = "modules/thumbnail/images/G2video.jpg";
102 $gallery2_flv_player = "modules/flashvideo/lib/G2flv.swf";
104 /* Store the passed URL in a shorter local variable */
105 $url = $form['webPage']['URL'];
108 *****************************
109 * Embed a Youtube Video
110 *****************************
112 if(preg_match("/$youtubeUrlPattern/",$url)) {
114 /* Make sure we can find a video_id in the URL */
115 if(preg_match("/watch\?v=(.*)/",$url,$matches)) {
116 $video_id = $matches[1];
118 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
119 "Unable to extract video id from url: $url"),null,null);
122 /* Make sure we have a valid youtube developer id */
123 $dev_id = $youtubeDevId;
124 if(!preg_match("/\w+/",$dev_id)) {
125 return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
126 "Invalid/missing YouTube developer ID: $dev_id"),null,null);
129 /* Youtube api feed */
130 $feed = $youtubeApiUrl.'?method=youtube.videos.get_details';
131 $feed.= "&dev_id=$dev_id&video_id=$video_id";
133 /* Get the youtube xml feed as a string data source */
134 list ($successfullyCopied, $xml, $response, $headers) =
135 GalleryCoreApi::fetchWebPage($feed, $extraHeaders);
136 if (!$successfullyCopied) {
137 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
138 "Unable to get video information at url: $url - $response"),null,null);
142 if(!strcmp($debugOutput,"true")) {
146 /* Extract certain information from the xml feed */
147 preg_match_all("/\<title\>(.+?)\<\/title\>/smi",$xml, $title);
148 preg_match_all("/\<description\>(.+?)\<\/description\>/smi",$xml, $description);
149 preg_match_all("/\<thumbnail_url\>(.+?)\<\/thumbnail_url\>/smi",$xml, $thumbnail);
152 array_shift($thumbnail);
153 array_shift($description);
155 /* Replace html characters. More can be added but this seems to work */
156 for($i=0;$i<count($description[0]);$i++){
157 $description[0][$i] = preg_replace("/</","<",$description[0][$i]);
158 $description[0][$i] = html_entity_decode($description[0][$i],ENT_QUOTES);
161 /* Store the information found in some local variables */
162 $title = $title[0][0];
163 $summary = $description[0][0];
164 $thumbnail = $thumbnail[0][0];
166 /* Format the description to hold a reference to the embedded video */
167 $description = '<object width="'.$width.'" height="'.$height.'">';
168 $description.= '<param name="movie" ';
169 $description.= 'value="http://www.youtube.com/v/'.$video_id.'"></param>';
170 $description.= '<param name="wmode" value="transparent"></param>';
171 $description.= '<embed src="http://www.youtube.com/v/'.$video_id.'" ';
172 $description.= 'type="application/x-shockwave-flash" wmode="transparent" ';
173 $description.= 'width="'.$width.'" height="'.$height.'"></embed></object>';
174 $description.= "<br>$summary";
177 **********************************
178 * Embed a Google Video
179 **********************************
181 } else if(preg_match("/$googleUrlPattern/",$url)) {
183 /* Make sure we can extract a docID */
184 if(preg_match("/docid=(.*)/",$url,$matches)) {
185 $doc_id = $matches[1];
187 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
188 "Unable to extract doc id from url: $url"),null,null);
191 /* Grab the contents of the webpage used to display the video on video.google.com */
192 list ($successfullyCopied, $contents, $response, $headers) =
193 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
194 if (!$successfullyCopied) {
195 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
196 "Unable to get video information at url: $url - $response"),NULL,NULL);
199 /* Extract the summary from the webpage contents */
200 preg_match('/<meta content="(.+?)\. \w+ \d+, \d+.*" name="description">/i',
201 $contents, $matches);
202 $summary=$matches[1];
204 /* Extract the title from the webpage contents */
206 if(preg_match('/<title>(.+?)\s+- Google Video<\/title>/i', $contents, $matches)) {
208 } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
212 /* Extract the thumbnail URL from the webpage contents */
213 preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
214 $contents, $matches);
215 $thumbnail=$matches[1];
216 $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
218 /* Format the description to hold a reference to the embedded video */
219 $description = '<embed FlashVars="autoPlay=true" ';
220 $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
221 $description.= 'type="application/x-shockwave-flash" ';
222 $description.= 'src="'.$googlePlayer.'?docId='.$doc_id.'"> ';
223 $description.= '</embed>';
224 $description.= "<br>$summary";
227 **********************************
228 * Embed a Yahoo Video
229 **********************************
231 } else if(preg_match("/$yahooUrlPattern/",$url)) {
233 /* Make sure we can extract a vidID */
234 if(preg_match("/vid=(.*)/",$url,$matches)) {
235 $vid_id = $matches[1];
237 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
238 "Unable to extract vid id from url: $url"),null,null);
241 /* Grab the contents of the webpage used to display the video on video.google.com */
242 list ($successfullyCopied, $contents, $response, $headers) =
243 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
244 if (!$successfullyCopied) {
245 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
246 "Unable to get video information at url: $url - $response"),NULL,NULL);
249 /* Extract the summary from the webpage contents */
250 preg_match('/Description:<\/em><p>(.+?)<\/p>/', $contents, $matches);
251 $summary=$matches[1];
253 /* Extract the title from the webpage contents */
255 if(preg_match('/<title>(.+?)\s+- Yahoo! Video<\/title>/i', $contents, $matches)) {
257 } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
261 /* Build the thumbnail URL from the vid_id */
262 $thumbnail=$yahooThumbnailUrl.$vid_id."_01";
264 /* Format the description to hold a reference to the embedded video */
265 preg_match('/(<embed src.+?<\/embed>)/', $contents, $matches);
266 $description=$matches[1];
267 $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
268 $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
269 $description.= "<br>$summary";
272 **********************************
273 * Embed a MetaCafe Video
274 **********************************
276 } else if(preg_match("/$metacafeUrlPattern/",$url)) {
278 /* Make sure we can extract a itemID */
279 if(preg_match("/\/watch\/(.+?)\/(.+?)/",$url,$matches)) {
280 $item_id = $matches[1];
282 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
283 "Unable to extract item id from url: $url"),null,null);
286 /* Grab the contents of the webpage used to display the video on video.google.com */
287 list ($successfullyCopied, $contents, $response, $headers) =
288 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
289 if (!$successfullyCopied) {
290 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
291 "Unable to get video information at url: $url - $response"),NULL,NULL);
294 /* Extract the summary from the webpage contents */
295 preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
296 $summary=$matches[1];
298 /* Extract the title from the webpage contents */
299 preg_match('/<title>(.+?)<\/title>/i', $contents, $matches);
302 /* Build the thumbnail URL from the item_id */
303 $thumbnail=$metacafeThumbnailUrl.$item_id.".jpg";
305 /* Format the description to hold a reference to the embedded video */
306 preg_match('/(embed src.+?\/embed)/', $contents, $matches);
307 $description="<".$matches[1];
308 $description=preg_replace("/"/","'",$description);
309 $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
310 $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
311 $description.= "</embed>";
312 $description.= "<br>$summary";
315 **********************************
316 * Embed a remote .flv file
317 **********************************
319 } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
321 /* Set the title and summary to the name of the file */
322 $title = $matches[1];
323 $summary = $matches[1];
326 * Set the thumbnail to some generic jpg image,
327 * since we can't extract it from the remote flv file.
328 * If no parameter is set, set it to a default value.
330 if(preg_match("/\w+/", $flvThumbnail)) {
331 $thumbnail = $flvThumbnail;
333 $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
337 * Check to make sure the URL to the remote flv file is valid
338 * (That the file exists at the URL given)
340 list ($successfullyCopied, $response, $headers) =
341 $this->fetchWebFileHeaders($url, $extraHeaders);
342 if (!$successfullyCopied) {
343 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
344 "Unable to find the video at url: $url - $response"),NULL,NULL);
348 * Format the description to hold a reference to the embedded video
349 * This reference will be embedded using the G2 internal player,
350 * or an external player if provided by the user.
352 if(!strcmp($useInternalFlvPlayer,"false")) {
355 * The user has indicated they want to use an external flv player
356 * Make sure one is defined!
358 if(!preg_match("/\w+/",$externalFlvPlayer)) {
359 return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
360 "Invalid/missing external player parameter"),null,null);
363 /* Format the description to hold a reference to the embedded video */
364 $description ='<embed src="'.$externalFlvPlayer.'" ';
365 $description.= 'width="'.$width.'" height="'.$height.'" ';
366 $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
367 $description.= 'type="application/x-shockwave-flash" ';
368 $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
369 $description.= 'flashvars="file='.$url;
370 $description.= '&fullscreenpage='.$thumbnail;
371 $description.= '&linktarget=_Blank&image='.$thumbnail;
373 if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
374 /* Format the flashvars for the internal G2 flv player */
375 $description.= '&showdigits=true&autostart=false&showfsbutton=true&';
376 $description.= '&repeat=false&lightcolor=0x9999FF';
377 $description.= '&backcolor=0x888888&frontcolor=0x000000"';
379 /* Format the flashvars for the external G2 flv player */
380 $description.= '&'.$externalFlvPlayerVars;
382 $description.= ' /> </p>';
384 /* Internal FLV player */
386 /* Format the description to hold a reference to the embedded video */
387 $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
388 $description = '<script type="text/javascript">'."\n";
389 $description.= '// <![CDATA['."\n";
390 $description.= 'function divResize(id, nw, nh) {'."\n";
391 $description.= 'var obj = document.getElementById(id);'."\n";
392 $description.= 'obj.style.width = nw + "px";'."\n";
393 $description.= 'obj.style.height = nh + "px";'."\n";
394 $description.= '}'."\n";
395 $description.= '// ]]>'."\n";
396 $description.= '</script>'."\n";
397 $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
398 $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
399 $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
400 $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
401 $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
402 $description.= '<param name="FlashVars" value="flvUrl='.$url;
403 $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
404 $description.= '&allowDl=true&thumbUrl='.$thumbnail;
405 $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
406 $description.= '<param name="quality" value="high"/>';
407 $description.= '<param name="scale" value="noscale"/>';
408 $description.= '<param name="salign" value="lt"/>';
409 $description.= '<param name="wmode" value="transparent"/>';
410 $description.= '<param name="allowScriptAccess" value="always"/>';
411 $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
412 $description.= 'flashvars="flvUrl='.$url;
413 $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
414 $description.= '&allowDl=true&thumbUrl='.$thumbnail;
415 $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
416 $description.= 'type="application/x-shockwave-flash" ';
417 $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
418 $description.= 'wmode="transparent" allowScriptAccess="always" ';
419 $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
420 $description.= '</object></div>';
424 **********************************
425 * Unsupported URL to embed
426 **********************************
429 return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
430 "Unable to embed video from: $url"),null,null);
435 **********************************
436 * Add the video to Gallery
437 **********************************
440 /* Get a local tmp file to save the thumbnail URL to */
441 $tmpDir = $gallery->getConfig('data.gallery.tmp');
442 $tmpFile = $platform->tempnam($tmpDir, 'add');
445 if(!strcmp($debugOutput,"true")) {
446 print "thumbnail: $thumbnail <br>";
449 /* Fetch the thumbnail and save it to a local file */
450 list ($successfullyCopied, $response, $headers) =
451 GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
452 if (!$successfullyCopied) {
453 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
454 "Unable to copy thumbnail from url: $url - $response"),null,null);
457 /* Obtain the mimeType of the thumbnail */
458 list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
460 /* Set the filename for the item we want to add */
462 $fileName = preg_replace("/\s+/","_",$fileName);
463 $fileName = preg_replace("/'/","",$fileName);
464 $fileName = preg_replace("/\"/","",$fileName);
465 $fileName = preg_replace("/&#\d+;/","",$fileName);
467 /* General debug output */
468 if(!strcmp($debugOutput,"true")) {
469 print "title: $title <br>";
470 print "<p><a href=\"".$title."\" target=\"_blank\">";
471 print "<img src=\"".$thumbnail."\">\n</a>".$summary."</p>";
472 print "<p>$description</p>";
473 print "thumbnail: $tmpFile <br>";
474 print "mimeType: $mimeType <br>";
475 print "fileName: $fileName <br>";
476 print "<br><br><b>Video Successfully Added to your Gallery Album</b><br><br>";
479 /* Make the gallery2 call to add this item to the album */
480 list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($tmpFile,
489 return array($ret, null, null);
492 $status['addedFiles'][] = array('fileName' => $url,
493 'id' => $newItem->getId(),
494 'warnings' => array());
496 @$platform->unlink($tmpFile);
499 return array(null, $error, $status);
503 * A simple function to resolve the value of a parameter from
504 * the default or override value if it exists.
506 function getParameter($params, $name) {
507 if(isset($params['override'][$name])) {
508 return($params['override'][$name]);
510 return($params['default'][$name]);
515 * A simple function to get the headers only (no body) for a given URL
518 function fetchWebFileHeaders($url, $requestHeaders=array()) {
521 $requestMethod='GET';
523 /* Convert illegal characters */
524 $url = str_replace(' ', '%20', $url);
526 /* Unescape ampersands, since if the URL comes from form input it will be escaped */
527 $url = str_replace('&', '&', $url);
529 $platform =& $gallery->getPlatform();
531 $urlComponents = parse_url($url);
532 if (empty($urlComponents['port'])) {
533 $urlComponents['port'] = 80;
535 if (empty($urlComponents['path'])) {
536 $urlComponents['path'] = '/';
539 $handle = @$platform->fsockopen(
540 $urlComponents['host'], $urlComponents['port'], $errno, $errstr, 5);
541 if (empty($handle)) {
542 $gallery->debug("Error $errno: '$errstr' requesting $url");
543 return array(null, null, null);
546 $requestUri = $urlComponents['path'];
547 if (!empty($urlComponents['query'])) {
548 $requestUri .= '?' . $urlComponents['query'];
550 $headerLines = array('Host: ' . $urlComponents['host']);
551 foreach ($requestHeaders as $key => $value) {
552 $headerLines[] = $key . ': ' . $value;
555 $success = $platform->fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s",
558 implode("\r\n", $headerLines),
561 /* Zero bytes written or false was returned */
563 "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''));
564 return array(null, null, null);
566 $platform->fflush($handle);
570 * Read the status line. fgets stops after newlines. The first line is the protocol
571 * version followed by a numeric status code and its associated textual phrase.
573 $responseStatus = trim($platform->fgets($handle, 4096));
574 if (empty($responseStatus)) {
575 $gallery->debug('Empty http response code, maybe timeout');
576 return array(null, null, null);
579 /* Read the headers */
580 $responseHeaders = array();
581 while (!$platform->feof($handle)) {
582 $line = trim($platform->fgets($handle, 4096));
587 /* Normalize the line endings */
588 $line = str_replace("\r", '', $line);
590 list ($key, $value) = explode(':', $line, 2);
591 if (isset($responseHeaders[$key])) {
592 if (!is_array($responseHeaders[$key])) {
593 $responseHeaders[$key] = array($responseHeaders[$key]);
595 $responseHeaders[$key][] = trim($value);
597 $responseHeaders[$key] = trim($value);
600 $platform->fclose($handle);
602 if(preg_match("/Not found/i", $responseStatus)) {
606 //print "success: $success <br>responseStatus: $responseStatus <br>responseHeaders: $responseHeaders <br>";
608 return array($success, $responseStatus, $responseHeaders);
612 * @see ItemAdd:loadTemplate
614 function loadTemplate(&$template, &$form, $item) {
617 if ($form['formName'] != 'ItemAddEmbedVideo') {
618 /* First time around, load the form with item data */
619 $form['webPage'] = '';
620 $form['formName'] = 'ItemAddEmbedVideo';
623 $session =& $gallery->getSession();
625 $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
628 'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
629 'modules_embedvideo');
633 * @see ItemAddPlugin::getTitle
635 function getTitle() {
636 list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
638 return array($ret, null);
641 return array(null, $module->translate('Embed Video'));