Added debug messages around rescaling the thumbnail
[embedvideo/.git] / ItemAddEmbedVideo.inc
1 <?php
2 /*
3  * Gallery - a web based photo album viewer and editor
4  * Copyright (C) 2000-2007 Bharat Mediratta
5  *
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.
10  *
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.
15  *
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.
19  */
20
21 GalleryCoreApi::requireOnce('modules/gd/classes/GdToolkitHelper.class');
22
23
24 /**
25  * This plugin will handle the addition of embedded video objects
26  * @package embedVideo
27  * @subpackage UserInterface
28  * @author Alan Pippin <apippin@pippins.net>
29  * @version $Revision: 1.1 $
30  */
31 class ItemAddEmbedVideo extends ItemAddPlugin {
32   
33   /**
34    * @see ItemAddPlugin::handleRequest
35    */
36  function handleRequest($form, &$item) {
37    global $gallery;
38     
39    $status = $error = array();
40    
41    if (isset($form['action']['addEmbedVideoPage'])) {
42      
43        $platform =& $gallery->getPlatform();
44
45        if (empty($extraHeaders)) {
46            $extraHeaders = array('Referer' => str_replace('&amp;', '&', $url));
47        }
48
49        if(isset($form['webPage']['URL'])) {
50          
51            /* Load any stored/set Parameters */
52            list ($ret, $params) =
53              GalleryCoreApi::fetchAllPluginParameters('module', 'embedvideo');
54            if ($ret) {
55                return array($ret, null, null);
56            }
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>"; */
65                    }
66                }
67            }
68            
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
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
77             */
78            $debugOutput = $this->getParameter($ItemAddEmbedVideo, 'debugOutput', "false");
79            $useInternalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'useInternalFlvPlayer', "true");
80            $youtubeDevId = $this->getParameter($ItemAddEmbedVideo, 'youtubeDevId', "");
81            $width = $this->getParameter($ItemAddEmbedVideo, 'width', "320");
82            $height = $this->getParameter($ItemAddEmbedVideo, 'height', "240");
83            $externalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayer', "");
84            $externalFlvPlayerVars = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayerVars', "");
85            $flvThumbnail = $this->getParameter($ItemAddEmbedVideo, 'flvThumbnail', "");
86            $useRemoteSize = $this->getParameter($ItemAddEmbedVideo, 'useRemoteSize', "false");
87            $autoStart = $this->getParameter($ItemAddEmbedVideo, 'autoStart', "false");
88            
89            /* Store other string constants we'll use later */
90           
91            /* youtube */
92            $youtubeUrlPattern="youtube.com";
93            $youtubeApiUrl="http://www.youtube.com/api2_rest";
94            $youtubeWidth="425";
95            $youtubeHeight="350";
96
97            /* google */
98            $googleUrlPattern="video.google.com";
99            $googlePlayer="http://video.google.com/googleplayer.swf";
100            $googleWidth="400";
101            $googleHeight="326";
102            
103            /* yahoo */
104            $yahooUrlPattern="video.yahoo.com";
105            $yahooThumbnailUrl="http://thmg01.video.search.yahoo.com/image/";
106            
107            /* metacafe */
108            $metacafeUrlPattern="metacafe.com";
109            $metacafeThumbnailUrl="http://www.metacafe.com/thumb/";
110            
111            /* Gallery2 specific paths and variables */
112            $urlGenerator =& $gallery->getUrlGenerator();
113            $gallery2_url = $urlGenerator->getCurrentUrlDir();
114            $gallery2_flv_thumbnail = "modules/thumbnail/images/G2video.jpg";
115            $gallery2_flv_player = "modules/flashvideo/lib/G2flv.swf";
116            
117            /* Store the passed URL in a shorter local variable */
118            $url = $form['webPage']['URL'];
119
120            /*
121             *****************************
122             * Embed a Youtube Video
123             *****************************
124             */
125            if(preg_match("/$youtubeUrlPattern/",$url)) {
126
127                /* Make sure we can find a video_id in the URL */
128                if(preg_match("/watch\?v=(.*)/",$url,$matches)) {
129                    $video_id = $matches[1];
130                } else {
131                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
132                                 "Unable to extract video id from url: $url"),null,null);
133                }
134                
135                /* Make sure we have a valid youtube developer id */
136                $dev_id = $youtubeDevId;
137                if(!preg_match("/\w+/",$dev_id)) {
138                    return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
139                                 "Invalid/missing YouTube developer ID: $dev_id"),null,null);
140                }
141                
142                /* Youtube api feed */
143                $feed = $youtubeApiUrl.'?method=youtube.videos.get_details';
144                $feed.= "&dev_id=$dev_id&video_id=$video_id";
145                
146                /* Get the youtube xml feed as a string data source */
147                list ($successfullyCopied, $xml, $response, $headers) =
148                  GalleryCoreApi::fetchWebPage($feed, $extraHeaders);
149                if (!$successfullyCopied) {
150                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
151                                 "Unable to get video information at url: $url - $response"),null,null);
152                }
153
154                if(!strcmp($debugOutput,"true")) {
155                  print "$xml";
156                }
157                
158                /* Extract certain information from the xml feed */
159                preg_match_all("/\<title\>(.+?)\<\/title\>/smi",$xml, $title);
160                preg_match_all("/\<description\>(.+?)\<\/description\>/smi",$xml, $description);
161                preg_match_all("/\<thumbnail_url\>(.+?)\<\/thumbnail_url\>/smi",$xml, $thumbnail);
162                
163                array_shift($title);
164                array_shift($thumbnail);
165                array_shift($description);
166           
167                /* Replace html characters. More can be added but this seems to work */
168                for($i=0;$i<count($description[0]);$i++){          
169                    $description[0][$i] = preg_replace("/&#60;/","<",$description[0][$i]);
170                    $description[0][$i] = html_entity_decode($description[0][$i],ENT_QUOTES);      
171                }
172
173                /* Store the information found in some local variables */
174                $title = $title[0][0];
175                $summary = $description[0][0];
176                $thumbnail = $thumbnail[0][0];
177
178                /* Determine what our width and height should be based on our useRemoteSize parameter */
179                if(!strcmp($useRemoteSize,"true")) {
180                  $width = $youtubeWidth;
181                  $height = $youtubeHeight;
182                }
183                
184                /* Determine if the video should autoplay or not based on the autoStart parameter */
185                $autoStartStr="";
186                if(!strcmp($autoStart,"true")) {
187                  $autoStartStr="&autoplay=1";
188                }
189                
190                /* Format the description to hold a reference to the embedded video */
191                $description = '<object width="'.$width.'" height="'.$height.'">';
192                $description.= '<param name="movie" ';
193                $description.= 'value="http://www.youtube.com/v/'.$video_id.'"></param>';
194                $description.= '<param name="wmode" value="transparent"></param>';
195                $description.= '<embed src="http://www.youtube.com/v/'.$video_id.$autoStartStr.'" ';
196                $description.= 'type="application/x-shockwave-flash" wmode="transparent" ';
197                $description.= 'width="'.$width.'" height="'.$height.'"></embed></object>';
198                $description.= "<br>$summary";
199
200            /*
201             **********************************
202             * Embed a Google Video
203             **********************************
204             */
205            } else if(preg_match("/$googleUrlPattern/",$url)) {
206
207                /* Make sure we can extract a docID */
208                if(preg_match("/docid=(.*)/",$url,$matches)) {
209                    $doc_id = $matches[1];
210                } else {
211                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
212                                 "Unable to extract doc id from url: $url"),null,null);
213                }
214
215                /* Grab the contents of the webpage used to display the video on video.google.com */
216                list ($successfullyCopied, $contents, $response, $headers) =
217                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
218                if (!$successfullyCopied) {
219                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
220                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
221                }
222
223                /* Extract the summary from the webpage contents */
224                preg_match('/<meta content="(.+?)\. \w+ \d+, \d+.*" name="description">/i',
225                           $contents, $matches);
226                $summary=$matches[1];
227
228                /* Extract the title from the webpage contents */
229                $title="Unknown";
230                if(preg_match('/<title>(.+?)\s+- Google Video<\/title>/i', $contents, $matches)) {
231                  $title=$matches[1];
232                } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
233                  $title=$matches[1];
234                }
235
236                /* Extract the thumbnail URL from the webpage contents */
237                preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
238                           $contents, $matches);
239                $thumbnail=$matches[1];
240                $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
241
242                /* Determine what our width and height should be based on our useRemoteSize parameter */
243                if(!strcmp($useRemoteSize,"true")) {
244                  $width = $googleWidth;
245                  $height = $googleHeight;
246                }
247
248                /* Determine if the video should autoplay or not based on the autoStart parameter */
249                $autoStartStr="";
250                if(!strcmp($autoStart,"true")) {
251                  $autoStartStr="&autoplay=1";
252                }
253
254                /* Format the description to hold a reference to the embedded video */
255                $description = '<embed FlashVars=';
256                $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
257                $description.= 'type="application/x-shockwave-flash" ';
258                $description.= 'src="'.$googlePlayer.'?docId='.$doc_id.$autoStartStr.'"> ';
259                $description.= '</embed>';
260                $description.= "<br>$summary";
261
262            /*
263             **********************************
264             * Embed a Yahoo Video
265             **********************************
266             * TODO: The autoStart parameter doesn't work with the yahoo video player
267             */
268            } else if(preg_match("/$yahooUrlPattern/",$url)) {
269
270                /* Make sure we can extract a vidID */
271                if(preg_match("/vid=(.*)/",$url,$matches)) {
272                    $vid_id = $matches[1];
273                } else {
274                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
275                                 "Unable to extract vid id from url: $url"),null,null);
276                }
277
278                /* Grab the contents of the webpage used to display the video on video.google.com */
279                list ($successfullyCopied, $contents, $response, $headers) =
280                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
281                if (!$successfullyCopied) {
282                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
283                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
284                }
285
286                /* Extract the summary from the webpage contents */
287                preg_match('/Description:<\/em><p>(.+?)<\/p>/', $contents, $matches);
288                $summary=$matches[1];
289
290                /* Extract the title from the webpage contents */
291                $title="Unknown";
292                if(preg_match('/<title>(.+?)\s+- Yahoo! Video<\/title>/i', $contents, $matches)) {
293                  $title=$matches[1];
294                } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
295                  $title=$matches[1];
296                }
297
298                /* Build the thumbnail URL from the vid_id */
299                $thumbnail=$yahooThumbnailUrl.$vid_id."_01";
300
301                /* Format the description to hold a reference to the embedded video */
302                preg_match('/(<embed src.+?<\/embed>)/', $contents, $matches);
303                $description=$matches[1];
304                if(!strcmp($useRemoteSize,"false")) {
305                  $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
306                  $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
307                }
308                $description.= "<br>$summary";
309
310            /*
311             **********************************
312             * Embed a MetaCafe Video
313             **********************************
314             */
315            } else if(preg_match("/$metacafeUrlPattern/",$url)) {
316
317                /* Make sure we can extract a itemID */
318                if(preg_match("/\/watch\/(.+?)\/(.+?)/",$url,$matches)) {
319                    $item_id = $matches[1];
320                } else {
321                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
322                                 "Unable to extract item id from url: $url"),null,null);
323                }
324
325                /* Grab the contents of the webpage used to display the video on video.google.com */
326                list ($successfullyCopied, $contents, $response, $headers) =
327                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
328                if (!$successfullyCopied) {
329                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
330                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
331                }
332
333                /* Extract the summary from the webpage contents */
334                preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
335                $summary=$matches[1];
336
337                /* Extract the title from the webpage contents */
338                preg_match('/<title>(.+?)<\/title>/i', $contents, $matches);
339                $title=$matches[1];
340                
341                /* Build the thumbnail URL from the item_id */
342                $thumbnail=$metacafeThumbnailUrl.$item_id.".jpg";
343
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                $description=preg_replace("/&quot;/","'",$description);
348                if(!strcmp($useRemoteSize,"false")) {
349                  $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
350                  $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
351                }
352                if(!strcmp($autoStart,"true")) {
353                  $description=preg_replace("/\.swf/",".swf?playerVars=autoPlay=yes",$description);
354                }
355                $description.= "</embed>";
356                $description.= "<br>$summary";
357          
358            /*
359             **********************************
360             * Embed a remote .flv file
361             **********************************
362             */
363            } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
364
365                /* Set the title and summary to the name of the file */
366                $title = $matches[1];
367                $summary = $matches[1];
368                
369                /*
370                 * Set the thumbnail to some generic jpg image,
371                 * since we can't extract it from the remote flv file.
372                 * If no parameter is set, set it to a default value.
373                 */
374                if(preg_match("/\w+/", $flvThumbnail)) {
375                  $thumbnail = $flvThumbnail;
376                } else {
377                  $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
378                }
379
380                /*
381                 * Check to make sure the URL to the remote flv file is valid
382                 * (That the file exists at the URL given)
383                 */
384                list ($successfullyCopied, $response, $headers) =
385                  $this->fetchWebFileHeaders($url, $extraHeaders);
386                if (!$successfullyCopied) {
387                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
388                               "Unable to find the video at url: $url - $response"),NULL,NULL);
389                }
390                
391                /*
392                 * Format the description to hold a reference to the embedded video
393                 * This reference will be embedded using the G2 internal player,
394                 * or an external player if provided by the user.
395                 */
396                if(!strcmp($useInternalFlvPlayer,"false")) {
397
398                    /*
399                     * The user has indicated they want to use an external flv player
400                     * Make sure one is defined!
401                     */
402                    if(!preg_match("/\w+/",$externalFlvPlayer)) {
403                        return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
404                                    "Invalid/missing external player parameter"),null,null);
405                    }
406
407                    /* Format the description to hold a reference to the embedded video */
408                    $description ='<embed src="'.$externalFlvPlayer.'" ';
409                    $description.= 'width="'.$width.'" height="'.$height.'" ';
410                    $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
411                    $description.= 'type="application/x-shockwave-flash" ';
412                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
413                    $description.= 'flashvars="file='.$url;
414                    $description.= '&fullscreenpage='.$thumbnail;
415                    $description.= '&linktarget=_Blank&image='.$thumbnail;
416
417                    if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
418                        /* Format the flashvars for the internal G2 flv player */
419                        $description.= '&showdigits=true&autostart='.$autoStart.'&showfsbutton=true&';
420                        $description.= '&repeat=false&lightcolor=0x9999FF';
421                        $description.= '&backcolor=0x888888&frontcolor=0x000000"';
422                    } else {
423                        /* Format the flashvars for the external G2 flv player */
424                        $description.= '&'.$externalFlvPlayerVars;
425                    }
426                    $description.=  ' />&nbsp;</p>';
427                
428                /* Internal FLV player */
429                } else {
430                    /* Format the description to hold a reference to the embedded video */
431                    $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
432                    $description = '<script type="text/javascript">'."\n";
433                    $description.= '// <![CDATA['."\n";
434                    $description.= 'function divResize(id, nw, nh) {'."\n";
435                    $description.= 'var obj = document.getElementById(id);'."\n";
436                    $description.= 'obj.style.width = nw + "px";'."\n";
437                    $description.= 'obj.style.height = nh + "px";'."\n";
438                    $description.= '}'."\n";
439                    $description.= '// ]]>'."\n";
440                    $description.= '</script>'."\n";
441                    $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
442                    $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
443                    $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
444                    $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
445                    $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
446                    $description.= '<param name="FlashVars" value="flvUrl='.$url;
447                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
448                    $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
449                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
450                    $description.= '<param name="quality" value="high"/>';
451                    $description.= '<param name="scale" value="noscale"/>';
452                    $description.= '<param name="salign" value="lt"/>';
453                    $description.= '<param name="wmode" value="transparent"/>';
454                    $description.= '<param name="allowScriptAccess" value="always"/>';
455                    $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
456                    $description.= 'flashvars="flvUrl='.$url;
457                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
458                    $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
459                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
460                    $description.= 'type="application/x-shockwave-flash" ';
461                    $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
462                    $description.= 'wmode="transparent" allowScriptAccess="always" ';
463                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
464                    $description.= '</object></div>';
465                }
466                
467           /*
468            **********************************
469            * Unsupported URL to embed
470            **********************************
471            */   
472            } else {
473                return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
474                             "Unable to embed video from: $url"),null,null);
475            }
476            
477
478            /*
479            **********************************
480            * Add the video to Gallery
481            **********************************
482            */
483            
484            /* Get a local tmp file to save the thumbnail URL to */
485            $tmpDir = $gallery->getConfig('data.gallery.tmp');
486            $tmpFile = $platform->tempnam($tmpDir, 'add');
487            $tmpFile.= ".jpg";
488            
489            if(!strcmp($debugOutput,"true")) {
490                print "thumbnail: $thumbnail <br>";
491            }
492            
493            /* Fetch the thumbnail and save it to a local file */
494            list ($successfullyCopied, $response, $headers) =
495              GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
496            if (!$successfullyCopied) {
497                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
498                             "Unable to copy thumbnail from url: $url - $response"),null,null);
499            }
500            
501            /* Obtain the mimeType of the thumbnail */
502            list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
503            
504            /* Set the filename for the item we want to add */
505            $fileName = $title;
506            $fileName = preg_replace("/\s+/","_",$fileName);
507            $fileName = preg_replace("/'/","",$fileName);
508            $fileName = preg_replace("/\"/","",$fileName);
509            $fileName = preg_replace("/&#\d+;/","",$fileName);
510            
511            /* General debug output */
512            if(!strcmp($debugOutput,"true")) {
513                print "title: $title <br>";
514                print "<p><a href=\"".$title."\" target=\"_blank\">";
515                print "<img src=\"".$thumbnail."\">\n</a>".$summary."</p>";
516                print "<p>$description</p>";
517                print "thumbnail: $tmpFile <br>";
518                print "mimeType: $mimeType <br>";
519                print "fileName: $fileName <br>";
520                print "<br><br><b>Video Successfully Added to your Gallery Album</b><br><br>";
521            }
522
523            /* Resize the thumbnail image to the size indicated by our album */
524            $debugString="";
525            list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'resize');
526            if (!$ret) {
527                $debugString.="Checking to see if a toolkit that can resize images was found. <br>";
528                if (isset($toolkit)) {
529                    $newTmpFile = $platform->tempnam($tmpDir, 'add');
530                    $newTmpFile.= ".jpg";
531                    $thumbnailSize = 150;
532                    list ($ret, $preferences) =
533                      GalleryCoreApi::fetchDerivativePreferencesForItem($item->getId());
534                    if(!$ret) {
535                        foreach ($preferences as $preference) {
536                          if (preg_match('/thumbnail\|(\d+)/',
537                                         $preference['derivativeOperations'], $matches)) {
538                              $thumbnailSize = $matches[1];
539                              $debugString.="Found thumbnail size in album preferences: $thumbnailSize <br>";
540                              break;
541                          }
542                        }
543                    }
544                    $debugString.="Resizing thumbnail image to $thumbnailSize: $tmpFile -> $newTmpFile <br>";
545                    $toolkit->performOperation($mimeType, 'resize', $tmpFile, $newTmpFile,
546                                               array($thumbnailSize,$thumbnailSize));
547                }
548            }
549            if(!strcmp($debugOutput,"true")) {
550                print "$debugString";
551            }
552            
553            /* Make the gallery2 call to add this item to the album */
554            list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($newTmpFile,
555                                                                   $fileName,
556                                                                   $title,
557                                                                   $summary,
558                                                                   $description,
559                                                                   $mimeType,
560                                                                   $item->getId());
561            
562            if ($ret) {
563                return array($ret, null, null);
564            }
565            
566            $status['addedFiles'][] = array('fileName' => $url,
567                                            'id' => $newItem->getId(),
568                                            'warnings' => array());
569        }
570        
571        /* Keep the tmpfiles around if we are in debug mode. Otherwise, remove them. */
572        if(!strcmp($debugOutput,"false")) {
573          @$platform->unlink($tmpFile);
574          @$platform->unlink($newTmpFile);
575        }
576        
577    }
578    
579    return array(null, $error, $status);
580  }
581
582  /**
583   * A simple function to resolve the value of a parameter from
584   * the default or override value if it exists, or set it
585   * to the default passed as an argument.
586   */
587  function getParameter($params, $name, $default="") {
588    if(isset($params['override'][$name])) {
589      /* print "override $name = ".$params['override'][$name]."<br>"; */
590      return($params['override'][$name]);
591    } else if(isset($params['default'][$name])) {
592      /* print "default $name = ".$params['default'][$name] ."<br>"; */
593      return($params['default'][$name]);
594    } else {
595      /* print "$name = $default <br>"; */
596      return($default);
597    }
598  }
599
600  /**
601   * A simple function to get the headers only (no body) for a given URL
602   * This was taken from GalleryCoreApi::requestWebPage
603   */
604  function fetchWebFileHeaders($url, $requestHeaders=array()) {
605      global $gallery;
606      
607      $requestMethod='GET';
608
609      /* Convert illegal characters */
610      $url = str_replace(' ', '%20', $url);
611      
612      /* Unescape ampersands, since if the URL comes from form input it will be escaped */
613      $url = str_replace('&amp;', '&', $url);
614
615      $platform =& $gallery->getPlatform();
616      
617      $urlComponents = parse_url($url);
618      if (empty($urlComponents['port'])) {
619          $urlComponents['port'] = 80;
620      }
621      if (empty($urlComponents['path'])) {
622          $urlComponents['path'] = '/';
623      }
624
625      $handle = @$platform->fsockopen(
626                                      $urlComponents['host'], $urlComponents['port'], $errno, $errstr, 5);
627      if (empty($handle)) {
628          $gallery->debug("Error $errno: '$errstr' requesting $url");
629          return array(null, null, null);
630      }
631      
632      $requestUri = $urlComponents['path'];
633      if (!empty($urlComponents['query'])) {
634          $requestUri .= '?' . $urlComponents['query'];
635      }
636      $headerLines = array('Host: ' . $urlComponents['host']);
637      foreach ($requestHeaders as $key => $value) {
638          $headerLines[] = $key . ': ' . $value;
639      }
640      
641      $success = $platform->fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s",
642                                                    $requestMethod,
643                                                    $requestUri,
644                                                    implode("\r\n", $headerLines),
645                                                    $requestBody));
646      if (!$success) {
647          /* Zero bytes written or false was returned */
648          $gallery->debug(
649                          "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''));
650          return array(null, null, null);
651      }
652      $platform->fflush($handle);
653      
654      
655      /*
656       * Read the status line.  fgets stops after newlines.  The first line is the protocol
657       * version followed by a numeric status code and its associated textual phrase.
658       */
659      $responseStatus = trim($platform->fgets($handle, 4096));
660      if (empty($responseStatus)) {
661          $gallery->debug('Empty http response code, maybe timeout');
662          return array(null, null, null);
663      }
664      
665      /* Read the headers */
666      $responseHeaders = array();
667      while (!$platform->feof($handle)) {
668          $line = trim($platform->fgets($handle, 4096));
669          if (empty($line)) {
670              break;
671          }
672        
673          /* Normalize the line endings */
674          $line = str_replace("\r", '', $line);
675          
676          list ($key, $value) = explode(':', $line, 2);
677          if (isset($responseHeaders[$key])) {
678              if (!is_array($responseHeaders[$key])) {
679                $responseHeaders[$key] = array($responseHeaders[$key]);
680              }
681              $responseHeaders[$key][] = trim($value);
682          } else {
683              $responseHeaders[$key] = trim($value);
684          }
685      }
686      $platform->fclose($handle);
687
688      if(preg_match("/Not found/i", $responseStatus)) {
689          $success = 0;
690      }
691
692      //print "success: $success <br>responseStatus: $responseStatus <br>responseHeaders: $responseHeaders <br>";
693      
694      return array($success, $responseStatus, $responseHeaders);
695  }
696  
697  /**
698   * @see ItemAdd:loadTemplate
699   */
700  function loadTemplate(&$template, &$form, $item) {
701     global $gallery;
702     
703     if ($form['formName'] != 'ItemAddEmbedVideo') {
704         /* First time around, load the form with item data */
705         $form['webPage'] = '';
706         $form['formName'] = 'ItemAddEmbedVideo';
707     }
708     
709     $session =& $gallery->getSession();
710     
711     $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
712     
713     return array(null,
714                  'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
715                  'modules_embedvideo');
716  }
717  
718  /**
719   * @see ItemAddPlugin::getTitle
720   */
721  function getTitle() {
722     list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
723     if ($ret) {
724         return array($ret, null);
725     }
726     
727     return array(null, $module->translate('Embed Video'));
728  }
729  
730 }       
731 ?>