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