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