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