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