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