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