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