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, $watermarkAlignment;
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");
92 $watermarkAlignment = $this->getParameter($ItemAddEmbedVideo, 'watermarkAlignment', "center");
94 /* Print our stored/set Parameters */
95 if(!strcmp($debugOutput,"true")) {
97 print "<h2>Variable Parameters</h2>";
98 print "debugOutput=$debugOutput<br>";
99 print "useInternalFlvPlayer=$useInternalFlvPlayer<br>";
100 print "youtubeDevId=$youtubeDevId<br>";
101 print "youtubeShowRelated=$youtubeShowRelated<br>";
102 print "width=$width<br>";
103 print "height=$height<br>";
104 print "externalFlvPlayer=$externalFlvPlayer<br>";
105 print "externalFlvPlayerVars=$externalFlvPlayerVars<br>";
106 print "flvThumbnail=$flvThumbnail<br>";
107 print "useRemoteSize=$useRemoteSize<br>";
108 print "autoStart=$autoStart<br>";
109 print "watermarkVideos=$watermarkVideos<br>";
110 print "watermarkImage=$watermarkImage<br>";
111 print "watermarkAlignment=$watermarkAlignment<br>";
115 /* Store other string constants we'll use later */
118 $youtubeUrlPattern="youtube.com";
119 $youtubeApiUrl="http://www.youtube.com/api2_rest";
120 /* We can't extract the server size from youtube */
122 $youtubeHeight="350";
125 $googleUrlPattern="video.google.com";
126 $googlePlayer="http://video.google.com/googleplayer.swf";
127 /* We can't extract the server size from google video */
132 $yahooUrlPattern="video.yahoo.com";
133 $yahooThumbnailUrl="http://thmg01.video.search.yahoo.com/image/";
136 $metacafeUrlPattern="metacafe.com";
137 $metacafeThumbnailUrl="http://www.metacafe.com/thumb/";
139 /* Gallery2 specific paths and variables */
140 $urlGenerator =& $gallery->getUrlGenerator();
141 $gallery2_url = $urlGenerator->getCurrentUrlDir();
142 $gallery2_flv_thumbnail = "modules/embedvideo/images/G2video_thumbnail.jpg";
143 $gallery2_video_watermark = "modules/embedvideo/images/G2video_watermark1.png";
144 $gallery2_flv_player = "modules/flashvideo/lib/G2flv.swf";
146 /* Store the passed URL in a shorter local variable */
147 $url = $form['webPage']['URL'];
150 *****************************
151 * Embed a Youtube Video
152 *****************************
154 if(preg_match("/$youtubeUrlPattern/",$url)) {
156 /* Make sure we can find a video_id in the URL */
157 if(preg_match("/watch\?v=(.*)/",$url,$matches)) {
158 $video_id = $matches[1];
160 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
161 "Unable to extract video id from url: $url"),null,null);
164 /* Make sure we have a valid youtube developer id */
165 $dev_id = $youtubeDevId;
166 if(!preg_match("/\w+/",$dev_id)) {
167 return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
168 "Invalid/missing YouTube developer ID: $dev_id"),null,null);
171 /* Youtube api feed */
172 $feed = $youtubeApiUrl.'?method=youtube.videos.get_details';
173 $feed.= "&dev_id=$dev_id&video_id=$video_id";
175 /* Get the youtube xml feed as a string data source */
176 list ($successfullyCopied, $xml, $response, $headers) =
177 GalleryCoreApi::fetchWebPage($feed, $extraHeaders);
178 if (!$successfullyCopied) {
179 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
180 "Unable to get video information at url: $url - $response"),null,null);
183 if(preg_match("/This video is private/",$xml)) {
184 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
185 "Unable to retrieve video information from youtube.".
186 "You cannot embed a private youtube video: $url"),null,null);
189 if(!strcmp($debugOutput,"true")) {
190 print "<h2>Youtube XML Dump</h2>";
195 /* Extract certain information from the xml feed */
196 preg_match_all("/\<title\>(.+?)\<\/title\>/smi",$xml, $title);
197 preg_match_all("/\<description\>(.+?)\<\/description\>/smi",$xml, $description);
198 preg_match_all("/\<thumbnail_url\>(.+?)\<\/thumbnail_url\>/smi",$xml, $thumbnail);
201 array_shift($thumbnail);
202 array_shift($description);
204 /* Replace html characters. More can be added but this seems to work */
205 for($i=0;$i<count($description[0]);$i++){
206 $description[0][$i] = preg_replace("/</","<",$description[0][$i]);
207 $description[0][$i] = html_entity_decode($description[0][$i],ENT_QUOTES);
210 /* Store the information found in some local variables */
211 $title = $title[0][0];
212 $summary = $description[0][0];
213 $thumbnail = $thumbnail[0][0];
215 /* Determine what our width and height should be based on our useRemoteSize parameter */
216 if(!strcmp($useRemoteSize,"true")) {
217 $width = $youtubeWidth;
218 $height = $youtubeHeight;
221 /* Determine if the video should autoplay or not based on the autoStart parameter */
223 if(!strcmp($autoStart,"true")) {
224 $autoStartStr="&autoplay=1";
227 /* Determine if the video should show related videos or not based on the youtubeShowRelated parameter */
228 $youtubeShowRelatedStr="";
229 if(!strcmp($youtubeShowRelated,"false")) {
230 $youtubeShowRelatedStr="&rel=0";
233 /* Format the description to hold a reference to the embedded video */
234 $description = '<object width="'.$width.'" height="'.$height.'">';
235 $description.= '<param name="movie" ';
236 $description.= 'value="http://www.youtube.com/v/'.$video_id.'"></param>';
237 $description.= '<param name="wmode" value="transparent"></param>';
238 $description.= '<embed src="http://www.youtube.com/v/';
239 $description.= $video_id.$autoStartStr.$youtubeShowRelatedStr;
240 $description.= '" type="application/x-shockwave-flash" wmode="transparent" ';
241 $description.= 'width="'.$width.'" height="'.$height.'"></embed></object>';
242 $description.= "<br>$summary";
245 **********************************
246 * Embed a Google Video
247 **********************************
249 } else if(preg_match("/$googleUrlPattern/",$url)) {
251 /* Make sure we can extract a docID */
252 if(preg_match("/docid=(.*)/",$url,$matches)) {
253 $doc_id = $matches[1];
255 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
256 "Unable to extract doc id from url: $url"),null,null);
259 /* Grab the contents of the webpage used to display the video on video.google.com */
260 list ($successfullyCopied, $contents, $response, $headers) =
261 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
262 if (!$successfullyCopied) {
263 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
264 "Unable to get video information at url: $url - $response"),NULL,NULL);
267 /* Extract the summary from the webpage contents */
268 //print "contents: $contents <br>";
269 preg_match('/<meta name="description" content="(.+?)\. \w+ \d+, \d+.*">/i',
270 $contents, $matches);
271 $summary=$matches[1];
273 /* Extract the title from the webpage contents */
275 if(preg_match('/<title>(.+?)\s+- Google Video<\/title>/i', $contents, $matches)) {
277 } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
281 /* Extract the thumbnail URL from the webpage contents */
282 preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
283 $contents, $matches);
284 $thumbnail=$matches[1];
285 $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
287 /* Determine what our width and height should be based on our useRemoteSize parameter */
288 if(!strcmp($useRemoteSize,"true")) {
289 $width = $googleWidth;
290 $height = $googleHeight;
293 /* Determine if the video should autoplay or not based on the autoStart parameter */
295 if(!strcmp($autoStart,"true")) {
296 $autoStartStr="&autoplay=1";
299 /* Format the description to hold a reference to the embedded video */
300 $description = '<embed ';
301 $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
302 $description.= 'type="application/x-shockwave-flash" ';
303 $description.= 'src="'.$googlePlayer.'?docId='.$doc_id.$autoStartStr.'" flashvars=""> ';
304 $description.= '</embed>';
305 $description.= "<br>$summary";
308 **********************************
309 * Embed a Yahoo Video
310 **********************************
311 * TODO: The autoStart parameter doesn't work with the yahoo video player
313 } else if(preg_match("/$yahooUrlPattern/",$url)) {
315 /* Make sure we can extract a vidID */
316 if(preg_match("/vid=(.*)/",$url,$matches)) {
317 $vid_id = $matches[1];
319 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
320 "Unable to extract vid id from url: $url"),null,null);
323 /* Grab the contents of the webpage used to display the video on video.google.com */
324 list ($successfullyCopied, $contents, $response, $headers) =
325 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
326 if (!$successfullyCopied) {
327 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
328 "Unable to get video information at url: $url - $response"),NULL,NULL);
331 /* Extract the summary from the webpage contents */
332 preg_match('/Description:<\/em><p>(.+?)<\/p>/', $contents, $matches);
333 $summary=$matches[1];
335 /* Extract the title from the webpage contents */
337 if(preg_match('/<title>(.+?)\s+- Yahoo! Video<\/title>/i', $contents, $matches)) {
339 } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
343 /* Build the thumbnail URL from the vid_id */
344 $thumbnail=$yahooThumbnailUrl.$vid_id."_01";
346 /* Format the description to hold a reference to the embedded video */
347 preg_match('/(<embed src.+?<\/embed>)/', $contents, $matches);
348 $description=$matches[1];
349 if(!strcmp($useRemoteSize,"false")) {
350 $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
351 $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
353 $description.= "<br>$summary";
356 **********************************
357 * Embed a MetaCafe Video
358 **********************************
360 } else if(preg_match("/$metacafeUrlPattern/",$url)) {
362 /* Make sure we can extract a itemID */
363 if(preg_match("/\/watch\/(.+?)\/(.+?)/",$url,$matches)) {
364 $item_id = $matches[1];
366 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
367 "Unable to extract item id from url: $url"),null,null);
370 /* Grab the contents of the webpage used to display the video on video.google.com */
371 list ($successfullyCopied, $contents, $response, $headers) =
372 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
373 if (!$successfullyCopied) {
374 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
375 "Unable to get video information at url: $url - $response"),NULL,NULL);
378 /* Extract the summary from the webpage contents */
379 preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
380 $summary=$matches[1];
382 /* Extract the title from the webpage contents */
383 preg_match('/<title>(.+?)<\/title>/i', $contents, $matches);
386 /* Build the thumbnail URL from the item_id */
387 $thumbnail=$metacafeThumbnailUrl.$item_id.".jpg";
389 /* Format the description to hold a reference to the embedded video */
390 preg_match('/(embed src.+?\/embed)/', $contents, $matches);
391 $description="<".$matches[1];
392 $description=preg_replace("/"/","'",$description);
393 if(!strcmp($useRemoteSize,"false")) {
394 $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
395 $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
397 if(!strcmp($autoStart,"true")) {
398 $description=preg_replace("/\.swf/",".swf?playerVars=autoPlay=yes",$description);
400 $description.= "</embed>";
401 $description.= "<br>$summary";
405 **********************************
406 * Embed a remote .swf file
407 **********************************
409 } else if(preg_match("/.*\/(.+?)\.swf/i",$url,$matches)) {
411 /* Set the title and summary to the name of the file */
412 $title = $matches[1];
413 $summary = $matches[1];
416 * Set the thumbnail to some generic jpg image,
417 * since we can't extract it from the remote swf file.
418 * If no parameter is set, set it to a default value.
420 if(preg_match("/\w+/", $flvThumbnail)) {
421 $thumbnail = $flvThumbnail;
423 $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
427 * Check to make sure the URL to the remote swf file is valid
428 * (That the file exists at the URL given)
430 list ($successfullyCopied, $response, $headers) =
431 $this->fetchWebFileHeaders($url, $extraHeaders);
432 if (!$successfullyCopied) {
433 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
434 "Unable to find the video at url: $url - $response"),NULL,NULL);
438 * Format the description to hold a reference to the embedded video
441 /* Format the description to hold a reference to the embedded video */
442 $description ='<embed src="'.$url.'">';
445 **********************************
446 * Embed a remote .flv file
447 **********************************
449 } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
451 /* Set the title and summary to the name of the file */
452 $title = $matches[1];
453 $summary = $matches[1];
456 * Set the thumbnail to some generic jpg image,
457 * since we can't extract it from the remote flv file.
458 * If no parameter is set, set it to a default value.
460 if(preg_match("/\w+/", $flvThumbnail)) {
461 $thumbnail = $flvThumbnail;
463 $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
467 * Check to make sure the URL to the remote flv file is valid
468 * (That the file exists at the URL given)
470 list ($successfullyCopied, $response, $headers) =
471 $this->fetchWebFileHeaders($url, $extraHeaders);
472 if (!$successfullyCopied) {
473 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
474 "Unable to find the video at url: $url - $response"),NULL,NULL);
478 * Format the description to hold a reference to the embedded video
479 * This reference will be embedded using the G2 internal player,
480 * or an external player if provided by the user.
482 if(!strcmp($useInternalFlvPlayer,"false")) {
485 * The user has indicated they want to use an external flv player
486 * Make sure one is defined!
488 if(!preg_match("/\w+/",$externalFlvPlayer)) {
489 return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
490 "Invalid/missing external player parameter"),null,null);
493 /* Format the description to hold a reference to the embedded video */
494 $description ='<embed src="'.$externalFlvPlayer.'" ';
495 $description.= 'width="'.$width.'" height="'.$height.'" ';
496 $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
497 $description.= 'type="application/x-shockwave-flash" ';
498 $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
499 $description.= 'flashvars="file='.$url;
500 $description.= '&fullscreenpage='.$thumbnail;
501 $description.= '&linktarget=_Blank&image='.$thumbnail;
503 if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
504 /* Format the flashvars for the internal G2 flv player */
505 $description.= '&showdigits=true&autostart='.$autoStart.'&showfsbutton=true&';
506 $description.= '&repeat=false&lightcolor=0x9999FF';
507 $description.= '&backcolor=0x888888&frontcolor=0x000000"';
509 /* Format the flashvars for the external G2 flv player */
510 $description.= '&'.$externalFlvPlayerVars;
512 $description.= ' /> </p>';
514 /* Internal FLV player */
516 /* Format the description to hold a reference to the embedded video */
517 $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
518 $description = '<script type="text/javascript">'."\n";
519 $description.= '// <![CDATA['."\n";
520 $description.= 'function divResize(id, nw, nh) {'."\n";
521 $description.= 'var obj = document.getElementById(id);'."\n";
522 $description.= 'obj.style.width = nw + "px";'."\n";
523 $description.= 'obj.style.height = nh + "px";'."\n";
524 $description.= '}'."\n";
525 $description.= '// ]]>'."\n";
526 $description.= '</script>'."\n";
527 $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
528 $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
529 $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
530 $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
531 $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
532 $description.= '<param name="FlashVars" value="flvUrl='.$url;
533 $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
534 $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
535 $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
536 $description.= '<param name="quality" value="high"/>';
537 $description.= '<param name="scale" value="noscale"/>';
538 $description.= '<param name="salign" value="lt"/>';
539 $description.= '<param name="wmode" value="transparent"/>';
540 $description.= '<param name="allowScriptAccess" value="always"/>';
541 $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
542 $description.= 'flashvars="flvUrl='.$url;
543 $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
544 $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
545 $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
546 $description.= 'type="application/x-shockwave-flash" ';
547 $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
548 $description.= 'wmode="transparent" allowScriptAccess="always" ';
549 $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
550 $description.= '</object></div>';
554 **********************************
555 * Unsupported URL to embed
556 **********************************
559 return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
560 "Unable to embed video from: $url"),null,null);
565 **********************************
566 * Add the video to Gallery
567 **********************************
570 /* Get a local tmp file to save the thumbnail URL to */
571 $tmpDir = $gallery->getConfig('data.gallery.tmp');
572 $tmpFile = $platform->tempnam($tmpDir, 'add');
575 /* Fetch the thumbnail and save it to a local file */
576 list ($successfullyCopied, $response, $headers) =
577 GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
578 if (!$successfullyCopied) {
579 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
580 "Unable to copy thumbnail from url: $thumbnail - $response"),null,null);
583 /* Obtain the mimeType of the thumbnail */
584 list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
586 /* Set the filename for the item we want to add */
588 $fileName = preg_replace("/\s+/","_",$fileName);
589 $fileName = preg_replace("/'/","",$fileName);
590 $fileName = preg_replace("/\"/","",$fileName);
591 $fileName = preg_replace("/&#\d+;/","",$fileName);
593 /* General debug output */
594 if(!strcmp($debugOutput,"true")) {
595 print "<h2>Item Parameters</h2>";
596 print "url: $url <br>";
597 print "title: $title <br>";
598 print "thumbnailUrl: <img src=\"".$thumbnail."\">\n</a>".$summary."</p>";
599 print "description: <p>$description</p>";
600 print "thumbnail: $tmpFile <br>";
601 print "mimeType: $mimeType <br>";
602 print "fileName: $fileName <br>";
603 print "width: $width <br>";
604 print "height: $height <br>";
608 /* Resize the thumbnail image to the size indicated by our album */
610 list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'resize');
612 $debugString.="Checking to see if a toolkit that can resize images was found. <br>";
613 if (isset($toolkit)) {
614 $newTmpFile = $platform->tempnam($tmpDir, 'add');
615 $newTmpFile.= ".jpg";
616 $thumbnailSize = 150;
617 list ($ret, $preferences) =
618 GalleryCoreApi::fetchDerivativePreferencesForItem($item->getId());
620 foreach ($preferences as $preference) {
621 if (preg_match('/thumbnail\|(\d+)/',
622 $preference['derivativeOperations'], $matches)) {
623 $thumbnailSize = $matches[1];
624 $debugString.="Found thumbnail size in album preferences: $thumbnailSize <br>";
630 // Obtain the width and height of the original thumbnail, finding out it's ratio,
631 // and using that ratio when determining the width of the video below.
632 // Example: youtube: 130x97 google: 160x120 metacafe: 90x76 yahoo: 100x70
633 // Set the thumbnailHeight to the current thumbnailSize
634 // Set the thumbnailWidth to the appropriate size based on the thumbnailHeight * ratio
635 $image_data = @getimagesize($tmpFile);
637 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
638 "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
640 $ratio = $image_data[0] / $image_data[1];
641 $debugString.="Using ratio from original thumbnail of $ratio. ";
642 $thumbnailHeight=$thumbnailSize;
643 $thumbnailWidth=round($thumbnailHeight * $ratio);
644 $debugString.="Resizing thumbnail image to $thumbnailWidth x $thumbnailHeight: $tmpFile -> $newTmpFile <br>";
645 $toolkit->performOperation($mimeType, 'resize', $tmpFile, $newTmpFile,
646 array($thumbnailWidth,$thumbnailHeight));
649 if(!strcmp($debugOutput,"true")) {
650 print "<h2>Thumbnail Resize</h2>";
651 print "$debugString";
655 /* Watermark the video thumbnail image if indicated by our parameter */
656 if(!strcmp($watermarkVideos,"true")) {
659 * If no watermarkImage parameter is set, set it to a default value.
661 if(preg_match("/\w+/", $watermarkImage)) {
662 $watermarkImage = $watermarkImage;
664 $watermarkImage = $gallery2_url.$gallery2_video_watermark;
667 /* Get the watermark Image Extension */
668 preg_match('/\.(...)$/', $watermarkImage, $matches);
669 $watermarkExt=$matches[1];
672 * Check to make sure the URL to the watermark image file is valid
673 * (That the file exists at the URL given). Skip this part if it is a local path.
675 if(!preg_match("/^\//", $watermarkImage)) {
676 list ($successfullyCopied, $response, $headers) =
677 $this->fetchWebFileHeaders($watermarkImage, $extraHeaders);
678 if (!$successfullyCopied) {
679 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
680 "Unable to find the watermark image at url: $watermarkImage - $response"),NULL,NULL);
683 /* Download the watermark image to a local file */
684 $tmpDir = $gallery->getConfig('data.gallery.tmp');
685 $watermark = $platform->tempnam($tmpDir, 'wmk_img_');
686 $watermark.= "." . $watermarkExt;
687 list ($successfullyCopied, $response, $headers) =
688 GalleryCoreApi::fetchWebFile($watermarkImage, $watermark, $extraHeaders);
689 if (!$successfullyCopied) {
690 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
691 "Unable to copy watermark image from url: $watermarkImage - $response"),null,null);
694 $tmpDir = $gallery->getConfig('data.gallery.tmp');
695 $watermark = $platform->tempnam($tmpDir, 'wmk_img_');
696 $watermark.= "." . $watermarkExt;
697 if(!$platform->copy($watermarkImage, $watermark)) {
698 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
699 "Unable to copy watermark image from path: $watermarkImage"),null,null);
703 /* See if there is a toolkit installed that can perform a composite operation */
704 list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'composite');
706 return array($ret->wrap(__FILE__, __LINE__,
707 "Unable to locate a toolkit module to perform the 'composite' watermark operation"), null);
710 /* Make sure we can access the toolkit found */
711 if (!isset($toolkit)) {
712 return array(GalleryStatus::error(ERROR_PERMISSION_DENIED, __FILE__, __LINE__,
713 "Unable to access the toolkit module to perform the 'composite' watermark operation"), null);
716 /* Get the image dimensions of the thumbnail */
717 $image_data = @getimagesize($newTmpFile);
719 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
720 "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
722 $thumbnailWidth = $image_data[0];
723 $thumbnailHeight = $image_data[1];
725 /* Get the image dimensions of the watermark */
726 $image_data = @getimagesize($watermark);
728 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
729 "Unable to retrieve watermark dimensions for: $tmpFile"),null,null);
731 $watermarkWidth = $image_data[0];
732 $watermarkHeight = $image_data[1];
734 /* Obtain the mimeType of the watermark */
735 list ($ret, $watermarkMimeType) = GalleryCoreApi::getMimeType($watermark);
737 /* Remove the gallery base path from the watermark image path */
738 /* This has to be done to satisfy the argument requirement for the toolkit operation */
739 $dataDir = $gallery->getConfig('data.gallery.base');
740 $dataDir=preg_replace("/\//","\\/",$dataDir);
741 if(preg_match("/$dataDir(.*)/", $watermark, $matches)) {
742 $watermark = $matches[1];
745 /* General debug output */
746 if(!strcmp($debugOutput,"true")) {
747 print "<h2>Watermark Operation</h2>";
748 print "watermarkImage: $watermarkImage <br>";
749 print "watermarkTmpImage: $watermark <br>";
750 print "watermarkMimeType: $watermarkMimeType <br>";
751 print "watermarkWidth: $watermarkWidth <br>";
752 print "watermarkHeight: $watermarkHeight <br>";
753 print "watermarkedWidth: $thumbnailWidth <br>";
754 print "watermarkedHeight: $thumbnailHeight <br>";
757 /* Apply the watermark image to the thumbnail */
758 $tmpFile = $platform->tempnam($tmpDir, 'wmk_');
759 list ($ret, $mimeType) = $toolkit->performOperation(
760 $mimeType, 'composite', $newTmpFile, $tmpFile,
761 array($watermark, $watermarkMimeType,
762 $watermarkWidth, $watermarkHeight,
763 $watermarkAlignment, 0, 0));
765 /* Check the return code of the composite operation */
767 return array($ret->wrap(__FILE__, __LINE__,
768 "Unable to apply watermark to the video thumbnail image"), null);
771 if(!strcmp($debugOutput,"true")) {
772 print "watermarked Image: $tmpFile <br>";
776 /* Update the path of our thumbnail to point to the new watermarked thumbnail instead */
777 $newTmpFile = $tmpFile;
781 /* Make the gallery2 call to add this item to the album */
782 list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($newTmpFile,
791 return array($ret, null, null);
794 $status['addedFiles'][] = array('fileName' => $url,
795 'id' => $newItem->getId(),
796 'warnings' => array());
798 if(!strcmp($debugOutput,"true")) {
799 print "<br><br><h2>Video Successfully Added to your Gallery Album</h2><br><br><hr>";
803 /* Keep the tmpfiles around if we are in debug mode. Otherwise, remove them. */
804 if(!strcmp($debugOutput,"false")) {
805 @$platform->unlink($tmpFile);
806 @$platform->unlink($newTmpFile);
811 return array(null, $error, $status);
815 * A simple function to resolve the value of a parameter from
816 * the default or override value if it exists, or set it
817 * to the default passed as an argument.
819 function getParameter($params, $name, $default="") {
820 if(isset($params['override'][$name])) {
821 /* print "override $name = ".$params['override'][$name]."<br>"; */
822 return($params['override'][$name]);
823 } else if(isset($params['default'][$name])) {
824 /* print "default $name = ".$params['default'][$name] ."<br>"; */
825 return($params['default'][$name]);
827 /* print "$name = $default <br>"; */
833 * A simple function to get the headers only (no body) for a given URL
834 * This was taken from GalleryCoreApi::requestWebPage
836 function fetchWebFileHeaders($url, $requestHeaders=array()) {
839 $requestMethod='GET';
841 /* Convert illegal characters */
842 $url = str_replace(' ', '%20', $url);
844 /* Unescape ampersands, since if the URL comes from form input it will be escaped */
845 $url = str_replace('&', '&', $url);
847 $platform =& $gallery->getPlatform();
849 $urlComponents = parse_url($url);
850 if (empty($urlComponents['port'])) {
851 $urlComponents['port'] = 80;
853 if (empty($urlComponents['path'])) {
854 $urlComponents['path'] = '/';
857 $handle = @$platform->fsockopen(
858 $urlComponents['host'], $urlComponents['port'], $errno, $errstr, 5);
859 if (empty($handle)) {
860 $gallery->debug("Error $errno: '$errstr' requesting $url");
861 return array(null, null, null);
864 $requestUri = $urlComponents['path'];
865 if (!empty($urlComponents['query'])) {
866 $requestUri .= '?' . $urlComponents['query'];
868 $headerLines = array('Host: ' . $urlComponents['host']);
869 foreach ($requestHeaders as $key => $value) {
870 $headerLines[] = $key . ': ' . $value;
873 $success = $platform->fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s",
876 implode("\r\n", $headerLines),
879 /* Zero bytes written or false was returned */
881 "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''));
882 return array(null, null, null);
884 $platform->fflush($handle);
888 * Read the status line. fgets stops after newlines. The first line is the protocol
889 * version followed by a numeric status code and its associated textual phrase.
891 $responseStatus = trim($platform->fgets($handle, 4096));
892 if (empty($responseStatus)) {
893 $gallery->debug('Empty http response code, maybe timeout');
894 return array(null, null, null);
897 /* Read the headers */
898 $responseHeaders = array();
899 while (!$platform->feof($handle)) {
900 $line = trim($platform->fgets($handle, 4096));
905 /* Normalize the line endings */
906 $line = str_replace("\r", '', $line);
908 list ($key, $value) = explode(':', $line, 2);
909 if (isset($responseHeaders[$key])) {
910 if (!is_array($responseHeaders[$key])) {
911 $responseHeaders[$key] = array($responseHeaders[$key]);
913 $responseHeaders[$key][] = trim($value);
915 $responseHeaders[$key] = trim($value);
918 $platform->fclose($handle);
920 if(preg_match("/Not found/i", $responseStatus)) {
924 //print "success: $success <br>responseStatus: $responseStatus <br>responseHeaders: $responseHeaders <br>";
926 return array($success, $responseStatus, $responseHeaders);
930 * @see ItemAdd:loadTemplate
932 function loadTemplate(&$template, &$form, $item) {
935 if ($form['formName'] != 'ItemAddEmbedVideo') {
936 /* First time around, load the form with item data */
937 $form['webPage'] = '';
938 $form['formName'] = 'ItemAddEmbedVideo';
941 $session =& $gallery->getSession();
943 $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
946 'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
947 'modules_embedvideo');
951 * @see ItemAddPlugin::getTitle
953 function getTitle() {
954 list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
956 return array($ret, null);
959 return array(null, $module->translate('Embed Video'));