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