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