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