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