Added new autoStart parameter. Added new useRemoteSize parameter.
[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 /**
22  * This plugin will handle the addition of embedded video objects
23  * @package embedVideo
24  * @subpackage UserInterface
25  * @author Alan Pippin <apippin@pippins.net>
26  * @version $Revision: 1.1 $
27  */
28 class ItemAddEmbedVideo extends ItemAddPlugin {
29   
30   /**
31    * @see ItemAddPlugin::handleRequest
32    */
33  function handleRequest($form, &$item) {
34    global $gallery;
35     
36    $status = $error = array();
37    
38    if (isset($form['action']['addEmbedVideoPage'])) {
39      
40        $platform =& $gallery->getPlatform();
41
42        if (empty($extraHeaders)) {
43            $extraHeaders = array('Referer' => str_replace('&amp;', '&', $url));
44        }
45
46        if(isset($form['webPage']['URL'])) {
47          
48            /* Load any stored/set Parameters */
49            list ($ret, $params) =
50              GalleryCoreApi::fetchAllPluginParameters('module', 'embedvideo');
51            if ($ret) {
52                return array($ret, null, null);
53            }
54            foreach (array('default', 'override') as $type) {
55                $ItemAddUploadApplet[$type] = array();
56                if (!empty($params['embedvideo' . $type . 'Variables'])) {
57                    $variablesArray = explode('|', $params['embedvideo' . $type . 'Variables']);
58                    foreach ($variablesArray as $variable) {
59                        list ($name, $value) = explode('=', $variable);
60                        $ItemAddEmbedVideo[$type][$name] = $value;
61                        /* print "type: $type name: $name value: $value <br>"; */
62                    }
63                }
64            }
65            
66            /* Store any Parameters into some simpler, shorter, local variables */
67            global $debugOutput, $useInternalFlvPlayer, $youtubeDevId;
68            global $width, $height, $externalFlvPlayer, $externalFlvPlayerVars;
69            global $flvThumbnail, $useRemoteSize, $autoStart;
70
71            /* Find out what value our parameters should have by looking to see if they
72             * are defined in our overrides section or default section. If they are not
73             * defined in either of these 2 places, pass in a default value to set them to
74             */
75            $debugOutput = $this->getParameter($ItemAddEmbedVideo, 'debugOutput', "false");
76            $useInternalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'useInternalFlvPlayer', "true");
77            $youtubeDevId = $this->getParameter($ItemAddEmbedVideo, 'youtubeDevId', "");
78            $width = $this->getParameter($ItemAddEmbedVideo, 'width', "320");
79            $height = $this->getParameter($ItemAddEmbedVideo, 'height', "240");
80            $externalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayer', "");
81            $externalFlvPlayerVars = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayerVars', "");
82            $flvThumbnail = $this->getParameter($ItemAddEmbedVideo, 'flvThumbnail', "");
83            $useRemoteSize = $this->getParameter($ItemAddEmbedVideo, 'useRemoteSize', "false");
84            $autoStart = $this->getParameter($ItemAddEmbedVideo, 'autoStart', "false");
85            
86            /* Store other string constants we'll use later */
87           
88            /* youtube */
89            $youtubeUrlPattern="youtube.com";
90            $youtubeApiUrl="http://www.youtube.com/api2_rest";
91            $youtubeWidth="425";
92            $youtubeHeight="350";
93
94            /* google */
95            $googleUrlPattern="video.google.com";
96            $googlePlayer="http://video.google.com/googleplayer.swf";
97            $googleWidth="400";
98            $googleHeight="326";
99            
100            /* yahoo */
101            $yahooUrlPattern="video.yahoo.com";
102            $yahooThumbnailUrl="http://thmg01.video.search.yahoo.com/image/";
103            
104            /* metacafe */
105            $metacafeUrlPattern="metacafe.com";
106            $metacafeThumbnailUrl="http://www.metacafe.com/thumb/";
107            
108            /* Gallery2 specific paths and variables */
109            $urlGenerator =& $gallery->getUrlGenerator();
110            $gallery2_url = $urlGenerator->getCurrentUrlDir();
111            $gallery2_flv_thumbnail = "modules/thumbnail/images/G2video.jpg";
112            $gallery2_flv_player = "modules/flashvideo/lib/G2flv.swf";
113            
114            /* Store the passed URL in a shorter local variable */
115            $url = $form['webPage']['URL'];
116
117            /*
118             *****************************
119             * Embed a Youtube Video
120             *****************************
121             */
122            if(preg_match("/$youtubeUrlPattern/",$url)) {
123
124                /* Make sure we can find a video_id in the URL */
125                if(preg_match("/watch\?v=(.*)/",$url,$matches)) {
126                    $video_id = $matches[1];
127                } else {
128                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
129                                 "Unable to extract video id from url: $url"),null,null);
130                }
131                
132                /* Make sure we have a valid youtube developer id */
133                $dev_id = $youtubeDevId;
134                if(!preg_match("/\w+/",$dev_id)) {
135                    return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
136                                 "Invalid/missing YouTube developer ID: $dev_id"),null,null);
137                }
138                
139                /* Youtube api feed */
140                $feed = $youtubeApiUrl.'?method=youtube.videos.get_details';
141                $feed.= "&dev_id=$dev_id&video_id=$video_id";
142                
143                /* Get the youtube xml feed as a string data source */
144                list ($successfullyCopied, $xml, $response, $headers) =
145                  GalleryCoreApi::fetchWebPage($feed, $extraHeaders);
146                if (!$successfullyCopied) {
147                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
148                                 "Unable to get video information at url: $url - $response"),null,null);
149                }
150
151                if(!strcmp($debugOutput,"true")) {
152                  print "$xml";
153                }
154                
155                /* Extract certain information from the xml feed */
156                preg_match_all("/\<title\>(.+?)\<\/title\>/smi",$xml, $title);
157                preg_match_all("/\<description\>(.+?)\<\/description\>/smi",$xml, $description);
158                preg_match_all("/\<thumbnail_url\>(.+?)\<\/thumbnail_url\>/smi",$xml, $thumbnail);
159                
160                array_shift($title);
161                array_shift($thumbnail);
162                array_shift($description);
163           
164                /* Replace html characters. More can be added but this seems to work */
165                for($i=0;$i<count($description[0]);$i++){          
166                    $description[0][$i] = preg_replace("/&#60;/","<",$description[0][$i]);
167                    $description[0][$i] = html_entity_decode($description[0][$i],ENT_QUOTES);      
168                }
169
170                /* Store the information found in some local variables */
171                $title = $title[0][0];
172                $summary = $description[0][0];
173                $thumbnail = $thumbnail[0][0];
174
175                /* Determine what our width and height should be based on our useRemoteSize parameter */
176                if(!strcmp($useRemoteSize,"true")) {
177                  $width = $youtubeWidth;
178                  $height = $youtubeHeight;
179                }
180                
181                /* Determine if the video should autoplay or not based on the autoStart parameter */
182                $autoStartStr="";
183                if(!strcmp($autoStart,"true")) {
184                  $autoStartStr="&autoplay=1";
185                }
186                
187                /* Format the description to hold a reference to the embedded video */
188                $description = '<object width="'.$width.'" height="'.$height.'">';
189                $description.= '<param name="movie" ';
190                $description.= 'value="http://www.youtube.com/v/'.$video_id.'"></param>';
191                $description.= '<param name="wmode" value="transparent"></param>';
192                $description.= '<embed src="http://www.youtube.com/v/'.$video_id.$autoStartStr.'" ';
193                $description.= 'type="application/x-shockwave-flash" wmode="transparent" ';
194                $description.= 'width="'.$width.'" height="'.$height.'"></embed></object>';
195                $description.= "<br>$summary";
196
197            /*
198             **********************************
199             * Embed a Google Video
200             **********************************
201             */
202            } else if(preg_match("/$googleUrlPattern/",$url)) {
203
204                /* Make sure we can extract a docID */
205                if(preg_match("/docid=(.*)/",$url,$matches)) {
206                    $doc_id = $matches[1];
207                } else {
208                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
209                                 "Unable to extract doc id from url: $url"),null,null);
210                }
211
212                /* Grab the contents of the webpage used to display the video on video.google.com */
213                list ($successfullyCopied, $contents, $response, $headers) =
214                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
215                if (!$successfullyCopied) {
216                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
217                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
218                }
219
220                /* Extract the summary from the webpage contents */
221                preg_match('/<meta content="(.+?)\. \w+ \d+, \d+.*" name="description">/i',
222                           $contents, $matches);
223                $summary=$matches[1];
224
225                /* Extract the title from the webpage contents */
226                $title="Unknown";
227                if(preg_match('/<title>(.+?)\s+- Google Video<\/title>/i', $contents, $matches)) {
228                  $title=$matches[1];
229                } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
230                  $title=$matches[1];
231                }
232
233                /* Extract the thumbnail URL from the webpage contents */
234                preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
235                           $contents, $matches);
236                $thumbnail=$matches[1];
237                $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
238
239                /* Determine what our width and height should be based on our useRemoteSize parameter */
240                if(!strcmp($useRemoteSize,"true")) {
241                  $width = $googleWidth;
242                  $height = $googleHeight;
243                }
244
245                /* Determine if the video should autoplay or not based on the autoStart parameter */
246                $autoStartStr="";
247                if(!strcmp($autoStart,"true")) {
248                  $autoStartStr="&autoplay=1";
249                }
250
251                /* Format the description to hold a reference to the embedded video */
252                $description = '<embed FlashVars=';
253                $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
254                $description.= 'type="application/x-shockwave-flash" ';
255                $description.= 'src="'.$googlePlayer.'?docId='.$doc_id.$autoStartStr.'"> ';
256                $description.= '</embed>';
257                $description.= "<br>$summary";
258
259            /*
260             **********************************
261             * Embed a Yahoo Video
262             **********************************
263             * TODO: The autoStart parameter doesn't work with the yahoo video player
264             */
265            } else if(preg_match("/$yahooUrlPattern/",$url)) {
266
267                /* Make sure we can extract a vidID */
268                if(preg_match("/vid=(.*)/",$url,$matches)) {
269                    $vid_id = $matches[1];
270                } else {
271                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
272                                 "Unable to extract vid id from url: $url"),null,null);
273                }
274
275                /* Grab the contents of the webpage used to display the video on video.google.com */
276                list ($successfullyCopied, $contents, $response, $headers) =
277                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
278                if (!$successfullyCopied) {
279                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
280                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
281                }
282
283                /* Extract the summary from the webpage contents */
284                preg_match('/Description:<\/em><p>(.+?)<\/p>/', $contents, $matches);
285                $summary=$matches[1];
286
287                /* Extract the title from the webpage contents */
288                $title="Unknown";
289                if(preg_match('/<title>(.+?)\s+- Yahoo! Video<\/title>/i', $contents, $matches)) {
290                  $title=$matches[1];
291                } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
292                  $title=$matches[1];
293                }
294
295                /* Build the thumbnail URL from the vid_id */
296                $thumbnail=$yahooThumbnailUrl.$vid_id."_01";
297
298                /* Format the description to hold a reference to the embedded video */
299                preg_match('/(<embed src.+?<\/embed>)/', $contents, $matches);
300                $description=$matches[1];
301                if(!strcmp($useRemoteSize,"false")) {
302                  $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
303                  $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
304                }
305                $description.= "<br>$summary";
306
307            /*
308             **********************************
309             * Embed a MetaCafe Video
310             **********************************
311             */
312            } else if(preg_match("/$metacafeUrlPattern/",$url)) {
313
314                /* Make sure we can extract a itemID */
315                if(preg_match("/\/watch\/(.+?)\/(.+?)/",$url,$matches)) {
316                    $item_id = $matches[1];
317                } else {
318                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
319                                 "Unable to extract item id from url: $url"),null,null);
320                }
321
322                /* Grab the contents of the webpage used to display the video on video.google.com */
323                list ($successfullyCopied, $contents, $response, $headers) =
324                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
325                if (!$successfullyCopied) {
326                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
327                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
328                }
329
330                /* Extract the summary from the webpage contents */
331                preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
332                $summary=$matches[1];
333
334                /* Extract the title from the webpage contents */
335                preg_match('/<title>(.+?)<\/title>/i', $contents, $matches);
336                $title=$matches[1];
337                
338                /* Build the thumbnail URL from the item_id */
339                $thumbnail=$metacafeThumbnailUrl.$item_id.".jpg";
340
341                /* Format the description to hold a reference to the embedded video */
342                preg_match('/(embed src.+?\/embed)/', $contents, $matches);
343                $description="<".$matches[1];
344                $description=preg_replace("/&quot;/","'",$description);
345                if(!strcmp($useRemoteSize,"false")) {
346                  $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
347                  $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
348                }
349                if(!strcmp($autoStart,"true")) {
350                  $description=preg_replace("/\.swf/",".swf?playerVars=autoPlay=yes",$description);
351                }
352                $description.= "</embed>";
353                $description.= "<br>$summary";
354          
355            /*
356             **********************************
357             * Embed a remote .flv file
358             **********************************
359             */
360            } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
361
362                /* Set the title and summary to the name of the file */
363                $title = $matches[1];
364                $summary = $matches[1];
365                
366                /*
367                 * Set the thumbnail to some generic jpg image,
368                 * since we can't extract it from the remote flv file.
369                 * If no parameter is set, set it to a default value.
370                 */
371                if(preg_match("/\w+/", $flvThumbnail)) {
372                  $thumbnail = $flvThumbnail;
373                } else {
374                  $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
375                }
376
377                /*
378                 * Check to make sure the URL to the remote flv file is valid
379                 * (That the file exists at the URL given)
380                 */
381                list ($successfullyCopied, $response, $headers) =
382                  $this->fetchWebFileHeaders($url, $extraHeaders);
383                if (!$successfullyCopied) {
384                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
385                               "Unable to find the video at url: $url - $response"),NULL,NULL);
386                }
387                
388                /*
389                 * Format the description to hold a reference to the embedded video
390                 * This reference will be embedded using the G2 internal player,
391                 * or an external player if provided by the user.
392                 */
393                if(!strcmp($useInternalFlvPlayer,"false")) {
394
395                    /*
396                     * The user has indicated they want to use an external flv player
397                     * Make sure one is defined!
398                     */
399                    if(!preg_match("/\w+/",$externalFlvPlayer)) {
400                        return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
401                                    "Invalid/missing external player parameter"),null,null);
402                    }
403
404                    /* Format the description to hold a reference to the embedded video */
405                    $description ='<embed src="'.$externalFlvPlayer.'" ';
406                    $description.= 'width="'.$width.'" height="'.$height.'" ';
407                    $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
408                    $description.= 'type="application/x-shockwave-flash" ';
409                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
410                    $description.= 'flashvars="file='.$url;
411                    $description.= '&fullscreenpage='.$thumbnail;
412                    $description.= '&linktarget=_Blank&image='.$thumbnail;
413
414                    if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
415                        /* Format the flashvars for the internal G2 flv player */
416                        $description.= '&showdigits=true&autostart='.$autoStart.'&showfsbutton=true&';
417                        $description.= '&repeat=false&lightcolor=0x9999FF';
418                        $description.= '&backcolor=0x888888&frontcolor=0x000000"';
419                    } else {
420                        /* Format the flashvars for the external G2 flv player */
421                        $description.= '&'.$externalFlvPlayerVars;
422                    }
423                    $description.=  ' />&nbsp;</p>';
424                
425                /* Internal FLV player */
426                } else {
427                    /* Format the description to hold a reference to the embedded video */
428                    $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
429                    $description = '<script type="text/javascript">'."\n";
430                    $description.= '// <![CDATA['."\n";
431                    $description.= 'function divResize(id, nw, nh) {'."\n";
432                    $description.= 'var obj = document.getElementById(id);'."\n";
433                    $description.= 'obj.style.width = nw + "px";'."\n";
434                    $description.= 'obj.style.height = nh + "px";'."\n";
435                    $description.= '}'."\n";
436                    $description.= '// ]]>'."\n";
437                    $description.= '</script>'."\n";
438                    $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
439                    $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
440                    $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
441                    $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
442                    $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
443                    $description.= '<param name="FlashVars" value="flvUrl='.$url;
444                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
445                    $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
446                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
447                    $description.= '<param name="quality" value="high"/>';
448                    $description.= '<param name="scale" value="noscale"/>';
449                    $description.= '<param name="salign" value="lt"/>';
450                    $description.= '<param name="wmode" value="transparent"/>';
451                    $description.= '<param name="allowScriptAccess" value="always"/>';
452                    $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
453                    $description.= 'flashvars="flvUrl='.$url;
454                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
455                    $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
456                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
457                    $description.= 'type="application/x-shockwave-flash" ';
458                    $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
459                    $description.= 'wmode="transparent" allowScriptAccess="always" ';
460                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
461                    $description.= '</object></div>';
462                }
463                
464           /*
465            **********************************
466            * Unsupported URL to embed
467            **********************************
468            */   
469            } else {
470                return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
471                             "Unable to embed video from: $url"),null,null);
472            }
473            
474
475            /*
476            **********************************
477            * Add the video to Gallery
478            **********************************
479            */
480            
481            /* Get a local tmp file to save the thumbnail URL to */
482            $tmpDir = $gallery->getConfig('data.gallery.tmp');
483            $tmpFile = $platform->tempnam($tmpDir, 'add');
484            $tmpFile.= ".jpg";
485            
486            if(!strcmp($debugOutput,"true")) {
487                print "thumbnail: $thumbnail <br>";
488            }
489            
490            /* Fetch the thumbnail and save it to a local file */
491            list ($successfullyCopied, $response, $headers) =
492              GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
493            if (!$successfullyCopied) {
494                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
495                             "Unable to copy thumbnail from url: $url - $response"),null,null);
496            }
497            
498            /* Obtain the mimeType of the thumbnail */
499            list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
500            
501            /* Set the filename for the item we want to add */
502            $fileName = $title;
503            $fileName = preg_replace("/\s+/","_",$fileName);
504            $fileName = preg_replace("/'/","",$fileName);
505            $fileName = preg_replace("/\"/","",$fileName);
506            $fileName = preg_replace("/&#\d+;/","",$fileName);
507            
508            /* General debug output */
509            if(!strcmp($debugOutput,"true")) {
510                print "title: $title <br>";
511                print "<p><a href=\"".$title."\" target=\"_blank\">";
512                print "<img src=\"".$thumbnail."\">\n</a>".$summary."</p>";
513                print "<p>$description</p>";
514                print "thumbnail: $tmpFile <br>";
515                print "mimeType: $mimeType <br>";
516                print "fileName: $fileName <br>";
517                print "<br><br><b>Video Successfully Added to your Gallery Album</b><br><br>";
518            }
519
520            /* Make the gallery2 call to add this item to the album */
521            list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($tmpFile,
522                                                                   $fileName,
523                                                                   $title,
524                                                                   $summary,
525                                                                   $description,
526                                                                   $mimeType,
527                                                                   $item->getId());
528            
529            if ($ret) {
530                return array($ret, null, null);
531            }
532            
533            $status['addedFiles'][] = array('fileName' => $url,
534                                            'id' => $newItem->getId(),
535                                            'warnings' => array());
536        }
537        @$platform->unlink($tmpFile);
538    }
539    
540    return array(null, $error, $status);
541  }
542
543  /**
544   * A simple function to resolve the value of a parameter from
545   * the default or override value if it exists, or set it
546   * to the default passed as an argument.
547   */
548  function getParameter($params, $name, $default="") {
549    if(isset($params['override'][$name])) {
550      /* print "override $name = ".$params['override'][$name]."<br>"; */
551      return($params['override'][$name]);
552    } else if(isset($params['default'][$name])) {
553      /* print "default $name = ".$params['default'][$name] ."<br>"; */
554      return($params['default'][$name]);
555    } else {
556      /* print "$name = $default <br>"; */
557      return($default);
558    }
559  }
560
561  /**
562   * A simple function to get the headers only (no body) for a given URL
563   * This was taken from GalleryCoreApi::requestWebPage
564   */
565  function fetchWebFileHeaders($url, $requestHeaders=array()) {
566      global $gallery;
567      
568      $requestMethod='GET';
569
570      /* Convert illegal characters */
571      $url = str_replace(' ', '%20', $url);
572      
573      /* Unescape ampersands, since if the URL comes from form input it will be escaped */
574      $url = str_replace('&amp;', '&', $url);
575
576      $platform =& $gallery->getPlatform();
577      
578      $urlComponents = parse_url($url);
579      if (empty($urlComponents['port'])) {
580          $urlComponents['port'] = 80;
581      }
582      if (empty($urlComponents['path'])) {
583          $urlComponents['path'] = '/';
584      }
585
586      $handle = @$platform->fsockopen(
587                                      $urlComponents['host'], $urlComponents['port'], $errno, $errstr, 5);
588      if (empty($handle)) {
589          $gallery->debug("Error $errno: '$errstr' requesting $url");
590          return array(null, null, null);
591      }
592      
593      $requestUri = $urlComponents['path'];
594      if (!empty($urlComponents['query'])) {
595          $requestUri .= '?' . $urlComponents['query'];
596      }
597      $headerLines = array('Host: ' . $urlComponents['host']);
598      foreach ($requestHeaders as $key => $value) {
599          $headerLines[] = $key . ': ' . $value;
600      }
601      
602      $success = $platform->fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s",
603                                                    $requestMethod,
604                                                    $requestUri,
605                                                    implode("\r\n", $headerLines),
606                                                    $requestBody));
607      if (!$success) {
608          /* Zero bytes written or false was returned */
609          $gallery->debug(
610                          "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''));
611          return array(null, null, null);
612      }
613      $platform->fflush($handle);
614      
615      
616      /*
617       * Read the status line.  fgets stops after newlines.  The first line is the protocol
618       * version followed by a numeric status code and its associated textual phrase.
619       */
620      $responseStatus = trim($platform->fgets($handle, 4096));
621      if (empty($responseStatus)) {
622          $gallery->debug('Empty http response code, maybe timeout');
623          return array(null, null, null);
624      }
625      
626      /* Read the headers */
627      $responseHeaders = array();
628      while (!$platform->feof($handle)) {
629          $line = trim($platform->fgets($handle, 4096));
630          if (empty($line)) {
631              break;
632          }
633        
634          /* Normalize the line endings */
635          $line = str_replace("\r", '', $line);
636          
637          list ($key, $value) = explode(':', $line, 2);
638          if (isset($responseHeaders[$key])) {
639              if (!is_array($responseHeaders[$key])) {
640                $responseHeaders[$key] = array($responseHeaders[$key]);
641              }
642              $responseHeaders[$key][] = trim($value);
643          } else {
644              $responseHeaders[$key] = trim($value);
645          }
646      }
647      $platform->fclose($handle);
648
649      if(preg_match("/Not found/i", $responseStatus)) {
650          $success = 0;
651      }
652
653      //print "success: $success <br>responseStatus: $responseStatus <br>responseHeaders: $responseHeaders <br>";
654      
655      return array($success, $responseStatus, $responseHeaders);
656  }
657  
658  /**
659   * @see ItemAdd:loadTemplate
660   */
661  function loadTemplate(&$template, &$form, $item) {
662     global $gallery;
663     
664     if ($form['formName'] != 'ItemAddEmbedVideo') {
665         /* First time around, load the form with item data */
666         $form['webPage'] = '';
667         $form['formName'] = 'ItemAddEmbedVideo';
668     }
669     
670     $session =& $gallery->getSession();
671     
672     $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
673     
674     return array(null,
675                  'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
676                  'modules_embedvideo');
677  }
678  
679  /**
680   * @see ItemAddPlugin::getTitle
681   */
682  function getTitle() {
683     list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
684     if ($ret) {
685         return array($ret, null);
686     }
687     
688     return array(null, $module->translate('Embed Video'));
689  }
690  
691 }       
692 ?>