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