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.
21 GalleryCoreApi::requireOnce('modules/gd/classes/GdToolkitHelper.class');
25 * This plugin will handle the addition of embedded video objects
27 * @subpackage UserInterface
28 * @author Alan Pippin <apippin@pippins.net>
29 * @version $Revision: 1.1 $
31 class ItemAddEmbedVideo extends ItemAddPlugin {
34 * @see ItemAddPlugin::handleRequest
36 function handleRequest($form, &$item) {
39 $status = $error = array();
41 if (isset($form['action']['addEmbedVideoPage'])) {
43 $platform =& $gallery->getPlatform();
45 if (empty($extraHeaders)) {
46 $extraHeaders = array('Referer' => str_replace('&', '&', $url));
49 if(isset($form['webPage']['URL'])) {
51 /* Load any stored/set Parameters */
52 list ($ret, $params) =
53 GalleryCoreApi::fetchAllPluginParameters('module', 'embedvideo');
55 return array($ret, null, null);
57 foreach (array('default', 'override') as $type) {
58 $ItemAddUploadApplet[$type] = array();
59 if (!empty($params['embedvideo' . $type . 'Variables'])) {
60 $variablesArray = explode('|', $params['embedvideo' . $type . 'Variables']);
61 foreach ($variablesArray as $variable) {
62 list ($name, $value) = explode('=', $variable);
63 $ItemAddEmbedVideo[$type][$name] = $value;
64 /* print "type: $type name: $name value: $value <br>"; */
69 /* Store any Parameters into some simpler, shorter, local variables */
70 global $debugOutput, $useInternalFlvPlayer, $youtubeDevId;
71 global $width, $height, $externalFlvPlayer, $externalFlvPlayerVars;
72 global $flvThumbnail, $useRemoteSize, $autoStart;
73 global $watermarkVideos, $watermarkImage;
75 /* Find out what value our parameters should have by looking to see if they
76 * are defined in our overrides section or default section. If they are not
77 * defined in either of these 2 places, pass in a default value to set them to
79 $debugOutput = $this->getParameter($ItemAddEmbedVideo, 'debugOutput', "false");
80 $useInternalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'useInternalFlvPlayer', "true");
81 $youtubeDevId = $this->getParameter($ItemAddEmbedVideo, 'youtubeDevId', "");
82 $youtubeShowRelated = $this->getParameter($ItemAddEmbedVideo, 'youtubeShowRelated', "false");
83 $width = $this->getParameter($ItemAddEmbedVideo, 'width', "320");
84 $height = $this->getParameter($ItemAddEmbedVideo, 'height', "240");
85 $externalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayer', "");
86 $externalFlvPlayerVars = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayerVars', "");
87 $flvThumbnail = $this->getParameter($ItemAddEmbedVideo, 'flvThumbnail', "");
88 $useRemoteSize = $this->getParameter($ItemAddEmbedVideo, 'useRemoteSize', "false");
89 $autoStart = $this->getParameter($ItemAddEmbedVideo, 'autoStart', "false");
90 $watermarkImage = $this->getParameter($ItemAddEmbedVideo, 'watermarkImage', "");
91 $watermarkVideos = $this->getParameter($ItemAddEmbedVideo, 'watermarkVideos', "false");
93 /* Print our stored/set Parameters */
94 if(!strcmp($debugOutput,"true")) {
96 print "<h2>Variable Parameters</h2>";
97 print "debugOutput=$debugOutput<br>";
98 print "useInternalFlvPlayer=$useInternalFlvPlayer<br>";
99 print "youtubeDevId=$youtubeDevId<br>";
100 print "youtubeShowRelated=$youtubeShowRelated<br>";
101 print "width=$width<br>";
102 print "height=$height<br>";
103 print "externalFlvPlayer=$externalFlvPlayer<br>";
104 print "externalFlvPlayerVars=$externalFlvPlayerVars<br>";
105 print "flvThumbnail=$flvThumbnail<br>";
106 print "useRemoteSize=$useRemoteSize<br>";
107 print "autoStart=$autoStart<br>";
108 print "watermarkVideos=$watermarkVideos<br>";
109 print "watermarkImage=$watermarkImage<br>";
113 /* Store other string constants we'll use later */
116 $youtubeUrlPattern="youtube.com";
117 $youtubeApiUrl="http://www.youtube.com/api2_rest";
118 /* We can't extract the server size from youtube */
120 $youtubeHeight="350";
123 $googleUrlPattern="video.google.com";
124 $googlePlayer="http://video.google.com/googleplayer.swf";
125 /* We can't extract the server size from google video */
130 $yahooUrlPattern="video.yahoo.com";
131 $yahooThumbnailUrl="http://thmg01.video.search.yahoo.com/image/";
134 $metacafeUrlPattern="metacafe.com";
135 $metacafeThumbnailUrl="http://www.metacafe.com/thumb/";
137 /* Gallery2 specific paths and variables */
138 $urlGenerator =& $gallery->getUrlGenerator();
139 $gallery2_url = $urlGenerator->getCurrentUrlDir();
140 $gallery2_flv_thumbnail = "modules/embedvideo/images/G2video_thumbnail.jpg";
141 $gallery2_video_watermark = "modules/embedvideo/images/G2video_watermark1.png";
142 $gallery2_flv_player = "modules/flashvideo/lib/G2flv.swf";
144 /* Store the passed URL in a shorter local variable */
145 $url = $form['webPage']['URL'];
148 *****************************
149 * Embed a Youtube Video
150 *****************************
152 if(preg_match("/$youtubeUrlPattern/",$url)) {
154 /* Make sure we can find a video_id in the URL */
155 if(preg_match("/watch\?v=(.*)/",$url,$matches)) {
156 $video_id = $matches[1];
158 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
159 "Unable to extract video id from url: $url"),null,null);
162 /* Make sure we have a valid youtube developer id */
163 $dev_id = $youtubeDevId;
164 if(!preg_match("/\w+/",$dev_id)) {
165 return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
166 "Invalid/missing YouTube developer ID: $dev_id"),null,null);
169 /* Youtube api feed */
170 $feed = $youtubeApiUrl.'?method=youtube.videos.get_details';
171 $feed.= "&dev_id=$dev_id&video_id=$video_id";
173 /* Get the youtube xml feed as a string data source */
174 list ($successfullyCopied, $xml, $response, $headers) =
175 GalleryCoreApi::fetchWebPage($feed, $extraHeaders);
176 if (!$successfullyCopied) {
177 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
178 "Unable to get video information at url: $url - $response"),null,null);
181 if(preg_match("/This video is private/",$xml)) {
182 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
183 "Unable to retrieve video information from youtube.".
184 "You cannot embed a private youtube video: $url"),null,null);
187 if(!strcmp($debugOutput,"true")) {
188 print "<h2>Youtube XML Dump</h2>";
193 /* Extract certain information from the xml feed */
194 preg_match_all("/\<title\>(.+?)\<\/title\>/smi",$xml, $title);
195 preg_match_all("/\<description\>(.+?)\<\/description\>/smi",$xml, $description);
196 preg_match_all("/\<thumbnail_url\>(.+?)\<\/thumbnail_url\>/smi",$xml, $thumbnail);
199 array_shift($thumbnail);
200 array_shift($description);
202 /* Replace html characters. More can be added but this seems to work */
203 for($i=0;$i<count($description[0]);$i++){
204 $description[0][$i] = preg_replace("/</","<",$description[0][$i]);
205 $description[0][$i] = html_entity_decode($description[0][$i],ENT_QUOTES);
208 /* Store the information found in some local variables */
209 $title = $title[0][0];
210 $summary = $description[0][0];
211 $thumbnail = $thumbnail[0][0];
213 /* Determine what our width and height should be based on our useRemoteSize parameter */
214 if(!strcmp($useRemoteSize,"true")) {
215 $width = $youtubeWidth;
216 $height = $youtubeHeight;
219 /* Determine if the video should autoplay or not based on the autoStart parameter */
221 if(!strcmp($autoStart,"true")) {
222 $autoStartStr="&autoplay=1";
225 /* Determine if the video should show related videos or not based on the youtubeShowRelated parameter */
226 $youtubeShowRelatedStr="";
227 if(!strcmp($youtubeShowRelated,"false")) {
228 $youtubeShowRelatedStr="&rel=0";
231 /* Format the description to hold a reference to the embedded video */
232 $description = '<object width="'.$width.'" height="'.$height.'">';
233 $description.= '<param name="movie" ';
234 $description.= 'value="http://www.youtube.com/v/'.$video_id.'"></param>';
235 $description.= '<param name="wmode" value="transparent"></param>';
236 $description.= '<embed src="http://www.youtube.com/v/';
237 $description.= $video_id.$autoStartStr.$youtubeShowRelatedStr;
238 $description.= '" type="application/x-shockwave-flash" wmode="transparent" ';
239 $description.= 'width="'.$width.'" height="'.$height.'"></embed></object>';
240 $description.= "<br>$summary";
243 **********************************
244 * Embed a Google Video
245 **********************************
247 } else if(preg_match("/$googleUrlPattern/",$url)) {
249 /* Make sure we can extract a docID */
250 if(preg_match("/docid=(.*)/",$url,$matches)) {
251 $doc_id = $matches[1];
253 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
254 "Unable to extract doc id from url: $url"),null,null);
257 /* Grab the contents of the webpage used to display the video on video.google.com */
258 list ($successfullyCopied, $contents, $response, $headers) =
259 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
260 if (!$successfullyCopied) {
261 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
262 "Unable to get video information at url: $url - $response"),NULL,NULL);
265 /* Extract the summary from the webpage contents */
266 //print "contents: $contents <br>";
267 preg_match('/<meta name="description" content="(.+?)\. \w+ \d+, \d+.*">/i',
268 $contents, $matches);
269 $summary=$matches[1];
271 /* Extract the title from the webpage contents */
273 if(preg_match('/<title>(.+?)\s+- Google Video<\/title>/i', $contents, $matches)) {
275 } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
279 /* Extract the thumbnail URL from the webpage contents */
280 preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
281 $contents, $matches);
282 $thumbnail=$matches[1];
283 $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
285 /* Determine what our width and height should be based on our useRemoteSize parameter */
286 if(!strcmp($useRemoteSize,"true")) {
287 $width = $googleWidth;
288 $height = $googleHeight;
291 /* Determine if the video should autoplay or not based on the autoStart parameter */
293 if(!strcmp($autoStart,"true")) {
294 $autoStartStr="&autoplay=1";
297 /* Format the description to hold a reference to the embedded video */
298 $description = '<embed ';
299 $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
300 $description.= 'type="application/x-shockwave-flash" ';
301 $description.= 'src="'.$googlePlayer.'?docId='.$doc_id.$autoStartStr.'" flashvars=""> ';
302 $description.= '</embed>';
303 $description.= "<br>$summary";
306 **********************************
307 * Embed a Yahoo Video
308 **********************************
309 * TODO: The autoStart parameter doesn't work with the yahoo video player
311 } else if(preg_match("/$yahooUrlPattern/",$url)) {
313 /* Make sure we can extract a vidID */
314 if(preg_match("/vid=(.*)/",$url,$matches)) {
315 $vid_id = $matches[1];
317 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
318 "Unable to extract vid id from url: $url"),null,null);
321 /* Grab the contents of the webpage used to display the video on video.google.com */
322 list ($successfullyCopied, $contents, $response, $headers) =
323 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
324 if (!$successfullyCopied) {
325 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
326 "Unable to get video information at url: $url - $response"),NULL,NULL);
329 /* Extract the summary from the webpage contents */
330 preg_match('/Description:<\/em><p>(.+?)<\/p>/', $contents, $matches);
331 $summary=$matches[1];
333 /* Extract the title from the webpage contents */
335 if(preg_match('/<title>(.+?)\s+- Yahoo! Video<\/title>/i', $contents, $matches)) {
337 } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
341 /* Build the thumbnail URL from the vid_id */
342 $thumbnail=$yahooThumbnailUrl.$vid_id."_01";
344 /* Format the description to hold a reference to the embedded video */
345 preg_match('/(<embed src.+?<\/embed>)/', $contents, $matches);
346 $description=$matches[1];
347 if(!strcmp($useRemoteSize,"false")) {
348 $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
349 $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
351 $description.= "<br>$summary";
354 **********************************
355 * Embed a MetaCafe Video
356 **********************************
358 } else if(preg_match("/$metacafeUrlPattern/",$url)) {
360 /* Make sure we can extract a itemID */
361 if(preg_match("/\/watch\/(.+?)\/(.+?)/",$url,$matches)) {
362 $item_id = $matches[1];
364 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
365 "Unable to extract item id from url: $url"),null,null);
368 /* Grab the contents of the webpage used to display the video on video.google.com */
369 list ($successfullyCopied, $contents, $response, $headers) =
370 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
371 if (!$successfullyCopied) {
372 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
373 "Unable to get video information at url: $url - $response"),NULL,NULL);
376 /* Extract the summary from the webpage contents */
377 preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
378 $summary=$matches[1];
380 /* Extract the title from the webpage contents */
381 preg_match('/<title>(.+?)<\/title>/i', $contents, $matches);
384 /* Build the thumbnail URL from the item_id */
385 $thumbnail=$metacafeThumbnailUrl.$item_id.".jpg";
387 /* Format the description to hold a reference to the embedded video */
388 preg_match('/(embed src.+?\/embed)/', $contents, $matches);
389 $description="<".$matches[1];
390 $description=preg_replace("/"/","'",$description);
391 if(!strcmp($useRemoteSize,"false")) {
392 $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
393 $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
395 if(!strcmp($autoStart,"true")) {
396 $description=preg_replace("/\.swf/",".swf?playerVars=autoPlay=yes",$description);
398 $description.= "</embed>";
399 $description.= "<br>$summary";
403 **********************************
404 * Embed a remote .swf file
405 **********************************
407 } else if(preg_match("/.*\/(.+?)\.swf/i",$url,$matches)) {
409 /* Set the title and summary to the name of the file */
410 $title = $matches[1];
411 $summary = $matches[1];
414 * Set the thumbnail to some generic jpg image,
415 * since we can't extract it from the remote swf file.
416 * If no parameter is set, set it to a default value.
418 if(preg_match("/\w+/", $flvThumbnail)) {
419 $thumbnail = $flvThumbnail;
421 $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
425 * Check to make sure the URL to the remote swf file is valid
426 * (That the file exists at the URL given)
428 list ($successfullyCopied, $response, $headers) =
429 $this->fetchWebFileHeaders($url, $extraHeaders);
430 if (!$successfullyCopied) {
431 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
432 "Unable to find the video at url: $url - $response"),NULL,NULL);
436 * Format the description to hold a reference to the embedded video
439 /* Format the description to hold a reference to the embedded video */
440 $description ='<embed src="'.$url.'">';
443 **********************************
444 * Embed a remote .flv file
445 **********************************
447 } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
449 /* Set the title and summary to the name of the file */
450 $title = $matches[1];
451 $summary = $matches[1];
454 * Set the thumbnail to some generic jpg image,
455 * since we can't extract it from the remote flv file.
456 * If no parameter is set, set it to a default value.
458 if(preg_match("/\w+/", $flvThumbnail)) {
459 $thumbnail = $flvThumbnail;
461 $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
465 * Check to make sure the URL to the remote flv file is valid
466 * (That the file exists at the URL given)
468 list ($successfullyCopied, $response, $headers) =
469 $this->fetchWebFileHeaders($url, $extraHeaders);
470 if (!$successfullyCopied) {
471 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
472 "Unable to find the video at url: $url - $response"),NULL,NULL);
476 * Format the description to hold a reference to the embedded video
477 * This reference will be embedded using the G2 internal player,
478 * or an external player if provided by the user.
480 if(!strcmp($useInternalFlvPlayer,"false")) {
483 * The user has indicated they want to use an external flv player
484 * Make sure one is defined!
486 if(!preg_match("/\w+/",$externalFlvPlayer)) {
487 return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
488 "Invalid/missing external player parameter"),null,null);
491 /* Format the description to hold a reference to the embedded video */
492 $description ='<embed src="'.$externalFlvPlayer.'" ';
493 $description.= 'width="'.$width.'" height="'.$height.'" ';
494 $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
495 $description.= 'type="application/x-shockwave-flash" ';
496 $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
497 $description.= 'flashvars="file='.$url;
498 $description.= '&fullscreenpage='.$thumbnail;
499 $description.= '&linktarget=_Blank&image='.$thumbnail;
501 if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
502 /* Format the flashvars for the internal G2 flv player */
503 $description.= '&showdigits=true&autostart='.$autoStart.'&showfsbutton=true&';
504 $description.= '&repeat=false&lightcolor=0x9999FF';
505 $description.= '&backcolor=0x888888&frontcolor=0x000000"';
507 /* Format the flashvars for the external G2 flv player */
508 $description.= '&'.$externalFlvPlayerVars;
510 $description.= ' /> </p>';
512 /* Internal FLV player */
514 /* Format the description to hold a reference to the embedded video */
515 $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
516 $description = '<script type="text/javascript">'."\n";
517 $description.= '// <![CDATA['."\n";
518 $description.= 'function divResize(id, nw, nh) {'."\n";
519 $description.= 'var obj = document.getElementById(id);'."\n";
520 $description.= 'obj.style.width = nw + "px";'."\n";
521 $description.= 'obj.style.height = nh + "px";'."\n";
522 $description.= '}'."\n";
523 $description.= '// ]]>'."\n";
524 $description.= '</script>'."\n";
525 $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
526 $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
527 $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
528 $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
529 $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
530 $description.= '<param name="FlashVars" value="flvUrl='.$url;
531 $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
532 $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
533 $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
534 $description.= '<param name="quality" value="high"/>';
535 $description.= '<param name="scale" value="noscale"/>';
536 $description.= '<param name="salign" value="lt"/>';
537 $description.= '<param name="wmode" value="transparent"/>';
538 $description.= '<param name="allowScriptAccess" value="always"/>';
539 $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
540 $description.= 'flashvars="flvUrl='.$url;
541 $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
542 $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
543 $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
544 $description.= 'type="application/x-shockwave-flash" ';
545 $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
546 $description.= 'wmode="transparent" allowScriptAccess="always" ';
547 $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
548 $description.= '</object></div>';
552 **********************************
553 * Unsupported URL to embed
554 **********************************
557 return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
558 "Unable to embed video from: $url"),null,null);
563 **********************************
564 * Add the video to Gallery
565 **********************************
568 /* Get a local tmp file to save the thumbnail URL to */
569 $tmpDir = $gallery->getConfig('data.gallery.tmp');
570 $tmpFile = $platform->tempnam($tmpDir, 'add');
573 /* Fetch the thumbnail and save it to a local file */
574 list ($successfullyCopied, $response, $headers) =
575 GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
576 if (!$successfullyCopied) {
577 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
578 "Unable to copy thumbnail from url: $thumbnail - $response"),null,null);
581 /* Obtain the mimeType of the thumbnail */
582 list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
584 /* Set the filename for the item we want to add */
586 $fileName = preg_replace("/\s+/","_",$fileName);
587 $fileName = preg_replace("/'/","",$fileName);
588 $fileName = preg_replace("/\"/","",$fileName);
589 $fileName = preg_replace("/&#\d+;/","",$fileName);
591 /* General debug output */
592 if(!strcmp($debugOutput,"true")) {
593 print "<h2>Item Parameters</h2>";
594 print "url: $url <br>";
595 print "title: $title <br>";
596 print "thumbnailUrl: <img src=\"".$thumbnail."\">\n</a>".$summary."</p>";
597 print "description: <p>$description</p>";
598 print "thumbnail: $tmpFile <br>";
599 print "mimeType: $mimeType <br>";
600 print "fileName: $fileName <br>";
601 print "width: $width <br>";
602 print "height: $height <br>";
606 /* Resize the thumbnail image to the size indicated by our album */
608 list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'resize');
610 $debugString.="Checking to see if a toolkit that can resize images was found. <br>";
611 if (isset($toolkit)) {
612 $newTmpFile = $platform->tempnam($tmpDir, 'add');
613 $newTmpFile.= ".jpg";
614 $thumbnailSize = 150;
615 list ($ret, $preferences) =
616 GalleryCoreApi::fetchDerivativePreferencesForItem($item->getId());
618 foreach ($preferences as $preference) {
619 if (preg_match('/thumbnail\|(\d+)/',
620 $preference['derivativeOperations'], $matches)) {
621 $thumbnailSize = $matches[1];
622 $debugString.="Found thumbnail size in album preferences: $thumbnailSize <br>";
628 // Obtain the width and height of the original thumbnail, finding out it's ratio,
629 // and using that ratio when determining the width of the video below.
630 // Example: youtube: 130x97 google: 160x120 metacafe: 90x76 yahoo: 100x70
631 // Set the thumbnailHeight to the current thumbnailSize
632 // Set the thumbnailWidth to the appropriate size based on the thumbnailHeight * ratio
633 $image_data = @getimagesize($tmpFile);
635 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
636 "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
638 $ratio = $image_data[0] / $image_data[1];
639 $debugString.="Using ratio from original thumbnail of $ratio. ";
640 $thumbnailHeight=$thumbnailSize;
641 $thumbnailWidth=round($thumbnailHeight * $ratio);
642 $debugString.="Resizing thumbnail image to $thumbnailWidth x $thumbnailHeight: $tmpFile -> $newTmpFile <br>";
643 $toolkit->performOperation($mimeType, 'resize', $tmpFile, $newTmpFile,
644 array($thumbnailWidth,$thumbnailHeight));
647 if(!strcmp($debugOutput,"true")) {
648 print "<h2>Thumbnail Resize</h2>";
649 print "$debugString";
653 /* Watermark the video thumbnail image if indicated by our parameter */
654 if(!strcmp($watermarkVideos,"true")) {
657 * If no watermarkImage parameter is set, set it to a default value.
659 if(preg_match("/\w+/", $watermarkImage)) {
660 $watermarkImage = $watermarkImage;
662 $watermarkImage = $gallery2_url.$gallery2_video_watermark;
665 /* Get the watermark Image Extension */
666 preg_match('/\.(...)$/', $watermarkImage, $matches);
667 $watermarkExt=$matches[1];
670 * Check to make sure the URL to the watermark image file is valid
671 * (That the file exists at the URL given)
673 list ($successfullyCopied, $response, $headers) =
674 $this->fetchWebFileHeaders($watermarkImage, $extraHeaders);
675 if (!$successfullyCopied) {
676 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
677 "Unable to find the watermark image at url: $watermarkImage - $response"),NULL,NULL);
680 /* Download the watermark image to a local file */
681 $tmpDir = $gallery->getConfig('data.gallery.tmp');
682 $watermark = $platform->tempnam($tmpDir, 'wmk_img_');
683 $watermark.= "." . $watermarkExt;
684 list ($successfullyCopied, $response, $headers) =
685 GalleryCoreApi::fetchWebFile($watermarkImage, $watermark, $extraHeaders);
686 if (!$successfullyCopied) {
687 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
688 "Unable to copy watermark image from url: $watermarkImage - $response"),null,null);
691 /* See if there is a toolkit installed that can perform a composite operation */
692 list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'composite');
694 return array($ret->wrap(__FILE__, __LINE__,
695 "Unable to locate a toolkit module to perform the 'composite' watermark operation"), null);
698 /* Make sure we can access the toolkit found */
699 if (!isset($toolkit)) {
700 return array(GalleryStatus::error(ERROR_PERMISSION_DENIED, __FILE__, __LINE__,
701 "Unable to access the toolkit module to perform the 'composite' watermark operation"), null);
704 /* Get the image dimensions of the thumbnail */
705 $image_data = @getimagesize($newTmpFile);
707 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
708 "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
710 $thumbnailWidth = $image_data[0];
711 $thumbnailHeight = $image_data[1];
713 /* Get the image dimensions of the watermark */
714 $image_data = @getimagesize($watermark);
716 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
717 "Unable to retrieve watermark dimensions for: $tmpFile"),null,null);
719 $watermarkWidth = $image_data[0];
720 $watermarkHeight = $image_data[1];
722 /* Obtain the mimeType of the watermark */
723 list ($ret, $watermarkMimeType) = GalleryCoreApi::getMimeType($watermark);
725 /* Remove the gallery base path from the watermark image path */
726 /* This has to be done to satisfy the argument requirement for the toolkit operation */
727 $dataDir = $gallery->getConfig('data.gallery.base');
728 $dataDir=preg_replace("/\//","\\/",$dataDir);
729 preg_match("/$dataDir(.*)/", $watermark, $matches);
730 $watermark = $matches[1];
732 /* General debug output */
733 if(!strcmp($debugOutput,"true")) {
734 print "<h2>Watermark Operation</h2>";
735 print "watermarkImage: $watermarkImage <br>";
736 print "watermarkTmpImage: $watermark <br>";
737 print "watermarkMimeType: $watermarkMimeType <br>";
738 print "watermarkWidth: $watermarkWidth <br>";
739 print "watermarkHeight: $watermarkHeight <br>";
740 print "watermarkedWidth: $thumbnailWidth <br>";
741 print "watermarkedHeight: $thumbnailHeight <br>";
744 /* Apply the watermark image to the thumbnail */
745 $tmpFile = $platform->tempnam($tmpDir, 'wmk_');
746 list ($ret, $mimeType) = $toolkit->performOperation(
747 $mimeType, 'composite', $newTmpFile, $tmpFile,
748 array($watermark, $watermarkMimeType,
749 $watermarkWidth, $watermarkHeight,
750 'bottom-left', 0, 0));
752 /* Check the return code of the composite operation */
754 return array($ret->wrap(__FILE__, __LINE__,
755 "Unable to apply watermark to the video thumbnail image"), null);
758 if(!strcmp($debugOutput,"true")) {
759 print "watermarked Image: $tmpFile <br>";
763 /* Update the path of our thumbnail to point to the new watermarked thumbnail instead */
764 $newTmpFile = $tmpFile;
768 /* Make the gallery2 call to add this item to the album */
769 list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($newTmpFile,
778 return array($ret, null, null);
781 $status['addedFiles'][] = array('fileName' => $url,
782 'id' => $newItem->getId(),
783 'warnings' => array());
785 if(!strcmp($debugOutput,"true")) {
786 print "<br><br><h2>Video Successfully Added to your Gallery Album</h2><br><br><hr>";
790 /* Keep the tmpfiles around if we are in debug mode. Otherwise, remove them. */
791 if(!strcmp($debugOutput,"false")) {
792 @$platform->unlink($tmpFile);
793 @$platform->unlink($newTmpFile);
798 return array(null, $error, $status);
802 * A simple function to resolve the value of a parameter from
803 * the default or override value if it exists, or set it
804 * to the default passed as an argument.
806 function getParameter($params, $name, $default="") {
807 if(isset($params['override'][$name])) {
808 /* print "override $name = ".$params['override'][$name]."<br>"; */
809 return($params['override'][$name]);
810 } else if(isset($params['default'][$name])) {
811 /* print "default $name = ".$params['default'][$name] ."<br>"; */
812 return($params['default'][$name]);
814 /* print "$name = $default <br>"; */
820 * A simple function to get the headers only (no body) for a given URL
821 * This was taken from GalleryCoreApi::requestWebPage
823 function fetchWebFileHeaders($url, $requestHeaders=array()) {
826 $requestMethod='GET';
828 /* Convert illegal characters */
829 $url = str_replace(' ', '%20', $url);
831 /* Unescape ampersands, since if the URL comes from form input it will be escaped */
832 $url = str_replace('&', '&', $url);
834 $platform =& $gallery->getPlatform();
836 $urlComponents = parse_url($url);
837 if (empty($urlComponents['port'])) {
838 $urlComponents['port'] = 80;
840 if (empty($urlComponents['path'])) {
841 $urlComponents['path'] = '/';
844 $handle = @$platform->fsockopen(
845 $urlComponents['host'], $urlComponents['port'], $errno, $errstr, 5);
846 if (empty($handle)) {
847 $gallery->debug("Error $errno: '$errstr' requesting $url");
848 return array(null, null, null);
851 $requestUri = $urlComponents['path'];
852 if (!empty($urlComponents['query'])) {
853 $requestUri .= '?' . $urlComponents['query'];
855 $headerLines = array('Host: ' . $urlComponents['host']);
856 foreach ($requestHeaders as $key => $value) {
857 $headerLines[] = $key . ': ' . $value;
860 $success = $platform->fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s",
863 implode("\r\n", $headerLines),
866 /* Zero bytes written or false was returned */
868 "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''));
869 return array(null, null, null);
871 $platform->fflush($handle);
875 * Read the status line. fgets stops after newlines. The first line is the protocol
876 * version followed by a numeric status code and its associated textual phrase.
878 $responseStatus = trim($platform->fgets($handle, 4096));
879 if (empty($responseStatus)) {
880 $gallery->debug('Empty http response code, maybe timeout');
881 return array(null, null, null);
884 /* Read the headers */
885 $responseHeaders = array();
886 while (!$platform->feof($handle)) {
887 $line = trim($platform->fgets($handle, 4096));
892 /* Normalize the line endings */
893 $line = str_replace("\r", '', $line);
895 list ($key, $value) = explode(':', $line, 2);
896 if (isset($responseHeaders[$key])) {
897 if (!is_array($responseHeaders[$key])) {
898 $responseHeaders[$key] = array($responseHeaders[$key]);
900 $responseHeaders[$key][] = trim($value);
902 $responseHeaders[$key] = trim($value);
905 $platform->fclose($handle);
907 if(preg_match("/Not found/i", $responseStatus)) {
911 //print "success: $success <br>responseStatus: $responseStatus <br>responseHeaders: $responseHeaders <br>";
913 return array($success, $responseStatus, $responseHeaders);
917 * @see ItemAdd:loadTemplate
919 function loadTemplate(&$template, &$form, $item) {
922 if ($form['formName'] != 'ItemAddEmbedVideo') {
923 /* First time around, load the form with item data */
924 $form['webPage'] = '';
925 $form['formName'] = 'ItemAddEmbedVideo';
928 $session =& $gallery->getSession();
930 $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
933 'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
934 'modules_embedvideo');
938 * @see ItemAddPlugin::getTitle
940 function getTitle() {
941 list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
943 return array($ret, null);
946 return array(null, $module->translate('Embed Video'));