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