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