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