Added support for new youtube API: GDATA. Deprecated youtubeDevId
[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, $url;
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;
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            $youtubeShowRelated = $this->getParameter($ItemAddEmbedVideo, 'youtubeShowRelated', "false");
82            $width = $this->getParameter($ItemAddEmbedVideo, 'width', "320");
83            $height = $this->getParameter($ItemAddEmbedVideo, 'height', "240");
84            $externalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayer', "");
85            $externalFlvPlayerVars = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayerVars', "");
86            $flvThumbnail = $this->getParameter($ItemAddEmbedVideo, 'flvThumbnail', "");
87            $useRemoteSize = $this->getParameter($ItemAddEmbedVideo, 'useRemoteSize', "false");
88            $autoStart = $this->getParameter($ItemAddEmbedVideo, 'autoStart', "false");
89            $watermarkImage = $this->getParameter($ItemAddEmbedVideo, 'watermarkImage', "");
90            $watermarkVideos = $this->getParameter($ItemAddEmbedVideo, 'watermarkVideos', "false");
91            $watermarkAlignment = $this->getParameter($ItemAddEmbedVideo, 'watermarkAlignment', "left");
92            $wordwrapSummary = $this->getParameter($ItemAddEmbedVideo, 'wordwrapSummary', "0");
93            $wordwrapDescription = $this->getParameter($ItemAddEmbedVideo, 'wordwrapDescription', "0");
94
95            /* Print our stored/set Parameters */
96            if(!strcmp($debugOutput,"true")) {
97              print "\n<hr>";
98              print "<h2>Variable Parameters</h2>\n";
99              print "debugOutput=$debugOutput<br>\n";
100              print "useInternalFlvPlayer=$useInternalFlvPlayer<br>\n";
101              print "youtubeShowRelated=$youtubeShowRelated<br>\n";
102              print "width=$width<br>\n";
103              print "height=$height<br>\n";
104              print "externalFlvPlayer=$externalFlvPlayer<br>\n";
105              print "externalFlvPlayerVars=$externalFlvPlayerVars<br>\n";
106              print "flvThumbnail=$flvThumbnail<br>\n";
107              print "useRemoteSize=$useRemoteSize<br>\n";
108              print "autoStart=$autoStart<br>\n";
109              print "watermarkVideos=$watermarkVideos<br>\n";
110              print "watermarkImage=$watermarkImage<br>\n";
111              print "watermarkAlignment=$watermarkAlignment<br>\n";
112              print "wordwrapSummary=$wordwrapSummary<br>\n";
113              print "wordwrapDescription=$wordwrapDescription<br>\n";
114              print "<hr>\n";
115            }
116
117            /* Store other string constants we'll use later */
118           
119            /* youtube */
120            $youtubeUrlPattern="youtube.com";
121            $youtubeApiUrl="http://gdata.youtube.com/feeds/api/";
122            $youtubeThumbnailUrl="http://img.youtube.com/vi/";
123            /* We can't extract the server size from youtube */
124            $youtubeWidth="425";
125            $youtubeHeight="350";
126
127            /* google */
128            $googleUrlPattern="video.google.com";
129            $googlePlayer="http://video.google.com/googleplayer.swf";
130            /* We can't extract the server size from google video */
131            $googleWidth="400";
132            $googleHeight="326";
133            
134            /* yahoo */
135            $yahooUrlPattern="video.yahoo.com";
136            $yahooThumbnailUrl="http://thmg01.video.search.yahoo.com/image/";
137            
138            /* metacafe */
139            $metacafeUrlPattern="metacafe.com";
140            $metacafeThumbnailUrl="http://www.metacafe.com/thumb/";
141
142            /* revver */
143            $revverUrlPattern="revver.com";
144            $revverThumbnailUrl="http://frame.revver.com/frame/120x90/";
145
146            /* dailymotion */
147            $dailymotionUrlPattern="dailymotion.com";
148            $dailymotionThumbnailUrl="http://www.dailymotion.com/thumbnail/160x120/video/";
149
150            /* divshare */
151            $divshareUrlPattern="divshare.com";
152            $divshareThumbnailUrl="http://www.divshare.com/direct/video_thumb/";
153
154            /* stickam */
155            $stickamUrlPattern="stickam.com";
156            $stickamThumbnailUrl="http://static.stickam.com/";
157
158            /* myspace */
159            $myspaceUrlPattern="vids.myspace.com";
160            $myspaceUrlPattern2="myspacetv.com";
161            $myspaceThumbnailUrl="http://mediaservices.myspace.com/services/rss.ashx?type=video&videoID=";
162
163            /* vimeo */
164            $vimeoUrlPattern="www.vimeo.com";
165            
166            /* Gallery2 specific paths and variables */
167            $urlGenerator =& $gallery->getUrlGenerator();
168            $gallery2_url = $urlGenerator->getCurrentUrlDir();
169            $gallery2_flv_thumbnail = "modules/embedvideo/images/G2video_thumbnail.jpg";
170            $gallery2_video_watermark = "modules/embedvideo/images/G2video_watermark1.png";
171            $gallery2_flv_player = "modules/flashvideo/lib/G2flv.swf";
172            
173            /* Store the passed URL in a shorter local variable */
174            $url = $form['webPage']['URL'];
175
176            /*
177             *****************************
178             * Embed a Youtube Video
179             *****************************
180             */
181            if(preg_match("/$youtubeUrlPattern/",$url)) {
182              
183                /* Make sure we can find a video_id in the URL */
184                $extra_params = "";
185                if(preg_match("/watch\?v=(.*?)(&\S+=\S+)/",$url,$matches)) {
186                    $video_id = $matches[1];
187                    $extra_params = $matches[2];
188                } else if (preg_match("/watch\?v=(.*)/",$url,$matches)) {
189                    $video_id = $matches[1];
190                } else {
191                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
192                                 "Unable to extract video id from url: $url"),null,null);
193                }
194
195                /* If extra params were given, handle them here */
196                if(strcmp($extra_params,"")) {
197                  /* Handle the HD format information */
198                  if(preg_match("/fmt=(\d+)/",$extra_params,$matches)) {
199                    $extra_params="&ap=%2526fmt%3D".$matches[1];
200                  }
201                }
202                        
203                /* Youtube api feed */
204                $feed = $youtubeApiUrl."videos/$video_id";
205
206                if(!strcmp($debugOutput,"true")) {
207                    print "\n<h2>Youtube URL Parsing Results</h2>";
208                    print "video_id: $video_id<br>";
209                    print "extra_embed_params: $extra_params<br>";
210                    print "gdata feed: $feed<br>";
211                    print "<hr>";
212                }
213
214                /* Get the youtube xml feed as a string data source */
215                list ($successfullyCopied, $xml, $response, $headers) =
216                  GalleryCoreApi::fetchWebPage($feed, $extraHeaders);
217                if (!$successfullyCopied) {
218                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
219                                                     "Unable to get video information at url: $url - $response"),null,null);
220                }
221                  
222                if(preg_match("/This video is private/",$xml)) {
223                  return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
224                                                     "Unable to retrieve video information from youtube.".
225                                                     "You cannot embed a private youtube video: $url"),null,null);
226                }
227                  
228                if(!strcmp($debugOutput,"true")) {
229                  print "\n<h2>Youtube XML Dump</h2>";
230                  print "$xml";
231                  print "<hr>";
232                }
233                  
234                /* Extract certain information from the xml feed */
235                preg_match_all("/\<media:title.+?\>(.+?)\<\/media:title\>/smi",$xml, $title);
236                preg_match_all("/\<media:description.+?\>(.+?)\<\/media:description\>/smi",$xml, $description);
237                preg_match_all("/\<media:thumbnail url='(.+?)'/smi",$xml, $thumbnail);
238                  
239                array_shift($title);
240                array_shift($thumbnail);
241                array_shift($description);
242
243                /* Replace html characters. More can be added but this seems to work */
244                for($i=0;$i<count($description[0]);$i++){          
245                  $description[0][$i] = preg_replace("/&#60;/","<",$description[0][$i]);
246                  $description[0][$i] = html_entity_decode($description[0][$i],ENT_QUOTES);        
247                }
248                  
249                /* Store the information found in some local variables */
250                $title = $title[0][0];
251                $summary = $description[0][0];
252                  
253                /* The last thumbnail match we make will always be the highest resolution */
254                $thumbnail = $thumbnail[0][sizeof($thumbnail[0])-1];
255
256                if(!strcmp($debugOutput,"true")) {
257                  print "title: $title<br>";
258                  print "summary: $summary<br>";
259                  print "thumbnail: $thumbnail<br>";
260                }
261                  
262                /* Determine what our width and height should be based on our useRemoteSize parameter */
263                if(!strcmp($useRemoteSize,"true")) {
264                  $width = $youtubeWidth;
265                  $height = $youtubeHeight;
266                }
267                  
268                /* Determine if the video should autoplay or not based on the autoStart parameter */
269                $autoStartStr="";
270                if(!strcmp($autoStart,"true")) {
271                  $autoStartStr="&autoplay=1";
272                }
273                  
274                /* Determine if the video should show related videos or not based on the youtubeShowRelated parameter */
275                $youtubeShowRelatedStr="";
276                if(!strcmp($youtubeShowRelated,"false")) {
277                  $youtubeShowRelatedStr="&rel=0";
278                }
279
280                /* Format the description to hold a reference to the embedded video */
281                $description = '<object width="'.$width.'" height="'.$height.'">';
282                $description.= '<param name="movie" ';
283                $description.= 'value="http://www.youtube.com/v/'.$video_id.$extra_params.'"></param>';
284                $description.= '<param name="wmode" value="transparent"></param>';
285                $description.= '<embed src="http://www.youtube.com/v/';
286                $description.= $video_id.$extra_params.$autoStartStr.$youtubeShowRelatedStr;
287                $description.= '" type="application/x-shockwave-flash" wmode="transparent" ';
288                $description.= 'width="'.$width.'" height="'.$height.'"></embed></object>';
289
290            /*
291             **********************************
292             * Embed a Google Video
293             **********************************
294             */
295            } else if(preg_match("/$googleUrlPattern/",$url)) {
296
297                /* Make sure we can extract a docID */
298                if(preg_match("/docid=(.*)/",$url,$matches)) {
299                    $doc_id = $matches[1];
300                } else {
301                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
302                                 "Unable to extract doc id from url: $url"),null,null);
303                }
304
305                /* Grab the contents of the webpage used to display the video on video.google.com */
306                list ($successfullyCopied, $contents, $response, $headers) =
307                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
308                if (!$successfullyCopied) {
309                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
310                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
311                }
312
313                /* Extract the summary from the webpage contents */
314                //print "contents: $contents <br>";
315                preg_match('/<meta name="description" content="(.+?)\. \w+ \d+, \d+.*">/i',
316                           $contents, $matches);
317                $summary=$matches[1];
318
319                /* Extract the title from the webpage contents */
320                $title="Unknown";
321                if(preg_match('/<title>(.+?)\s+- Google Video<\/title>/i', $contents, $matches)) {
322                  $title=$matches[1];
323                } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
324                  $title=$matches[1];
325                }
326
327                /* Extract the thumbnail URL from the webpage contents */
328                preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
329                           $contents, $matches);
330                $thumbnail=$matches[1];
331                $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
332
333                /* Determine what our width and height should be based on our useRemoteSize parameter */
334                if(!strcmp($useRemoteSize,"true")) {
335                  $width = $googleWidth;
336                  $height = $googleHeight;
337                }
338
339                /* Determine if the video should autoplay or not based on the autoStart parameter */
340                $autoStartStr="";
341                if(!strcmp($autoStart,"true")) {
342                  $autoStartStr="&autoplay=1";
343                }
344
345                /* Format the description to hold a reference to the embedded video */
346                $description = '<embed ';
347                $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
348                $description.= 'type="application/x-shockwave-flash" ';
349                $description.= 'src="'.$googlePlayer.'?docId='.$doc_id.$autoStartStr.'" flashvars=""> ';
350                $description.= '</embed>';
351
352            /*
353             **********************************
354             * Embed a Yahoo Video
355             **********************************
356             * TODO: The autoStart parameter doesn't work with the yahoo video player
357             */
358            } else if(preg_match("/$yahooUrlPattern/",$url)) {
359
360                /* Make sure we can extract a vidID */
361                if(preg_match("/vid=(.*)/",$url,$matches)) {
362                    $vid_id = $matches[1];
363                } else {
364                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
365                                 "Unable to extract vid 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('/Description:<\/em><p>(.+?)<\/p>/', $contents, $matches);
378                $summary=$matches[1];
379
380                /* Extract the title from the webpage contents */
381                $title="Unknown";
382                if(preg_match('/<title>(.+?)\s+- Yahoo! Video<\/title>/i', $contents, $matches)) {
383                  $title=$matches[1];
384                } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
385                  $title=$matches[1];
386                }
387
388                /* Build the thumbnail URL from the vid_id */
389                $thumbnail=$yahooThumbnailUrl.$vid_id."_01";
390
391                /* Format the description to hold a reference to the embedded video */
392                if(preg_match('/(<embed src.+?<\/embed>)/', $contents, $matches)) { 
393                  $description=$matches[1];
394                  if(!strcmp($useRemoteSize,"false")) {
395                    $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
396                    $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
397                  }
398                } else {
399                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
400                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
401                }
402
403            /*
404             **********************************
405             * Embed a MetaCafe Video
406             **********************************
407             */
408            } else if(preg_match("/$metacafeUrlPattern/",$url)) {
409
410                /* Make sure we can extract a itemID */
411                if(preg_match("/\/watch\/(.+?)\/(.+?)/",$url,$matches)) {
412                    $item_id = $matches[1];
413                } else {
414                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
415                                 "Unable to extract item id from url: $url"),null,null);
416                }
417
418                /* Grab the contents of the webpage used to display the video on video.google.com */
419                list ($successfullyCopied, $contents, $response, $headers) =
420                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
421                if (!$successfullyCopied) {
422                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
423                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
424                }
425
426                /* Extract the summary from the webpage contents */
427                preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
428                $summary=$matches[1];
429
430                /* Extract the title from the webpage contents */
431                preg_match('/<title>(.+?)<\/title>/i', $contents, $matches);
432                $title=$matches[1];
433                
434                /* Build the thumbnail URL from the item_id */
435                $thumbnail=$metacafeThumbnailUrl.$item_id.".jpg";
436
437                /* Format the description to hold a reference to the embedded video */
438                if(preg_match('/(embed src.+?\/embed)/', $contents, $matches)) { 
439                  $description="<".$matches[1];
440                  $description=preg_replace("/&quot;/","'",$description);
441                  if(!strcmp($useRemoteSize,"false")) {
442                    $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
443                    $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
444                  }
445                  if(!strcmp($autoStart,"true")) {
446                    $description=preg_replace("/\.swf/",".swf?playerVars=autoPlay=yes",$description);
447                  }
448                  $description.= "</embed>";
449                } else {
450                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
451                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
452                }
453
454            /*
455             **********************************
456             * Embed a Revver Video
457             **********************************
458             * TODO: The autoStart parameter doesn't work with the yahoo video player
459             */
460            } else if(preg_match("/$revverUrlPattern/",$url)) {
461
462                /* Make sure we can extract a itemID */
463                if(preg_match("/\/watch\/(.+)/",$url,$matches)) {
464                    $item_id = $matches[1];
465                    $item_id=preg_replace("/\/$/","",$item_id);
466                } else {
467                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
468                                 "Unable to extract item id from url: $url"),null,null);
469                }
470
471                /* Grab the contents of the webpage used to display the video on video.google.com */
472                list ($successfullyCopied, $contents, $response, $headers) =
473                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
474                if (!$successfullyCopied) {
475                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
476                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
477                }
478
479                /* Extract the summary from the webpage contents */
480                if(preg_match('/"video_description">(.+?)<\/p>/i', $contents, $matches)) {
481                  $summary=$matches[1];
482                }
483                if(preg_match('/"video_description">(.+)/i', $contents, $matches)) {
484                  $summary=$matches[1];
485                }
486
487                /* Extract the title from the webpage contents */
488                preg_match('/digg_title = \'(.+?)\'/i', $contents, $matches);
489                $title=$matches[1];
490                
491                /* Build the thumbnail URL from the item_id */
492                $thumbnail=$revverThumbnailUrl.$item_id.".jpg";
493
494                /* Format the description to hold a reference to the embedded video */
495                if(preg_match('/<input class.+?(script src.+?\/script)/', $contents, $matches)) {
496                  $description="<".$matches[1];
497                  if(!strcmp($useRemoteSize,"false")) {
498                    $description=preg_replace("/width:\d+/","width:".$width,$description);
499                    $description=preg_replace("/height:\d+/","height:".$height,$description);
500                  }
501                  if(!strcmp($autoStart,"true")) {
502                    preg_match('/(height:\d+)/',$description,$matches);
503                    $height=$matches[1];
504                    $description=preg_replace("/$height/",$height.";autoplay:true",$description);
505                  }
506                  $description.= ">";
507                } else {
508                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
509                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
510                }
511             
512            /*
513             **********************************
514             * Embed a DailyMotion Video
515             **********************************
516             * TODO: The autoStart parameter doesn't work with the yahoo video player
517             */
518            } else if(preg_match("/$dailymotionUrlPattern/",$url)) {
519              
520                /* Make sure we can extract a itemID */
521                if(preg_match("/\/video\/(.+)/",$url,$matches)) {
522                    $item_id = $matches[1];
523                    $item_id=preg_replace("/\/$/","",$item_id);
524                } else {
525                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
526                                 "Unable to extract item id from url: $url"),null,null);
527                }
528
529                /* Grab the contents of the webpage used to display the video on video.google.com */
530                list ($successfullyCopied, $contents, $response, $headers) =
531                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
532                if (!$successfullyCopied) {
533                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
534                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
535                }
536
537                /* Extract the summary from the webpage contents */
538                preg_match('/<div class="description\s+foreground">(.+?)<\/div>/i', $contents, $matches);
539                $summary=$matches[1];
540
541                /* Extract the title from the webpage contents */
542                preg_match('/<meta name="title" content="Dailymotion : (.+?)" \/>/i', $contents, $matches);
543                $title=htmlentities($matches[1], ENT_QUOTES, "UTF-8");
544                
545                /* Build the thumbnail URL from the item_id */
546                $thumbnail=$dailymotionThumbnailUrl.$item_id;
547
548                /* Format the description to hold a reference to the embedded video */
549                if(preg_match('/<textarea id="video_player_embed_code_text".+?>(.+?)<\/textarea>/', $contents, $matches)) { 
550                  $description=$matches[1];
551                  $description=preg_replace("/&quot;/","'",$description);
552                  $description=preg_replace("/&lt;/","<",$description);
553                  $description=preg_replace("/&gt;/",">",$description);
554                  if(!strcmp($useRemoteSize,"false")) {
555                    $description=preg_replace("/width=\"\d+\"/","width=\"".$width."\"",$description);
556                    $description=preg_replace("/height=\"\d+\"/","height=\"".$height."\"",$description);
557                  }
558                } else {
559                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
560                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
561                }
562                
563            /*
564             **********************************
565             * Embed a DivShare Video
566             **********************************
567             */
568            } else if(preg_match("/$divshareUrlPattern/",$url)) {
569              
570                /* Make sure we can extract a itemID */
571                if(preg_match("/\/download\/(.+)/",$url,$matches)) {
572                    $item_id = $matches[1];
573                    $item_id=preg_replace("/\/$/","",$item_id);
574                } else {
575                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
576                                 "Unable to extract item id from url: $url"),null,null);
577                }
578
579                /* Grab the contents of the webpage used to display the video on video.google.com */
580                list ($successfullyCopied, $contents, $response, $headers) =
581                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
582                if (!$successfullyCopied) {
583                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
584                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
585                }
586
587                /* Extract the summary from the webpage contents */
588                //preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
589                //$summary=$matches[1];
590                // Right now, the description is a plug for divshare, nothing user specific about it
591                $summary="";
592
593                /* Extract the title from the webpage contents */
594                preg_match('/<title>(.+?) - Divshare<\/title>/i', $contents, $matches);
595                $title=$matches[1];
596                
597                /* Build the thumbnail URL from the item_id */
598                $thumbnail=$divshareThumbnailUrl.$item_id;
599
600                /* Format the description to hold a reference to the embedded video */
601                if(preg_match('/(<embed src.+?<\/embed>)/', $contents, $matches)) { 
602                  $description=$matches[1];
603                  if(!strcmp($useRemoteSize,"false")) {
604                    $description=preg_replace("/width=\"\d+\"/","width=\"".$width."\"",$description);
605                    $description=preg_replace("/height=\"\d+\"/","height=\"".$height."\"",$description);
606                  }
607                } else {
608                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
609                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
610                }
611
612            /*
613             **********************************
614             * Embed a StickAm Video
615             **********************************
616             */
617            } else if(preg_match("/$stickamUrlPattern/",$url)) {
618
619                /* Make sure we can extract a itemID */
620                if(preg_match("/mId=(.+)/",$url,$matches)) {
621                    $item_id = $matches[1];
622                    $item_id=preg_replace("/\/$/","",$item_id);
623                } else {
624                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
625                                 "Unable to extract item id from url: $url"),null,null);
626                }
627
628                /* Grab the contents of the webpage used to display the video on video.google.com */
629                $url=preg_replace("/&amp;/","&",$url);
630                list ($successfullyCopied, $contents, $response, $headers) =
631                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
632                if (!$successfullyCopied) {
633                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
634                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
635                }
636
637                /* Extract the summary from the webpage contents */
638                preg_match('/<meta name="description" content="(.+?)"\/>/i', $contents, $matches);
639                $summary=$matches[1];
640
641                /* Extract the title from the webpage contents */
642                preg_match('/<meta name="title" content="(.+?)">/i', $contents, $matches);
643                $title=$matches[1];             
644                
645                /* Build the thumbnail URL from the item_id */
646                if(preg_match('/movieName=(.+?)&userId=/i', $contents, $matches)) { 
647                  $thumbnail_url=$matches[1];
648                  $thumbnail_url=preg_replace("/%2F/","/",$thumbnail_url);
649                  $thumbnail=$stickamThumbnailUrl.$thumbnail_url.".jpg";
650                } else {
651                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
652                         "Unable to extract thumbnail from url: $url"),NULL,NULL);
653                }
654
655                /* Format the description to hold a reference to the embedded video */
656                if(preg_match('/input type.+?'.$item_id.'.+?value="(.+?)"/', $contents, $matches)) { 
657                  $description=$matches[1];
658                  $description=preg_replace("/&quot;/","'",$description);
659                  $description=preg_replace("/&lt;/","<",$description);
660                  $description=preg_replace("/&gt;/",">",$description);
661                  if(!strcmp($useRemoteSize,"false")) {
662                    $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
663                    $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
664                  }
665                } else {
666                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
667                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
668                }
669              
670            /*
671             **********************************
672             * Embed a Myspace Video
673             **********************************
674             */
675            } else if(preg_match("/($myspaceUrlPattern|$myspaceUrlPattern2)/",$url)) {
676
677                /* Make sure we can extract a itemID */
678                if(preg_match("/videoid=(.+)/i",$url,$matches)) {
679                    $video_id = $matches[1];
680                    $video_id=preg_replace("/\/$/","",$video_id);
681                } else {
682                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
683                                 "Unable to extract video id from url: $url"),null,null);
684                }
685
686                /* Grab the contents of the webpage used to display the video on video.google.com */
687                list ($successfullyCopied, $contents, $response, $headers) =
688                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
689                if (!$successfullyCopied) {
690                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
691                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
692                }
693
694                /* Extract the summary from the webpage contents */
695                preg_match('/class="description" id="vid_description">(.+?)<\/div>/i', $contents, $matches);
696                $summary=$matches[1];
697
698                /* Extract the title from the webpage contents */
699                preg_match('/<h1>(.+?)<\/h1>/i', $contents, $matches);
700                $title=$matches[1];             
701                
702                /* Build the thumbnail URL from the item_id */
703                $video_info_url=$myspaceThumbnailUrl.$video_id;
704                list ($successfullyCopied, $video_info, $response, $headers) =
705                  GalleryCoreApi::fetchWebPage($video_info_url, $extraHeaders);
706                if (!$successfullyCopied) {
707                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
708                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
709                }
710                if(preg_match('/thumbnail url="(.+?)"/',$video_info, $matches)) {
711                  $thumbnail = $matches[1];
712                } else {
713                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
714                         "Unable to extract thumbnail information from url: $url"),NULL,NULL);
715                }
716
717                /* Format the description to hold a reference to the embedded video */
718                if(preg_match('/(&lt;embed src.+?\/embed&gt;)/', $contents, $matches)) { 
719                  $description=$matches[1];
720                  $description=preg_replace("/&quot;/","'",$description);
721                  $description=preg_replace("/&lt;/","<",$description);
722                  $description=preg_replace("/&gt;/",">",$description);
723                  if(!strcmp($useRemoteSize,"false")) {
724                    $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
725                    $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
726                  }
727                } else {
728                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
729                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
730                }
731
732            /*
733             **********************************
734             * Embed a Vimeo Video
735             **********************************
736             */
737            } else if(preg_match("/$vimeoUrlPattern/",$url)) {
738
739                /* Make sure we can extract a docID */
740                if(preg_match("/$vimeoUrlPattern\/(.*)/",$url,$matches)) {
741                    $video_id = $matches[1];
742                } else {
743                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
744                                 "Unable to extract video id from url: $url"),null,null);
745                }
746
747                /* Grab the contents of the webpage used to display the video on video.google.com */
748                list ($successfullyCopied, $contents, $response, $headers) =
749                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
750                if (!$successfullyCopied) {
751                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
752                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
753                }
754
755                /* Extract the summary from the webpage contents */
756                preg_match('/<meta name="description" content="(.+?)"/i',
757                           $contents, $matches);
758                $summary=$matches[1];
759
760                /* Extract the title from the webpage contents */
761                preg_match('/<meta name="title" content="(.+?)"/i',
762                           $contents, $matches);
763                $title=$matches[1];
764
765                /* Extract the thumbnail URL from the webpage contents */
766                preg_match('/"videothumbnail" href="(.+?)"/i',
767                           $contents, $matches);
768                $thumbnail=$matches[1];
769
770                /* Determine what our width and height should be based on our useRemoteSize parameter */
771                if(!strcmp($useRemoteSize,"true")) {
772                  preg_match('/id="vimeo_player_'.$video_id.'".+?style="width:(\d+)px;height:(\d+)px;"/i',
773                             $contents, $matches);
774                  $width = $matches[1];
775                  $height = $matches[2];
776                }
777
778                /* Determine if the video should autoplay or not based on the autoStart parameter */
779                $autoStartStr="";
780                if(!strcmp($autoStart,"true")) {
781                  $autoStartStr="&amp;autoplay=1";
782                }
783
784                /* Format the description to hold a reference to the embedded video */
785                $description = '<object type="application/x-shockwave-flash" width="'.$width.'" height="'.$height.'"';
786                $description.= 'data="http://www.vimeo.com/moogaloop.swf?clip_id='.$video_id;
787                $description.= '&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1'.$autoStartStr;
788                $description.= '&amp;show_byline=1&amp;show_portrait=0&amp;color=">';
789                $description.= '<param name="quality" value="best" />';
790                $description.= '<param name="allowfullscreen" value="true" />';
791                $description.= '<param name="scale" value="showAll" />';
792                $description.= '<param name="movie" value="http://www.vimeo.com/moogaloop.swf?clip_id='.$video_id;
793                $description.= '&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1'.$autoStartStr;
794                $description.= '&amp;show_byline=1&amp;show_portrait=0&amp;color=" />';
795                $description.= '</object>';
796                
797            /*
798             **********************************
799             * Embed a remote .swf file
800             **********************************
801             */
802            } else if(preg_match("/.*\/(.+?)\.swf/i",$url,$matches)) {
803
804                /* Set the title and summary to the name of the file */
805                $title = $matches[1];
806                $summary = $matches[1];
807                
808                /*
809                 * Set the thumbnail to some generic jpg image,
810                 * since we can't extract it from the remote swf file.
811                 * If no parameter is set, set it to a default value.
812                 */
813                if(preg_match("/\w+/", $flvThumbnail)) {
814                  $thumbnail = $flvThumbnail;
815                } else {
816                  $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
817                }
818
819                /*
820                 * Check to make sure the URL to the remote swf file is valid
821                 * (That the file exists at the URL given)
822                 */
823                list ($successfullyCopied, $response, $headers) =
824                  $this->fetchWebFileHeaders($url, $extraHeaders);
825                if (!$successfullyCopied) {
826                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
827                               "Unable to find the video at url: $url - $response"),NULL,NULL);
828                }
829                
830                /*
831                 * Format the description to hold a reference to the embedded video
832                 */
833
834                /* Format the description to hold a reference to the embedded video */
835                $description ='<embed src="'.$url.'">';
836                
837            /*
838             **********************************
839             * Embed a remote .flv file
840             **********************************
841             */
842            } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
843
844                /* Set the title and summary to the name of the file */
845                $title = $matches[1];
846                $summary = $matches[1];
847                
848                /*
849                 * Set the thumbnail to some generic jpg image,
850                 * since we can't extract it from the remote flv file.
851                 * If no parameter is set, set it to a default value.
852                 */
853                if(preg_match("/\w+/", $flvThumbnail)) {
854                  $thumbnail = $flvThumbnail;
855                } else {
856                  $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
857                }
858
859                /*
860                 * Check to make sure the URL to the remote flv file is valid
861                 * (That the file exists at the URL given)
862                 */
863                list ($successfullyCopied, $response, $headers) =
864                  $this->fetchWebFileHeaders($url, $extraHeaders);
865                if (!$successfullyCopied) {
866                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
867                               "Unable to find the video at url: $url - $response"),NULL,NULL);
868                }
869                
870                /*
871                 * Format the description to hold a reference to the embedded video
872                 * This reference will be embedded using the G2 internal player,
873                 * or an external player if provided by the user.
874                 */
875                if(!strcmp($useInternalFlvPlayer,"false")) {
876
877                    /*
878                     * The user has indicated they want to use an external flv player
879                     * Make sure one is defined!
880                     */
881                    if(!preg_match("/\w+/",$externalFlvPlayer)) {
882                        return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
883                                    "Invalid/missing external player parameter"),null,null);
884                    }
885
886                    /* Format the description to hold a reference to the embedded video */
887                    $description ='<embed src="'.$externalFlvPlayer.'" ';
888                    $description.= 'width="'.$width.'" height="'.$height.'" ';
889                    $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
890                    $description.= 'type="application/x-shockwave-flash" ';
891                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
892                    $description.= 'flashvars="file='.$url;
893                    $description.= '&fullscreenpage='.$thumbnail;
894                    $description.= '&linktarget=_Blank&image='.$thumbnail;
895
896                    if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
897                        /* Format the flashvars for the internal G2 flv player */
898                        $description.= '&showdigits=true&autostart='.$autoStart.'&showfsbutton=true&';
899                        $description.= '&repeat=false&lightcolor=0x9999FF';
900                        $description.= '&backcolor=0x888888&frontcolor=0x000000"';
901                    } else {
902                        /* Format the flashvars for the external G2 flv player */
903                        $description.= '&'.$externalFlvPlayerVars;
904                    }
905                    $description.=  ' />&nbsp;</p>';
906                
907                /* Internal FLV player */
908                } else {
909                    /* Format the description to hold a reference to the embedded video */
910                    $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
911                    $description = '<script type="text/javascript">'."\n";
912                    $description.= '// <![CDATA['."\n";
913                    $description.= 'function divResize(id, nw, nh) {'."\n";
914                    $description.= 'var obj = document.getElementById(id);'."\n";
915                    $description.= 'obj.style.width = nw + "px";'."\n";
916                    $description.= 'obj.style.height = nh + "px";'."\n";
917                    $description.= '}'."\n";
918                    $description.= '// ]]>'."\n";
919                    $description.= '</script>'."\n";
920                    $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
921                    $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
922                    $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
923                    $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
924                    $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
925                    $description.= '<param name="FlashVars" value="flvUrl='.$url;
926                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
927                    $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
928                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
929                    $description.= '<param name="quality" value="high"/>';
930                    $description.= '<param name="scale" value="noscale"/>';
931                    $description.= '<param name="salign" value="lt"/>';
932                    $description.= '<param name="wmode" value="transparent"/>';
933                    $description.= '<param name="allowScriptAccess" value="always"/>';
934                    $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
935                    $description.= 'flashvars="flvUrl='.$url;
936                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
937                    $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
938                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
939                    $description.= 'type="application/x-shockwave-flash" ';
940                    $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
941                    $description.= 'wmode="transparent" allowScriptAccess="always" ';
942                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
943                    $description.= '</object></div>';
944                }
945                
946           /*
947            **********************************
948            * Unsupported URL to embed
949            **********************************
950            */   
951            } else {
952                return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
953                             "Unable to embed video from: $url"),null,null);
954            }
955            
956
957            /*
958            **********************************
959            * Add the video to Gallery
960            **********************************
961            */
962            
963            /* Get a local tmp file to save the thumbnail URL to */
964            $tmpDir = $gallery->getConfig('data.gallery.tmp');
965            $tmpFile = $platform->tempnam($tmpDir, 'add');
966            $tmpFile.= ".jpg";
967                    
968            /* Fetch the thumbnail and save it to a local file */
969            list ($successfullyCopied, $response, $headers) =
970              GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
971            if (!$successfullyCopied) {
972                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
973                             "Unable to copy thumbnail from url: $thumbnail - $response"),null,null);
974            }
975            
976            /* Obtain the mimeType of the thumbnail */
977            list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
978            
979            /* Set the filename for the item we want to add */
980            $fileName = $title;
981            $fileName = preg_replace("/\s+/","_",$fileName);
982            $fileName = preg_replace("/'/","",$fileName);
983            $fileName = preg_replace("/\"/","",$fileName);
984            $fileName = preg_replace("/&#\d+;/","",$fileName);
985
986            /* Wordwrap the description or summary as appropriate */
987            $description_summary = $summary;
988
989            if(strcmp($wordwrapSummary,"0")) {
990              $summary = wordwrap($summary,$wordwrapSummary,"<br>",FALSE);
991            }
992
993            if(strcmp($wordwrapDescription,"0")) {
994              $description_summary = wordwrap($description_summary,$wordwrapDescription,"<br>",FALSE);
995            }
996            
997            /* Tack on the summary to the end of the description */
998            $description.= "<br>$description_summary";
999            
1000            /* General debug output */
1001            if(!strcmp($debugOutput,"true")) {
1002                print "\n<h2>Item Parameters</h2>\n";
1003                print "url: $url <br>\n";
1004                print "title: $title <br>\n";
1005                print "thumbnailUrl: $thumbnail <br><img src=\"".$thumbnail."\"> <br>\n";
1006                print "summary: <p>$summary</p>\n";
1007                print "description: <p>$description</p>\n";
1008                print "thumbnail: $tmpFile <br>\n";
1009                print "mimeType: $mimeType <br>\n";
1010                print "fileName: $fileName <br>\n";
1011                print "width: $width <br>\n";
1012                print "height: $height <br>\n";
1013                print "<hr>";
1014            }
1015
1016            /* Resize the thumbnail image to the size indicated by our album */
1017            $debugString="";
1018            list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'resize');
1019            if (!$ret) {
1020                $debugString.="Checking to see if a toolkit that can resize images was found. <br>";
1021                if (isset($toolkit)) {
1022                    $newTmpFile = $platform->tempnam($tmpDir, 'add');
1023                    $newTmpFile.= ".jpg";
1024                    $thumbnailSize = 150;
1025                    list ($ret, $preferences) =
1026                      GalleryCoreApi::fetchDerivativePreferencesForItem($item->getId());
1027                    if(!$ret) {
1028                        foreach ($preferences as $preference) {
1029                          if (preg_match('/thumbnail\|(\d+)/',
1030                                         $preference['derivativeOperations'], $matches)) {
1031                              $thumbnailSize = $matches[1];
1032                              $debugString.="Found thumbnail size in album preferences: $thumbnailSize <br>";
1033                              break;
1034                          }
1035                        }
1036                    }
1037                    
1038                    // Obtain the width and height of the original thumbnail, finding out it's ratio,
1039                    // and using that ratio when determining the width of the video below.
1040                    // Example: youtube: 130x97 google: 160x120 metacafe: 90x76 yahoo: 100x70
1041                    // Set the thumbnailHeight to the current thumbnailSize
1042                    // Set the thumbnailWidth to the appropriate size based on the thumbnailHeight * ratio
1043                    $image_data = @getimagesize($tmpFile);
1044                    if(!$image_data) {
1045                      return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1046                             "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
1047                    }
1048                    $ratio = $image_data[0] / $image_data[1];
1049                    $debugString.="Using ratio from original thumbnail of $ratio. ";
1050                    $thumbnailHeight=$thumbnailSize;
1051                    $thumbnailWidth=round($thumbnailHeight * $ratio);
1052                    $debugString.="Resizing thumbnail image to $thumbnailWidth x $thumbnailHeight: $tmpFile -> $newTmpFile <br>";
1053                    $toolkit->performOperation($mimeType, 'resize', $tmpFile, $newTmpFile,
1054                                               array($thumbnailWidth,$thumbnailHeight));
1055                }
1056            }
1057            if(!strcmp($debugOutput,"true")) {
1058                print "\n<h2>Thumbnail Resize</h2>\n";
1059                print "$debugString\n";
1060                print "<hr>\n";
1061            }
1062
1063            /* Watermark the video thumbnail image if indicated by our parameter */
1064            if(!strcmp($watermarkVideos,"true")) {
1065              
1066              /*
1067               * If no watermarkImage parameter is set, set it to a default value.
1068               */
1069              if(preg_match("/\w+/", $watermarkImage)) {
1070                $watermarkImage = $watermarkImage;
1071              } else {
1072                $watermarkImage = $gallery2_url.$gallery2_video_watermark;
1073              }
1074              
1075              /* Get the watermark Image Extension */
1076              preg_match('/\.(...)$/', $watermarkImage, $matches);
1077              $watermarkExt=$matches[1];
1078              
1079              /*
1080               * Check to make sure the URL to the watermark image file is valid
1081               * (That the file exists at the URL given). Skip this part if it is a local path.
1082               */
1083              if(!preg_match("/^\//", $watermarkImage)) {
1084                list ($successfullyCopied, $response, $headers) =
1085                  $this->fetchWebFileHeaders($watermarkImage, $extraHeaders);
1086                if (!$successfullyCopied) {
1087                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
1088                         "Unable to find the watermark image at url: $watermarkImage - $response"),NULL,NULL);
1089                }
1090              
1091                /* Download the watermark image to a local file */
1092                $tmpDir = $gallery->getConfig('data.gallery.tmp');
1093                $watermark = $platform->tempnam($tmpDir, 'wmk_img_');
1094                $watermark.= "." . $watermarkExt;
1095                list ($successfullyCopied, $response, $headers) =
1096                  GalleryCoreApi::fetchWebFile($watermarkImage, $watermark, $extraHeaders);
1097                if (!$successfullyCopied) {
1098                  return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1099                         "Unable to copy watermark image from url: $watermarkImage - $response"),null,null);
1100                }
1101              } else {
1102                $tmpDir = $gallery->getConfig('data.gallery.tmp');
1103                $watermark = $platform->tempnam($tmpDir, 'wmk_img_');
1104                $watermark.= "." . $watermarkExt;
1105                if(!$platform->copy($watermarkImage, $watermark)) {
1106                  return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1107                         "Unable to copy watermark image from path: $watermarkImage"),null,null);
1108                }
1109              }
1110              
1111              /* See if there is a toolkit installed that can perform a composite operation */
1112              list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'composite');
1113              if ($ret) {
1114                return array($ret->wrap(__FILE__, __LINE__,
1115                       "Unable to locate a toolkit module to perform the 'composite' watermark operation"), null);
1116              }
1117
1118              /* Make sure we can access the toolkit found */
1119              if (!isset($toolkit)) {
1120                return array(GalleryStatus::error(ERROR_PERMISSION_DENIED, __FILE__, __LINE__,
1121                       "Unable to access the toolkit module to perform the 'composite' watermark operation"), null);
1122              }
1123              
1124              /* Get the image dimensions of the thumbnail */
1125              $image_data = @getimagesize($newTmpFile);
1126              if(!$image_data) {
1127                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1128                       "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
1129              }
1130              $thumbnailWidth = $image_data[0];
1131              $thumbnailHeight = $image_data[1];
1132
1133              /* Get the image dimensions of the watermark */
1134              $image_data = @getimagesize($watermark);
1135              if(!$image_data) {
1136                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1137                       "Unable to retrieve watermark dimensions for: $tmpFile"),null,null);
1138              }
1139              $watermarkWidth = $image_data[0];
1140              $watermarkHeight = $image_data[1];
1141
1142              /* Obtain the mimeType of the watermark */
1143              list ($ret, $watermarkMimeType) = GalleryCoreApi::getMimeType($watermark);
1144
1145              /* Remove the gallery base path from the watermark image path */
1146              /* This has to be done to satisfy the argument requirement for the toolkit operation */
1147              $dataDir = $gallery->getConfig('data.gallery.base');
1148              $dataDir=preg_replace("/\//","\\/",$dataDir);
1149              if(preg_match("/$dataDir(.*)/", $watermark, $matches)) { 
1150                $watermark = $matches[1];
1151              }
1152              
1153              /* General debug output */
1154              if(!strcmp($debugOutput,"true")) {
1155                print "\n<h2>Watermark Operation</h2>\n";
1156                print "watermarkImage: $watermarkImage <br>\n";
1157                print "watermarkTmpImage: $watermark <br>\n";
1158                print "watermarkMimeType: $watermarkMimeType <br>\n";
1159                print "watermarkWidth: $watermarkWidth <br>\n";
1160                print "watermarkHeight: $watermarkHeight <br>\n";
1161                print "watermarkedWidth: $thumbnailWidth <br>\n";
1162                print "watermarkedHeight: $thumbnailHeight <br>\n";
1163              }
1164
1165              /* Apply the watermark image to the thumbnail */
1166              $tmpFile = $platform->tempnam($tmpDir, 'wmk_');
1167              list ($ret, $mimeType) = $toolkit->performOperation(
1168                                                                  $mimeType, 'composite', $newTmpFile, $tmpFile,
1169                                                                  array($watermark, $watermarkMimeType,
1170                                                                        $watermarkWidth, $watermarkHeight,
1171                                                                        $watermarkAlignment, 0, 0));
1172              
1173              /* Check the return code of the composite operation */
1174              if ($ret) {
1175                return array($ret->wrap(__FILE__, __LINE__,
1176                                        "Unable to apply watermark to the video thumbnail image"), null);
1177              }
1178
1179              if(!strcmp($debugOutput,"true")) {
1180                print "\nwatermarked Image: $tmpFile <br>";
1181                print "<hr>";
1182              }
1183                        
1184              /* Update the path of our thumbnail to point to the new watermarked thumbnail instead */
1185              $newTmpFile = $tmpFile;
1186              
1187            }
1188            
1189            /* Make the gallery2 call to add this item to the album */
1190            list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($newTmpFile,
1191                                                                   $fileName,
1192                                                                   $title,
1193                                                                   $summary,
1194                                                                   $description,
1195                                                                   $mimeType,
1196                                                                   $item->getId());
1197            
1198            if ($ret) {
1199                return array($ret, null, null);
1200            }
1201            
1202            $status['addedFiles'][] = array('fileName' => $url,
1203                                            'id' => $newItem->getId(),
1204                                            'warnings' => array());
1205
1206            if(!strcmp($debugOutput,"true")) {
1207                print "\n<br><br><h2>Video Successfully Added to your Gallery Album</h2><br><br><hr>";
1208            }
1209        }
1210        
1211        /* Keep the tmpfiles around if we are in debug mode. Otherwise, remove them. */
1212        if(!strcmp($debugOutput,"false")) {
1213          @$platform->unlink($tmpFile);
1214          @$platform->unlink($newTmpFile);
1215        }
1216        
1217    }
1218    
1219    return array(null, $error, $status);
1220  }
1221
1222  /**
1223   * A simple function to resolve the value of a parameter from
1224   * the default or override value if it exists, or set it
1225   * to the default passed as an argument.
1226   */
1227  function getParameter($params, $name, $default="") {
1228    if(isset($params['override'][$name])) {
1229      /* print "override $name = ".$params['override'][$name]."<br>"; */
1230      return($params['override'][$name]);
1231    } else if(isset($params['default'][$name])) {
1232      /* print "default $name = ".$params['default'][$name] ."<br>"; */
1233      return($params['default'][$name]);
1234    } else {
1235      /* print "$name = $default <br>"; */
1236      return($default);
1237    }
1238  }
1239
1240  /**
1241   * A simple function to get the headers only (no body) for a given URL
1242   * This was taken from GalleryCoreApi::requestWebPage
1243   */
1244  function fetchWebFileHeaders($url, $requestHeaders=array()) {
1245      global $gallery;
1246      
1247      $requestMethod='GET';
1248      $requestBody='';
1249      
1250      /* Convert illegal characters */
1251      $url = str_replace(' ', '%20', $url);
1252      
1253      /* Unescape ampersands, since if the URL comes from form input it will be escaped */
1254      $url = str_replace('&amp;', '&', $url);
1255
1256      $platform =& $gallery->getPlatform();
1257      
1258      $urlComponents = parse_url($url);
1259      if (empty($urlComponents['port'])) {
1260          $urlComponents['port'] = 80;
1261      }
1262      if (empty($urlComponents['path'])) {
1263          $urlComponents['path'] = '/';
1264      }
1265
1266      $handle = @$platform->fsockopen(
1267                                      $urlComponents['host'], $urlComponents['port'], $errno, $errstr, 5);
1268      if (empty($handle)) {
1269          $gallery->debug("Error $errno: '$errstr' requesting $url");
1270          return array(null, null, null);
1271      }
1272      
1273      $requestUri = $urlComponents['path'];
1274      if (!empty($urlComponents['query'])) {
1275          $requestUri .= '?' . $urlComponents['query'];
1276      }
1277      $headerLines = array('Host: ' . $urlComponents['host']);
1278      foreach ($requestHeaders as $key => $value) {
1279          $headerLines[] = $key . ': ' . $value;
1280      }
1281      
1282      $success = $platform->fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s",
1283                                                    $requestMethod,
1284                                                    $requestUri,
1285                                                    implode("\r\n", $headerLines),
1286                                                    $requestBody));
1287      if (!$success) {
1288          /* Zero bytes written or false was returned */
1289          $gallery->debug(
1290                          "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''));
1291          return array(null, null, null);
1292      }
1293      $platform->fflush($handle);
1294      
1295      
1296      /*
1297       * Read the status line.  fgets stops after newlines.  The first line is the protocol
1298       * version followed by a numeric status code and its associated textual phrase.
1299       */
1300      $responseStatus = trim($platform->fgets($handle, 4096));
1301      if (empty($responseStatus)) {
1302          $gallery->debug('Empty http response code, maybe timeout');
1303          return array(null, null, null);
1304      }
1305      
1306      /* Read the headers */
1307      $responseHeaders = array();
1308      while (!$platform->feof($handle)) {
1309          $line = trim($platform->fgets($handle, 4096));
1310          if (empty($line)) {
1311              break;
1312          }
1313        
1314          /* Normalize the line endings */
1315          $line = str_replace("\r", '', $line);
1316          
1317          list ($key, $value) = explode(':', $line, 2);
1318          if (isset($responseHeaders[$key])) {
1319              if (!is_array($responseHeaders[$key])) {
1320                $responseHeaders[$key] = array($responseHeaders[$key]);
1321              }
1322              $responseHeaders[$key][] = trim($value);
1323          } else {
1324              $responseHeaders[$key] = trim($value);
1325          }
1326      }
1327      $platform->fclose($handle);
1328
1329      if(preg_match("/Not found/i", $responseStatus)) {
1330          $success = 0;
1331      }
1332
1333      //print "success: $success <br>responseStatus: $responseStatus <br>responseHeaders: $responseHeaders <br>";
1334      
1335      return array($success, $responseStatus, $responseHeaders);
1336  }
1337  
1338  /**
1339   * @see ItemAdd:loadTemplate
1340   */
1341  function loadTemplate(&$template, &$form, $item) {
1342     global $gallery;
1343     
1344     if ($form['formName'] != 'ItemAddEmbedVideo') {
1345         /* First time around, load the form with item data */
1346         $form['webPage'] = '';
1347         $form['formName'] = 'ItemAddEmbedVideo';
1348     }
1349     
1350     $session =& $gallery->getSession();
1351     
1352     $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
1353     
1354     return array(null,
1355                  'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
1356                  'modules_embedvideo');
1357  }
1358  
1359  /**
1360   * @see ItemAddPlugin::getTitle
1361   */
1362  function getTitle() {
1363     list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
1364     if ($ret) {
1365         return array($ret, null);
1366     }
1367     
1368     return array(null, $module->translate('Embed Video'));
1369  }
1370  
1371 }       
1372 ?>