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;
74 /* Find out what value our parameters should have by looking to see if they
75 * are defined in our overrides section or default section. If they are not
76 * defined in either of these 2 places, pass in a default value to set them to
78 $debugOutput = $this->getParameter($ItemAddEmbedVideo, 'debugOutput', "false");
79 $useInternalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'useInternalFlvPlayer', "true");
80 $youtubeDevId = $this->getParameter($ItemAddEmbedVideo, 'youtubeDevId', "");
81 $youtubeShowRelated = $this->getParameter($ItemAddEmbedVideo, 'youtubeShowRelated', "false");
82 $width = $this->getParameter($ItemAddEmbedVideo, 'width', "320");
83 $height = $this->getParameter($ItemAddEmbedVideo, 'height', "240");
84 $externalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayer', "");
85 $externalFlvPlayerVars = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayerVars', "");
86 $flvThumbnail = $this->getParameter($ItemAddEmbedVideo, 'flvThumbnail', "");
87 $useRemoteSize = $this->getParameter($ItemAddEmbedVideo, 'useRemoteSize', "false");
88 $autoStart = $this->getParameter($ItemAddEmbedVideo, 'autoStart', "false");
90 /* Print our stored/set Parameters */
91 if(!strcmp($debugOutput,"true")) {
93 print "<h2>Variable Parameters</h2>";
94 print "debugOutput=$debugOutput<br>";
95 print "useInternalFlvPlayer=$useInternalFlvPlayer<br>";
96 print "youtubeDevId=$youtubeDevId<br>";
97 print "youtubeShowRelated=$youtubeShowRelated<br>";
98 print "width=$width<br>";
99 print "height=$height<br>";
100 print "externalFlvPlayer=$externalFlvPlayer<br>";
101 print "externalFlvPlayerVars=$externalFlvPlayerVars<br>";
102 print "flvThumbnail=$flvThumbnail<br>";
103 print "useRemoteSize=$useRemoteSize<br>";
104 print "autoStart=$autoStart<br>";
108 /* Store other string constants we'll use later */
111 $youtubeUrlPattern="youtube.com";
112 $youtubeApiUrl="http://www.youtube.com/api2_rest";
113 /* We can't extract the server size from youtube */
115 $youtubeHeight="350";
118 $googleUrlPattern="video.google.com";
119 $googlePlayer="http://video.google.com/googleplayer.swf";
120 /* We can't extract the server size from google video */
125 $yahooUrlPattern="video.yahoo.com";
126 $yahooThumbnailUrl="http://thmg01.video.search.yahoo.com/image/";
129 $metacafeUrlPattern="metacafe.com";
130 $metacafeThumbnailUrl="http://www.metacafe.com/thumb/";
132 /* Gallery2 specific paths and variables */
133 $urlGenerator =& $gallery->getUrlGenerator();
134 $gallery2_url = $urlGenerator->getCurrentUrlDir();
135 $gallery2_flv_thumbnail = "modules/thumbnail/images/G2video.jpg";
136 $gallery2_flv_player = "modules/flashvideo/lib/G2flv.swf";
138 /* Store the passed URL in a shorter local variable */
139 $url = $form['webPage']['URL'];
142 *****************************
143 * Embed a Youtube Video
144 *****************************
146 if(preg_match("/$youtubeUrlPattern/",$url)) {
148 /* Make sure we can find a video_id in the URL */
149 if(preg_match("/watch\?v=(.*)/",$url,$matches)) {
150 $video_id = $matches[1];
152 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
153 "Unable to extract video id from url: $url"),null,null);
156 /* Make sure we have a valid youtube developer id */
157 $dev_id = $youtubeDevId;
158 if(!preg_match("/\w+/",$dev_id)) {
159 return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
160 "Invalid/missing YouTube developer ID: $dev_id"),null,null);
163 /* Youtube api feed */
164 $feed = $youtubeApiUrl.'?method=youtube.videos.get_details';
165 $feed.= "&dev_id=$dev_id&video_id=$video_id";
167 /* Get the youtube xml feed as a string data source */
168 list ($successfullyCopied, $xml, $response, $headers) =
169 GalleryCoreApi::fetchWebPage($feed, $extraHeaders);
170 if (!$successfullyCopied) {
171 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
172 "Unable to get video information at url: $url - $response"),null,null);
175 if(preg_match("/This video is private/",$xml)) {
176 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
177 "Unable to retrieve video information from youtube.".
178 "You cannot embed a private youtube video: $url"),null,null);
181 if(!strcmp($debugOutput,"true")) {
182 print "<h2>Youtube XML Dump</h2>";
187 /* Extract certain information from the xml feed */
188 preg_match_all("/\<title\>(.+?)\<\/title\>/smi",$xml, $title);
189 preg_match_all("/\<description\>(.+?)\<\/description\>/smi",$xml, $description);
190 preg_match_all("/\<thumbnail_url\>(.+?)\<\/thumbnail_url\>/smi",$xml, $thumbnail);
193 array_shift($thumbnail);
194 array_shift($description);
196 /* Replace html characters. More can be added but this seems to work */
197 for($i=0;$i<count($description[0]);$i++){
198 $description[0][$i] = preg_replace("/</","<",$description[0][$i]);
199 $description[0][$i] = html_entity_decode($description[0][$i],ENT_QUOTES);
202 /* Store the information found in some local variables */
203 $title = $title[0][0];
204 $summary = $description[0][0];
205 $thumbnail = $thumbnail[0][0];
207 /* Determine what our width and height should be based on our useRemoteSize parameter */
208 if(!strcmp($useRemoteSize,"true")) {
209 $width = $youtubeWidth;
210 $height = $youtubeHeight;
213 /* Determine if the video should autoplay or not based on the autoStart parameter */
215 if(!strcmp($autoStart,"true")) {
216 $autoStartStr="&autoplay=1";
219 /* Determine if the video should show related videos or not based on the youtubeShowRelated parameter */
220 $youtubeShowRelatedStr="";
221 if(!strcmp($youtubeShowRelated,"false")) {
222 $youtubeShowRelatedStr="&rel=0";
225 /* Format the description to hold a reference to the embedded video */
226 $description = '<object width="'.$width.'" height="'.$height.'">';
227 $description.= '<param name="movie" ';
228 $description.= 'value="http://www.youtube.com/v/'.$video_id.'"></param>';
229 $description.= '<param name="wmode" value="transparent"></param>';
230 $description.= '<embed src="http://www.youtube.com/v/';
231 $description.= $video_id.$autoStartStr.$youtubeShowRelatedStr;
232 $description.= '" type="application/x-shockwave-flash" wmode="transparent" ';
233 $description.= 'width="'.$width.'" height="'.$height.'"></embed></object>';
234 $description.= "<br>$summary";
237 **********************************
238 * Embed a Google Video
239 **********************************
241 } else if(preg_match("/$googleUrlPattern/",$url)) {
243 /* Make sure we can extract a docID */
244 if(preg_match("/docid=(.*)/",$url,$matches)) {
245 $doc_id = $matches[1];
247 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
248 "Unable to extract doc id from url: $url"),null,null);
251 /* Grab the contents of the webpage used to display the video on video.google.com */
252 list ($successfullyCopied, $contents, $response, $headers) =
253 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
254 if (!$successfullyCopied) {
255 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
256 "Unable to get video information at url: $url - $response"),NULL,NULL);
259 /* Extract the summary from the webpage contents */
260 //print "contents: $contents <br>";
261 preg_match('/<meta name="description" content="(.+?)\. \w+ \d+, \d+.*">/i',
262 $contents, $matches);
263 $summary=$matches[1];
265 /* Extract the title from the webpage contents */
267 if(preg_match('/<title>(.+?)\s+- Google Video<\/title>/i', $contents, $matches)) {
269 } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
273 /* Extract the thumbnail URL from the webpage contents */
274 preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
275 $contents, $matches);
276 $thumbnail=$matches[1];
277 $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
279 /* Determine what our width and height should be based on our useRemoteSize parameter */
280 if(!strcmp($useRemoteSize,"true")) {
281 $width = $googleWidth;
282 $height = $googleHeight;
285 /* Determine if the video should autoplay or not based on the autoStart parameter */
287 if(!strcmp($autoStart,"true")) {
288 $autoStartStr="&autoplay=1";
291 /* Format the description to hold a reference to the embedded video */
292 $description = '<embed ';
293 $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
294 $description.= 'type="application/x-shockwave-flash" ';
295 $description.= 'src="'.$googlePlayer.'?docId='.$doc_id.$autoStartStr.'" flashvars=""> ';
296 $description.= '</embed>';
297 $description.= "<br>$summary";
300 **********************************
301 * Embed a Yahoo Video
302 **********************************
303 * TODO: The autoStart parameter doesn't work with the yahoo video player
305 } else if(preg_match("/$yahooUrlPattern/",$url)) {
307 /* Make sure we can extract a vidID */
308 if(preg_match("/vid=(.*)/",$url,$matches)) {
309 $vid_id = $matches[1];
311 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
312 "Unable to extract vid id from url: $url"),null,null);
315 /* Grab the contents of the webpage used to display the video on video.google.com */
316 list ($successfullyCopied, $contents, $response, $headers) =
317 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
318 if (!$successfullyCopied) {
319 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
320 "Unable to get video information at url: $url - $response"),NULL,NULL);
323 /* Extract the summary from the webpage contents */
324 preg_match('/Description:<\/em><p>(.+?)<\/p>/', $contents, $matches);
325 $summary=$matches[1];
327 /* Extract the title from the webpage contents */
329 if(preg_match('/<title>(.+?)\s+- Yahoo! Video<\/title>/i', $contents, $matches)) {
331 } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
335 /* Build the thumbnail URL from the vid_id */
336 $thumbnail=$yahooThumbnailUrl.$vid_id."_01";
338 /* Format the description to hold a reference to the embedded video */
339 preg_match('/(<embed src.+?<\/embed>)/', $contents, $matches);
340 $description=$matches[1];
341 if(!strcmp($useRemoteSize,"false")) {
342 $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
343 $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
345 $description.= "<br>$summary";
348 **********************************
349 * Embed a MetaCafe Video
350 **********************************
352 } else if(preg_match("/$metacafeUrlPattern/",$url)) {
354 /* Make sure we can extract a itemID */
355 if(preg_match("/\/watch\/(.+?)\/(.+?)/",$url,$matches)) {
356 $item_id = $matches[1];
358 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
359 "Unable to extract item id from url: $url"),null,null);
362 /* Grab the contents of the webpage used to display the video on video.google.com */
363 list ($successfullyCopied, $contents, $response, $headers) =
364 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
365 if (!$successfullyCopied) {
366 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
367 "Unable to get video information at url: $url - $response"),NULL,NULL);
370 /* Extract the summary from the webpage contents */
371 preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
372 $summary=$matches[1];
374 /* Extract the title from the webpage contents */
375 preg_match('/<title>(.+?)<\/title>/i', $contents, $matches);
378 /* Build the thumbnail URL from the item_id */
379 $thumbnail=$metacafeThumbnailUrl.$item_id.".jpg";
381 /* Format the description to hold a reference to the embedded video */
382 preg_match('/(embed src.+?\/embed)/', $contents, $matches);
383 $description="<".$matches[1];
384 $description=preg_replace("/"/","'",$description);
385 if(!strcmp($useRemoteSize,"false")) {
386 $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
387 $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
389 if(!strcmp($autoStart,"true")) {
390 $description=preg_replace("/\.swf/",".swf?playerVars=autoPlay=yes",$description);
392 $description.= "</embed>";
393 $description.= "<br>$summary";
397 **********************************
398 * Embed a remote .swf file
399 **********************************
401 } else if(preg_match("/.*\/(.+?)\.swf/i",$url,$matches)) {
403 /* Set the title and summary to the name of the file */
404 $title = $matches[1];
405 $summary = $matches[1];
408 * Set the thumbnail to some generic jpg image,
409 * since we can't extract it from the remote swf file.
410 * If no parameter is set, set it to a default value.
412 if(preg_match("/\w+/", $flvThumbnail)) {
413 $thumbnail = $flvThumbnail;
415 $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
419 * Check to make sure the URL to the remote swf file is valid
420 * (That the file exists at the URL given)
422 list ($successfullyCopied, $response, $headers) =
423 $this->fetchWebFileHeaders($url, $extraHeaders);
424 if (!$successfullyCopied) {
425 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
426 "Unable to find the video at url: $url - $response"),NULL,NULL);
430 * Format the description to hold a reference to the embedded video
433 /* Format the description to hold a reference to the embedded video */
434 $description ='<embed src="'.$url.'">';
437 **********************************
438 * Embed a remote .flv file
439 **********************************
441 } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
443 /* Set the title and summary to the name of the file */
444 $title = $matches[1];
445 $summary = $matches[1];
448 * Set the thumbnail to some generic jpg image,
449 * since we can't extract it from the remote flv file.
450 * If no parameter is set, set it to a default value.
452 if(preg_match("/\w+/", $flvThumbnail)) {
453 $thumbnail = $flvThumbnail;
455 $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
459 * Check to make sure the URL to the remote flv file is valid
460 * (That the file exists at the URL given)
462 list ($successfullyCopied, $response, $headers) =
463 $this->fetchWebFileHeaders($url, $extraHeaders);
464 if (!$successfullyCopied) {
465 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
466 "Unable to find the video at url: $url - $response"),NULL,NULL);
470 * Format the description to hold a reference to the embedded video
471 * This reference will be embedded using the G2 internal player,
472 * or an external player if provided by the user.
474 if(!strcmp($useInternalFlvPlayer,"false")) {
477 * The user has indicated they want to use an external flv player
478 * Make sure one is defined!
480 if(!preg_match("/\w+/",$externalFlvPlayer)) {
481 return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
482 "Invalid/missing external player parameter"),null,null);
485 /* Format the description to hold a reference to the embedded video */
486 $description ='<embed src="'.$externalFlvPlayer.'" ';
487 $description.= 'width="'.$width.'" height="'.$height.'" ';
488 $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
489 $description.= 'type="application/x-shockwave-flash" ';
490 $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
491 $description.= 'flashvars="file='.$url;
492 $description.= '&fullscreenpage='.$thumbnail;
493 $description.= '&linktarget=_Blank&image='.$thumbnail;
495 if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
496 /* Format the flashvars for the internal G2 flv player */
497 $description.= '&showdigits=true&autostart='.$autoStart.'&showfsbutton=true&';
498 $description.= '&repeat=false&lightcolor=0x9999FF';
499 $description.= '&backcolor=0x888888&frontcolor=0x000000"';
501 /* Format the flashvars for the external G2 flv player */
502 $description.= '&'.$externalFlvPlayerVars;
504 $description.= ' /> </p>';
506 /* Internal FLV player */
508 /* Format the description to hold a reference to the embedded video */
509 $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
510 $description = '<script type="text/javascript">'."\n";
511 $description.= '// <![CDATA['."\n";
512 $description.= 'function divResize(id, nw, nh) {'."\n";
513 $description.= 'var obj = document.getElementById(id);'."\n";
514 $description.= 'obj.style.width = nw + "px";'."\n";
515 $description.= 'obj.style.height = nh + "px";'."\n";
516 $description.= '}'."\n";
517 $description.= '// ]]>'."\n";
518 $description.= '</script>'."\n";
519 $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
520 $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
521 $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
522 $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
523 $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
524 $description.= '<param name="FlashVars" value="flvUrl='.$url;
525 $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
526 $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
527 $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
528 $description.= '<param name="quality" value="high"/>';
529 $description.= '<param name="scale" value="noscale"/>';
530 $description.= '<param name="salign" value="lt"/>';
531 $description.= '<param name="wmode" value="transparent"/>';
532 $description.= '<param name="allowScriptAccess" value="always"/>';
533 $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
534 $description.= 'flashvars="flvUrl='.$url;
535 $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
536 $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
537 $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
538 $description.= 'type="application/x-shockwave-flash" ';
539 $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
540 $description.= 'wmode="transparent" allowScriptAccess="always" ';
541 $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
542 $description.= '</object></div>';
546 **********************************
547 * Unsupported URL to embed
548 **********************************
551 return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
552 "Unable to embed video from: $url"),null,null);
557 **********************************
558 * Add the video to Gallery
559 **********************************
562 /* Get a local tmp file to save the thumbnail URL to */
563 $tmpDir = $gallery->getConfig('data.gallery.tmp');
564 $tmpFile = $platform->tempnam($tmpDir, 'add');
567 /* Fetch the thumbnail and save it to a local file */
568 list ($successfullyCopied, $response, $headers) =
569 GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
570 if (!$successfullyCopied) {
571 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
572 "Unable to copy thumbnail from url: $thumbnail - $response"),null,null);
575 /* Obtain the mimeType of the thumbnail */
576 list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
578 /* Set the filename for the item we want to add */
580 $fileName = preg_replace("/\s+/","_",$fileName);
581 $fileName = preg_replace("/'/","",$fileName);
582 $fileName = preg_replace("/\"/","",$fileName);
583 $fileName = preg_replace("/&#\d+;/","",$fileName);
585 /* General debug output */
586 if(!strcmp($debugOutput,"true")) {
587 print "<h2>Item Parameters</h2>";
588 print "url: $url <br>";
589 print "title: $title <br>";
590 print "thumbnailUrl: <img src=\"".$thumbnail."\">\n</a>".$summary."</p>";
591 print "description: <p>$description</p>";
592 print "thumbnail: $tmpFile <br>";
593 print "mimeType: $mimeType <br>";
594 print "fileName: $fileName <br>";
595 print "width: $width <br>";
596 print "height: $height <br>";
600 /* Resize the thumbnail image to the size indicated by our album */
602 list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'resize');
604 $debugString.="Checking to see if a toolkit that can resize images was found. <br>";
605 if (isset($toolkit)) {
606 $newTmpFile = $platform->tempnam($tmpDir, 'add');
607 $newTmpFile.= ".jpg";
608 $thumbnailSize = 150;
609 list ($ret, $preferences) =
610 GalleryCoreApi::fetchDerivativePreferencesForItem($item->getId());
612 foreach ($preferences as $preference) {
613 if (preg_match('/thumbnail\|(\d+)/',
614 $preference['derivativeOperations'], $matches)) {
615 $thumbnailSize = $matches[1];
616 $debugString.="Found thumbnail size in album preferences: $thumbnailSize <br>";
622 // Obtain the width and height of the original thumbnail, finding out it's ratio,
623 // and using that ratio when determining the width of the video below.
624 // Example: youtube: 130x97 google: 160x120 metacafe: 90x76 yahoo: 100x70
625 // Set the thumbnailHeight to the current thumbnailSize
626 // Set the thumbnailWidth to the appropriate size based on the thumbnailHeight * ratio
627 $image_data = @getimagesize($tmpFile);
629 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
630 "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
632 $ratio = $image_data[0] / $image_data[1];
633 $debugString.="Using ratio from original thumbnail of $ratio. ";
634 $thumbnailHeight=$thumbnailSize;
635 $thumbnailWidth=round($thumbnailHeight * $ratio);
636 $debugString.="Resizing thumbnail image to $thumbnailWidth x $thumbnailHeight: $tmpFile -> $newTmpFile <br>";
637 $toolkit->performOperation($mimeType, 'resize', $tmpFile, $newTmpFile,
638 array($thumbnailWidth,$thumbnailHeight));
641 if(!strcmp($debugOutput,"true")) {
642 print "<h2>Thumbnail Resize</h2>";
643 print "$debugString";
647 /* Make the gallery2 call to add this item to the album */
648 list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($newTmpFile,
657 return array($ret, null, null);
660 $status['addedFiles'][] = array('fileName' => $url,
661 'id' => $newItem->getId(),
662 'warnings' => array());
664 if(!strcmp($debugOutput,"true")) {
665 print "<br><br><h2>Video Successfully Added to your Gallery Album</h2><br><br><hr>";
669 /* Keep the tmpfiles around if we are in debug mode. Otherwise, remove them. */
670 if(!strcmp($debugOutput,"false")) {
671 @$platform->unlink($tmpFile);
672 @$platform->unlink($newTmpFile);
677 return array(null, $error, $status);
681 * A simple function to resolve the value of a parameter from
682 * the default or override value if it exists, or set it
683 * to the default passed as an argument.
685 function getParameter($params, $name, $default="") {
686 if(isset($params['override'][$name])) {
687 /* print "override $name = ".$params['override'][$name]."<br>"; */
688 return($params['override'][$name]);
689 } else if(isset($params['default'][$name])) {
690 /* print "default $name = ".$params['default'][$name] ."<br>"; */
691 return($params['default'][$name]);
693 /* print "$name = $default <br>"; */
699 * A simple function to get the headers only (no body) for a given URL
700 * This was taken from GalleryCoreApi::requestWebPage
702 function fetchWebFileHeaders($url, $requestHeaders=array()) {
705 $requestMethod='GET';
707 /* Convert illegal characters */
708 $url = str_replace(' ', '%20', $url);
710 /* Unescape ampersands, since if the URL comes from form input it will be escaped */
711 $url = str_replace('&', '&', $url);
713 $platform =& $gallery->getPlatform();
715 $urlComponents = parse_url($url);
716 if (empty($urlComponents['port'])) {
717 $urlComponents['port'] = 80;
719 if (empty($urlComponents['path'])) {
720 $urlComponents['path'] = '/';
723 $handle = @$platform->fsockopen(
724 $urlComponents['host'], $urlComponents['port'], $errno, $errstr, 5);
725 if (empty($handle)) {
726 $gallery->debug("Error $errno: '$errstr' requesting $url");
727 return array(null, null, null);
730 $requestUri = $urlComponents['path'];
731 if (!empty($urlComponents['query'])) {
732 $requestUri .= '?' . $urlComponents['query'];
734 $headerLines = array('Host: ' . $urlComponents['host']);
735 foreach ($requestHeaders as $key => $value) {
736 $headerLines[] = $key . ': ' . $value;
739 $success = $platform->fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s",
742 implode("\r\n", $headerLines),
745 /* Zero bytes written or false was returned */
747 "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''));
748 return array(null, null, null);
750 $platform->fflush($handle);
754 * Read the status line. fgets stops after newlines. The first line is the protocol
755 * version followed by a numeric status code and its associated textual phrase.
757 $responseStatus = trim($platform->fgets($handle, 4096));
758 if (empty($responseStatus)) {
759 $gallery->debug('Empty http response code, maybe timeout');
760 return array(null, null, null);
763 /* Read the headers */
764 $responseHeaders = array();
765 while (!$platform->feof($handle)) {
766 $line = trim($platform->fgets($handle, 4096));
771 /* Normalize the line endings */
772 $line = str_replace("\r", '', $line);
774 list ($key, $value) = explode(':', $line, 2);
775 if (isset($responseHeaders[$key])) {
776 if (!is_array($responseHeaders[$key])) {
777 $responseHeaders[$key] = array($responseHeaders[$key]);
779 $responseHeaders[$key][] = trim($value);
781 $responseHeaders[$key] = trim($value);
784 $platform->fclose($handle);
786 if(preg_match("/Not found/i", $responseStatus)) {
790 //print "success: $success <br>responseStatus: $responseStatus <br>responseHeaders: $responseHeaders <br>";
792 return array($success, $responseStatus, $responseHeaders);
796 * @see ItemAdd:loadTemplate
798 function loadTemplate(&$template, &$form, $item) {
801 if ($form['formName'] != 'ItemAddEmbedVideo') {
802 /* First time around, load the form with item data */
803 $form['webPage'] = '';
804 $form['formName'] = 'ItemAddEmbedVideo';
807 $session =& $gallery->getSession();
809 $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
812 'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
813 'modules_embedvideo');
817 * @see ItemAddPlugin::getTitle
819 function getTitle() {
820 list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
822 return array($ret, null);
825 return array(null, $module->translate('Embed Video'));