New release 1.1.1:
[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.com";
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.com";
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.com";
137            $yahooThumbnailUrl="http://thmg01.video.search.yahoo.com/image/";
138            
139            /* metacafe */
140            $metacafeUrlPattern="metacafe.com";
141            $metacafeThumbnailUrl="http://www.metacafe.com/thumb/";
142
143            /* revver */
144            $revverUrlPattern="revver.com";
145            $revverThumbnailUrl="http://frame.revver.com/frame/120x90/";
146
147            /* dailymotion */
148            $dailymotionUrlPattern="dailymotion.com";
149            $dailymotionThumbnailUrl="http://www.dailymotion.com/thumbnail/160x120/video/";
150
151            /* divshare */
152            $divshareUrlPattern="divshare.com";
153            $divshareThumbnailUrl="http://www.divshare.com/direct/video_thumb/";
154
155            /* stickam */
156            $stickamUrlPattern="stickam.com";
157            $stickamThumbnailUrl="http://static.stickam.com/";
158
159            /* myspace */
160            $myspaceUrlPattern="vids.myspace.com";
161            $myspaceUrlPattern2="myspacetv.com";
162            $myspaceThumbnailUrl="http://mediaservices.myspace.com/services/rss.ashx?type=video&videoID=";
163
164            /* vimeo */
165            $vimeoUrlPattern="www.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 on video.google.com */
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 on video.google.com */
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 on video.google.com */
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 on video.google.com */
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 on video.google.com */
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 on video.google.com */
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('/input type.+?'.$item_id.'.+?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 on video.google.com */
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 on video.google.com */
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 type="application/x-shockwave-flash" width="'.$width.'" height="'.$height.'"';
802                $description.= 'data="http://www.vimeo.com/moogaloop.swf?clip_id='.$video_id;
803                $description.= '&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1'.$autoStartStr;
804                $description.= '&amp;show_byline=1&amp;show_portrait=0&amp;color=">';
805                $description.= '<param name="quality" value="best" />';
806                $description.= '<param name="allowfullscreen" value="true" />';
807                $description.= '<param name="scale" value="showAll" />';
808                $description.= '<param name="movie" value="http://www.vimeo.com/moogaloop.swf?clip_id='.$video_id;
809                $description.= '&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1'.$autoStartStr;
810                $description.= '&amp;show_byline=1&amp;show_portrait=0&amp;color=" />';
811                $description.= '</object>';
812                
813            /*
814             **********************************
815             * Embed a remote .swf file
816             **********************************
817             */
818            } else if(preg_match("/.*\/(.+?)\.swf/i",$url,$matches)) {
819
820                /* Set the title and summary to the name of the file */
821                $title = $matches[1];
822                $summary = $matches[1];
823                
824                /*
825                 * Set the thumbnail to some generic jpg image,
826                 * since we can't extract it from the remote swf file.
827                 * If no parameter is set, set it to a default value.
828                 */
829                if(preg_match("/\w+/", $flvThumbnail)) {
830                  $thumbnail = $flvThumbnail;
831                } else {
832                  $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
833                }
834
835                /*
836                 * Check to make sure the URL to the remote swf file is valid
837                 * (That the file exists at the URL given)
838                 */
839                list ($successfullyCopied, $response, $headers) =
840                  $this->fetchWebFileHeaders($url, $extraHeaders);
841                if (!$successfullyCopied) {
842                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
843                               "Unable to find the video at url: $url - $response"),NULL,NULL);
844                }
845                
846                /*
847                 * Format the description to hold a reference to the embedded video
848                 */
849
850                /* Format the description to hold a reference to the embedded video */
851                $description ='<embed src="'.$url.'">';
852                
853            /*
854             **********************************
855             * Embed a remote .flv or .mp4 file
856             **********************************
857             */
858            } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches) ||
859                      preg_match("/.*\/(.+?)\.mp4/i",$url,$matches)) {
860              
861                /* Set the title and summary to the name of the file */
862                $title = $matches[1];
863                $summary = $matches[1];
864                
865                /*
866                 * Set the thumbnail to some generic jpg image,
867                 * since we can't extract it from the remote flv file.
868                 * If no parameter is set, set it to a default value.
869                 */
870                if(preg_match("/\w+/", $flvThumbnail)) {
871                  $thumbnail = $flvThumbnail;
872                } else {
873                  $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
874                }
875
876                /*
877                 * Check to make sure the URL to the remote flv file is valid
878                 * (That the file exists at the URL given)
879                 */
880                list ($successfullyCopied, $response, $headers) =
881                  $this->fetchWebFileHeaders($url, $extraHeaders);
882                if (!$successfullyCopied) {
883                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
884                               "Unable to find the video at url: $url - $response"),NULL,NULL);
885                }
886                
887                /*
888                 * Format the description to hold a reference to the embedded video
889                 * This reference will be embedded using the G2 internal player,
890                 * or an external player if provided by the user.
891                 */
892                if(!strcmp($useInternalFlvPlayer,"false")) {
893
894                    /*
895                     * The user has indicated they want to use an external flv player
896                     * Make sure one is defined!
897                     */
898                    if(!preg_match("/\w+/",$externalFlvPlayer)) {
899                        return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
900                                    "Invalid/missing external player parameter"),null,null);
901                    }
902
903                    /* Format the description to hold a reference to the embedded video */
904                    $description ='<embed src="'.$externalFlvPlayer.'" ';
905                    $description.= 'width="'.$width.'" height="'.$height.'" ';
906                    $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
907                    $description.= 'type="application/x-shockwave-flash" ';
908                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
909                    $description.= 'flashvars="file='.$url;
910                    $description.= '&fullscreenpage='.$thumbnail;
911                    $description.= '&linktarget=_Blank&image='.$thumbnail;
912
913                    if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
914                        /* Format the flashvars for the internal G2 flv player */
915                        $description.= '&showdigits=true&autostart='.$autoStart.'&showfsbutton=true&';
916                        $description.= '&repeat=false&lightcolor=0x9999FF';
917                        $description.= '&backcolor=0x888888&frontcolor=0x000000"';
918                    } else {
919                        /* Format the flashvars for the external G2 flv player */
920                        $description.= '&'.$externalFlvPlayerVars;
921                    }
922                    $description.=  ' />&nbsp;</p>';
923                
924                /* Internal FLV player */
925                } else {
926                    /* Format the description to hold a reference to the embedded video */
927                    $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
928                    $description = '<script type="text/javascript">'."\n";
929                    $description.= '// <![CDATA['."\n";
930                    $description.= 'function divResize(id, nw, nh) {'."\n";
931                    $description.= 'var obj = document.getElementById(id);'."\n";
932                    $description.= 'obj.style.width = nw + "px";'."\n";
933                    $description.= 'obj.style.height = nh + "px";'."\n";
934                    $description.= '}'."\n";
935                    $description.= '// ]]>'."\n";
936                    $description.= '</script>'."\n";
937                    $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
938                    $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
939                    $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
940                    $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
941                    $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
942                    $description.= '<param name="FlashVars" value="flvUrl='.$url;
943                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
944                    $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
945                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
946                    $description.= '<param name="quality" value="high"/>';
947                    $description.= '<param name="scale" value="noscale"/>';
948                    $description.= '<param name="salign" value="lt"/>';
949                    $description.= '<param name="wmode" value="transparent"/>';
950                    $description.= '<param name="allowScriptAccess" value="always"/>';
951                    $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
952                    $description.= 'flashvars="flvUrl='.$url;
953                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
954                    $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
955                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
956                    $description.= 'type="application/x-shockwave-flash" ';
957                    $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
958                    $description.= 'wmode="transparent" allowScriptAccess="always" ';
959                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
960                    $description.= '</object></div>';
961                }
962
963            /*
964             **********************************
965             * Embed a generic <object ... <embed ... video
966             **********************************
967             */ 
968            } else {
969
970              /* Grab the contents of the webpage used to display the video */
971              list ($successfullyCopied, $contents, $response, $headers) =
972                GalleryCoreApi::fetchWebPage($url, $extraHeaders);
973              if (!$successfullyCopied) {
974                return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
975                                                   "Unable to get video information at url: $url - $response"),NULL,NULL);
976              }
977
978              /* Extract the URL base (site name) */
979              preg_match("/(http:\/\/.+?)\//i",$url,$matches);
980              $site = $matches[1];
981              print "site: $site<br>";
982              
983              /* Extract the summary from the webpage contents */
984              $summary="Unknown";
985              if(preg_match('/<meta name="description" content="(.+?)"/si', $contents, $matches)) {
986                $summary=$matches[1];
987              }
988
989              /* Extract the title from the webpage contents */
990              $title="Unknown";
991              if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
992                $title=$matches[1];
993              }
994
995              /*
996               * Set the thumbnail to some generic jpg image,
997               * since we can't extract it from a generic website.
998               * If no parameter is set, set it to a default value.
999               */
1000              if(preg_match("/\w+/", $flvThumbnail)) {
1001                $thumbnail = $flvThumbnail;
1002              } else {
1003                $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
1004              }
1005
1006              /* Format the description to hold a reference to the embedded video */
1007              if(preg_match('/(<object.+?<embed.+?<\/object>)/', $contents, $matches)) { 
1008                $description=$matches[1];
1009                if(!strcmp($useRemoteSize,"false")) {
1010                  $description=preg_replace("/width=\"\d+\"/","width=\"".$width."\"",$description);
1011                  $description=preg_replace("/height=\"\d+\"/","height=\"".$height."\"",$description);
1012                }
1013                $description=preg_replace("/src=\"\//","src=\"".$site."\/",$description);
1014              } else {
1015                $unsupported_url=1;
1016              }
1017            }
1018            
1019           /*
1020            **********************************
1021            * Unsupported URL to embed
1022            **********************************
1023            */   
1024            if($unsupported_url == 1) {
1025                return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
1026                             "Unable to embed video from: $url"),null,null);
1027            }
1028            
1029
1030            /*
1031            **********************************
1032            * Add the video to Gallery
1033            **********************************
1034            */
1035            
1036            /* Get a local tmp file to save the thumbnail URL to */
1037            $tmpDir = $gallery->getConfig('data.gallery.tmp');
1038            $tmpFile = $platform->tempnam($tmpDir, 'add');
1039            $tmpFile.= ".jpg";
1040                    
1041            /* Fetch the thumbnail and save it to a local file */
1042            list ($successfullyCopied, $response, $headers) =
1043              GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
1044            if (!$successfullyCopied) {
1045                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1046                             "Unable to copy thumbnail from url: $thumbnail - $response"),null,null);
1047            }
1048            
1049            /* Obtain the mimeType of the thumbnail */
1050            list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
1051            
1052            /* Set the filename for the item we want to add */
1053            $fileName = $title;
1054            $fileName = preg_replace("/\s+/","_",$fileName);
1055            $fileName = preg_replace("/'/","",$fileName);
1056            $fileName = preg_replace("/\"/","",$fileName);
1057            $fileName = preg_replace("/&#\d+;/","",$fileName);
1058
1059            /* Wordwrap the description or summary as appropriate */
1060            $description_summary = $summary;
1061
1062            if(strcmp($wordwrapSummary,"0")) {
1063              $summary = wordwrap($summary,$wordwrapSummary,"<br>",FALSE);
1064            }
1065
1066            if(strcmp($wordwrapDescription,"0")) {
1067              $description_summary = wordwrap($description_summary,$wordwrapDescription,"<br>",FALSE);
1068            }
1069            
1070            /* Tack on the summary to the end of the description */
1071            $description.= "<br>$description_summary";
1072            
1073            /* General debug output */
1074            if(!strcmp($debugOutput,"true")) {
1075                print "\n<h2>Item Parameters</h2>\n";
1076                print "url: $url <br>\n";
1077                print "title: $title <br>\n";
1078                print "thumbnailUrl: $thumbnail <br><img src=\"".$thumbnail."\"> <br>\n";
1079                print "summary: <p>$summary</p>\n";
1080                print "description: <p>$description</p>\n";
1081                print "thumbnail: $tmpFile <br>\n";
1082                print "mimeType: $mimeType <br>\n";
1083                print "fileName: $fileName <br>\n";
1084                print "width: $width <br>\n";
1085                print "height: $height <br>\n";
1086                print "<hr>";
1087            }
1088
1089            /* Resize the thumbnail image to the size indicated by our album */
1090            $debugString="";
1091            list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'resize');
1092            if (!$ret) {
1093                $debugString.="Checking to see if a toolkit that can resize images was found. <br>";
1094                if (isset($toolkit)) {
1095                    $newTmpFile = $platform->tempnam($tmpDir, 'add');
1096                    $newTmpFile.= ".jpg";
1097                    $thumbnailSize = 150;
1098                    list ($ret, $preferences) =
1099                      GalleryCoreApi::fetchDerivativePreferencesForItem($item->getId());
1100                    if(!$ret) {
1101                        foreach ($preferences as $preference) {
1102                          if (preg_match('/thumbnail\|(\d+)/',
1103                                         $preference['derivativeOperations'], $matches)) {
1104                              $thumbnailSize = $matches[1];
1105                              $debugString.="Found thumbnail size in album preferences: $thumbnailSize <br>";
1106                              break;
1107                          }
1108                        }
1109                    }
1110                    
1111                    // Obtain the width and height of the original thumbnail, finding out it's ratio,
1112                    // and using that ratio when determining the width of the video below.
1113                    // Example: youtube: 130x97 google: 160x120 metacafe: 90x76 yahoo: 100x70
1114                    // Set the thumbnailHeight to the current thumbnailSize
1115                    // Set the thumbnailWidth to the appropriate size based on the thumbnailHeight * ratio
1116                    $image_data = @getimagesize($tmpFile);
1117                    if(!$image_data) {
1118                      return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1119                             "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
1120                    }
1121                    $ratio = $image_data[0] / $image_data[1];
1122                    $debugString.="Using ratio from original thumbnail of $ratio. ";
1123                    $thumbnailHeight=$thumbnailSize;
1124                    $thumbnailWidth=round($thumbnailHeight * $ratio);
1125                    $debugString.="Resizing thumbnail image to $thumbnailWidth x $thumbnailHeight: $tmpFile -> $newTmpFile <br>";
1126                    $toolkit->performOperation($mimeType, 'resize', $tmpFile, $newTmpFile,
1127                                               array($thumbnailWidth,$thumbnailHeight));
1128                }
1129            }
1130            if(!strcmp($debugOutput,"true")) {
1131                print "\n<h2>Thumbnail Resize</h2>\n";
1132                print "$debugString\n";
1133                print "<hr>\n";
1134            }
1135
1136            /* Watermark the video thumbnail image if indicated by our parameter */
1137            if(!strcmp($watermarkVideos,"true")) {
1138              
1139              /*
1140               * If no watermarkImage parameter is set, set it to a default value.
1141               */
1142              if(preg_match("/\w+/", $watermarkImage)) {
1143                $watermarkImage = $watermarkImage;
1144              } else {
1145                $watermarkImage = $gallery2_url.$gallery2_video_watermark;
1146              }
1147              
1148              /* Get the watermark Image Extension */
1149              preg_match('/\.(...)$/', $watermarkImage, $matches);
1150              $watermarkExt=$matches[1];
1151              
1152              /*
1153               * Check to make sure the URL to the watermark image file is valid
1154               * (That the file exists at the URL given). Skip this part if it is a local path.
1155               */
1156              if(!preg_match("/^\//", $watermarkImage)) {
1157                list ($successfullyCopied, $response, $headers) =
1158                  $this->fetchWebFileHeaders($watermarkImage, $extraHeaders);
1159                if (!$successfullyCopied) {
1160                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
1161                         "Unable to find the watermark image at url: $watermarkImage - $response"),NULL,NULL);
1162                }
1163              
1164                /* Download the watermark image to a local file */
1165                $tmpDir = $gallery->getConfig('data.gallery.tmp');
1166                $watermark = $platform->tempnam($tmpDir, 'wmk_img_');
1167                $watermark.= "." . $watermarkExt;
1168                list ($successfullyCopied, $response, $headers) =
1169                  GalleryCoreApi::fetchWebFile($watermarkImage, $watermark, $extraHeaders);
1170                if (!$successfullyCopied) {
1171                  return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1172                         "Unable to copy watermark image from url: $watermarkImage - $response"),null,null);
1173                }
1174              } else {
1175                $tmpDir = $gallery->getConfig('data.gallery.tmp');
1176                $watermark = $platform->tempnam($tmpDir, 'wmk_img_');
1177                $watermark.= "." . $watermarkExt;
1178                if(!$platform->copy($watermarkImage, $watermark)) {
1179                  return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1180                         "Unable to copy watermark image from path: $watermarkImage"),null,null);
1181                }
1182              }
1183              
1184              /* See if there is a toolkit installed that can perform a composite operation */
1185              list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'composite');
1186              if ($ret) {
1187                return array($ret->wrap(__FILE__, __LINE__,
1188                       "Unable to locate a toolkit module to perform the 'composite' watermark operation"), null);
1189              }
1190
1191              /* Make sure we can access the toolkit found */
1192              if (!isset($toolkit)) {
1193                return array(GalleryStatus::error(ERROR_PERMISSION_DENIED, __FILE__, __LINE__,
1194                       "Unable to access the toolkit module to perform the 'composite' watermark operation"), null);
1195              }
1196              
1197              /* Get the image dimensions of the thumbnail */
1198              $image_data = @getimagesize($newTmpFile);
1199              if(!$image_data) {
1200                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1201                       "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
1202              }
1203              $thumbnailWidth = $image_data[0];
1204              $thumbnailHeight = $image_data[1];
1205
1206              /* Get the image dimensions of the watermark */
1207              $image_data = @getimagesize($watermark);
1208              if(!$image_data) {
1209                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1210                       "Unable to retrieve watermark dimensions for: $tmpFile"),null,null);
1211              }
1212              $watermarkWidth = $image_data[0];
1213              $watermarkHeight = $image_data[1];
1214
1215              /* Obtain the mimeType of the watermark */
1216              list ($ret, $watermarkMimeType) = GalleryCoreApi::getMimeType($watermark);
1217
1218              /* Remove the gallery base path from the watermark image path */
1219              /* This has to be done to satisfy the argument requirement for the toolkit operation */
1220              $dataDir = $gallery->getConfig('data.gallery.base');
1221              $dataDir=preg_replace("/\//","\\/",$dataDir);
1222              if(preg_match("/$dataDir(.*)/", $watermark, $matches)) { 
1223                $watermark = $matches[1];
1224              }
1225              
1226              /* General debug output */
1227              if(!strcmp($debugOutput,"true")) {
1228                print "\n<h2>Watermark Operation</h2>\n";
1229                print "watermarkImage: $watermarkImage <br>\n";
1230                print "watermarkTmpImage: $watermark <br>\n";
1231                print "watermarkMimeType: $watermarkMimeType <br>\n";
1232                print "watermarkWidth: $watermarkWidth <br>\n";
1233                print "watermarkHeight: $watermarkHeight <br>\n";
1234                print "watermarkedWidth: $thumbnailWidth <br>\n";
1235                print "watermarkedHeight: $thumbnailHeight <br>\n";
1236              }
1237
1238              /* Apply the watermark image to the thumbnail */
1239              $tmpFile = $platform->tempnam($tmpDir, 'wmk_');
1240              list ($ret, $mimeType) = $toolkit->performOperation(
1241                                                                  $mimeType, 'composite', $newTmpFile, $tmpFile,
1242                                                                  array($watermark, $watermarkMimeType,
1243                                                                        $watermarkWidth, $watermarkHeight,
1244                                                                        $watermarkAlignment, 0, 0));
1245              
1246              /* Check the return code of the composite operation */
1247              if ($ret) {
1248                return array($ret->wrap(__FILE__, __LINE__,
1249                                        "Unable to apply watermark to the video thumbnail image"), null);
1250              }
1251
1252              if(!strcmp($debugOutput,"true")) {
1253                print "\nwatermarked Image: $tmpFile <br>";
1254                print "<hr>";
1255              }
1256                        
1257              /* Update the path of our thumbnail to point to the new watermarked thumbnail instead */
1258              $newTmpFile = $tmpFile;
1259              
1260            }
1261            
1262            /* Make the gallery2 call to add this item to the album */
1263            list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($newTmpFile,
1264                                                                   $fileName,
1265                                                                   $title,
1266                                                                   $summary,
1267                                                                   $description,
1268                                                                   $mimeType,
1269                                                                   $item->getId());
1270            
1271            if ($ret) {
1272                return array($ret, null, null);
1273            }
1274            
1275            $status['addedFiles'][] = array('fileName' => $url,
1276                                            'id' => $newItem->getId(),
1277                                            'warnings' => array());
1278
1279            if(!strcmp($debugOutput,"true")) {
1280                print "\n<br><br><h2>Video Successfully Added to your Gallery Album</h2><br><br><hr>";
1281            }
1282        }
1283        
1284        /* Keep the tmpfiles around if we are in debug mode. Otherwise, remove them. */
1285        if(!strcmp($debugOutput,"false")) {
1286          @$platform->unlink($tmpFile);
1287          @$platform->unlink($newTmpFile);
1288        }
1289        
1290    }
1291    
1292    return array(null, $error, $status);
1293  }
1294
1295  /**
1296   * A simple function to resolve the value of a parameter from
1297   * the default or override value if it exists, or set it
1298   * to the default passed as an argument.
1299   */
1300  function getParameter($params, $name, $default="") {
1301    if(isset($params['override'][$name])) {
1302      /* print "override $name = ".$params['override'][$name]."<br>"; */
1303      return($params['override'][$name]);
1304    } else if(isset($params['default'][$name])) {
1305      /* print "default $name = ".$params['default'][$name] ."<br>"; */
1306      return($params['default'][$name]);
1307    } else {
1308      /* print "$name = $default <br>"; */
1309      return($default);
1310    }
1311  }
1312
1313  /**
1314   * A simple function to get the headers only (no body) for a given URL
1315   * This was taken from GalleryCoreApi::requestWebPage
1316   */
1317  function fetchWebFileHeaders($url, $requestHeaders=array()) {
1318      global $gallery;
1319      
1320      $requestMethod='GET';
1321      $requestBody='';
1322      
1323      /* Convert illegal characters */
1324      $url = str_replace(' ', '%20', $url);
1325      
1326      /* Unescape ampersands, since if the URL comes from form input it will be escaped */
1327      $url = str_replace('&amp;', '&', $url);
1328
1329      $platform =& $gallery->getPlatform();
1330      
1331      $urlComponents = parse_url($url);
1332      if (empty($urlComponents['port'])) {
1333          $urlComponents['port'] = 80;
1334      }
1335      if (empty($urlComponents['path'])) {
1336          $urlComponents['path'] = '/';
1337      }
1338
1339      $handle = @$platform->fsockopen(
1340                                      $urlComponents['host'], $urlComponents['port'], $errno, $errstr, 5);
1341      if (empty($handle)) {
1342          $gallery->debug("Error $errno: '$errstr' requesting $url");
1343          return array(null, null, null);
1344      }
1345      
1346      $requestUri = $urlComponents['path'];
1347      if (!empty($urlComponents['query'])) {
1348          $requestUri .= '?' . $urlComponents['query'];
1349      }
1350      $headerLines = array('Host: ' . $urlComponents['host']);
1351      foreach ($requestHeaders as $key => $value) {
1352          $headerLines[] = $key . ': ' . $value;
1353      }
1354      
1355      $success = $platform->fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s",
1356                                                    $requestMethod,
1357                                                    $requestUri,
1358                                                    implode("\r\n", $headerLines),
1359                                                    $requestBody));
1360      if (!$success) {
1361          /* Zero bytes written or false was returned */
1362          $gallery->debug(
1363                          "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''));
1364          return array(null, null, null);
1365      }
1366      $platform->fflush($handle);
1367      
1368      
1369      /*
1370       * Read the status line.  fgets stops after newlines.  The first line is the protocol
1371       * version followed by a numeric status code and its associated textual phrase.
1372       */
1373      $responseStatus = trim($platform->fgets($handle, 4096));
1374      if (empty($responseStatus)) {
1375          $gallery->debug('Empty http response code, maybe timeout');
1376          return array(null, null, null);
1377      }
1378      
1379      /* Read the headers */
1380      $responseHeaders = array();
1381      while (!$platform->feof($handle)) {
1382          $line = trim($platform->fgets($handle, 4096));
1383          if (empty($line)) {
1384              break;
1385          }
1386        
1387          /* Normalize the line endings */
1388          $line = str_replace("\r", '', $line);
1389          
1390          list ($key, $value) = explode(':', $line, 2);
1391          if (isset($responseHeaders[$key])) {
1392              if (!is_array($responseHeaders[$key])) {
1393                $responseHeaders[$key] = array($responseHeaders[$key]);
1394              }
1395              $responseHeaders[$key][] = trim($value);
1396          } else {
1397              $responseHeaders[$key] = trim($value);
1398          }
1399      }
1400      $platform->fclose($handle);
1401
1402      if(preg_match("/Not found/i", $responseStatus)) {
1403          $success = 0;
1404      }
1405
1406      //print "success: $success <br>responseStatus: $responseStatus <br>responseHeaders: $responseHeaders <br>";
1407      
1408      return array($success, $responseStatus, $responseHeaders);
1409  }
1410  
1411  /**
1412   * @see ItemAdd:loadTemplate
1413   */
1414  function loadTemplate(&$template, &$form, $item) {
1415     global $gallery;
1416     
1417     if ($form['formName'] != 'ItemAddEmbedVideo') {
1418         /* First time around, load the form with item data */
1419         $form['webPage'] = '';
1420         $form['formName'] = 'ItemAddEmbedVideo';
1421     }
1422     
1423     $session =& $gallery->getSession();
1424     
1425     $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
1426     
1427     return array(null,
1428                  'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
1429                  'modules_embedvideo');
1430  }
1431  
1432  /**
1433   * @see ItemAddPlugin::getTitle
1434   */
1435  function getTitle() {
1436     list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
1437     if ($ret) {
1438         return array($ret, null);
1439     }
1440     
1441     return array(null, $module->translate('Embed Video'));
1442  }
1443  
1444 }       
1445 ?>