Added ability to check for "File not found" HTTP error when embedding link to remote...
[embedvideo/.git] / ItemAddEmbedVideo.inc
index 457ad724a52fd6ae6920873c550f05d11c5f7b0c..b8941f60e09fcc5409f20bec9ea527629f35eea1 100644 (file)
@@ -38,7 +38,11 @@ class ItemAddEmbedVideo extends ItemAddPlugin {
    if (isset($form['action']['addEmbedVideoPage'])) {
      
        $platform =& $gallery->getPlatform();
-      
+
+       if (empty($extraHeaders)) {
+          $extraHeaders = array('Referer' => str_replace('&', '&', $url));
+       }
+
        if(isset($form['webPage']['URL'])) {
         
           /* Load any stored/set Parameters */
@@ -54,30 +58,36 @@ class ItemAddEmbedVideo extends ItemAddPlugin {
                   foreach ($variablesArray as $variable) {
                       list ($name, $value) = explode('=', $variable);
                       $ItemAddEmbedVideo[$type][$name] = $value;
+                      /* print "type: $type name: $name value: $value <br>"; */
                   }
               }
           }
           
           /* Store any Parameters into some simpler, shorter, local variables */
-          $debugOutput = $ItemAddEmbedVideo['default']['debugOutput'];
-          $useInternalFlvPlayer = $ItemAddEmbedVideo['default']['useInternalFlvPlayer'];
-          $youtubeDevId = $ItemAddEmbedVideo['default']['youtubeDevId'];
-          $width=$ItemAddEmbedVideo['default']['width'];
-          $height=$ItemAddEmbedVideo['default']['height'];
-          $externalFlvPlayer = $ItemAddEmbedVideo['default']['externalFlvPlayer'];
-          $externalFlvPlayerVars = $ItemAddEmbedVideo['default']['externalFlvPlayerVars'];
-          $flvThumbnail = $ItemAddEmbedVideo['default']['flvThumbnail'];
+          global $debugOutput, $useInternalFlvPlayer, $youtubeDevId;
+          global $width, $height, $externalFlvPlayer, $externalFlvPlayerVars;
+          global $flvThumbnail;
+
+          $debugOutput = $this->getParameter($ItemAddEmbedVideo, 'debugOutput');
+          $useInternalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'useInternalFlvPlayer');
+          $youtubeDevId = $this->getParameter($ItemAddEmbedVideo, 'youtubeDevId');
+          $width = $this->getParameter($ItemAddEmbedVideo, 'width');
+          $height = $this->getParameter($ItemAddEmbedVideo, 'height');
+          $externalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayer');
+          $externalFlvPlayerVars = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayerVars');
+          $flvThumbnail = $this->getParameter($ItemAddEmbedVideo, 'flvThumbnail');
 
           /* Store other string constants we'll use later */
-          $youtubeUrlPattern="www.youtube.com";
+          $youtubeUrlPattern="youtube.com";
           $youtubeApiUrl="http://www.youtube.com/api2_rest";
           $googleUrlPattern="video.google.com";
           $googlePlayer="http://video.google.com/googleplayer.swf";
           
           /* Gallery2 specific paths and variables */
-          $gallery2_url = "http://www.pippins.net/gallery2";
-          $gallery2_flv_thumbnail = "/modules/thumbnail/images/G2video.jpg";
-          $gallery2_flv_player = "/modules/flashvideo/lib/G2flv.swf";
+          $urlGenerator =& $gallery->getUrlGenerator();
+          $gallery2_url = $urlGenerator->getCurrentUrlDir();
+          $gallery2_flv_thumbnail = "modules/thumbnail/images/G2video.jpg";
+          $gallery2_flv_player = "modules/flashvideo/lib/G2flv.swf";
           
           /* Store the passed URL in a shorter local variable */
           $url = $form['webPage']['URL'];
@@ -109,9 +119,15 @@ class ItemAddEmbedVideo extends ItemAddPlugin {
               $feed.= "&dev_id=$dev_id&video_id=$video_id";
               
               /* Get the youtube xml feed as a string data source */
-              $xml = _getFeed($feed);  
+              list ($successfullyCopied, $xml, $response, $headers) =
+                GalleryCoreApi::fetchWebPage($feed, $extraHeaders);
+              if (!$successfullyCopied) {
+                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
+                               "Unable to get video information at url: $url - $response"),null,null);
+              }
 
-              if($debugOutput) {
+
+              if(!strcmp($debugOutput,"true")) {
                 print "$xml";
               }
               
@@ -161,7 +177,12 @@ class ItemAddEmbedVideo extends ItemAddPlugin {
               }
 
               /* Grab the contents of the webpage used to display the video on video.google.com */
-              $contents=file_get_contents($url);
+              list ($successfullyCopied, $contents, $response, $headers) =
+                GalleryCoreApi::fetchWebPage($url, $extraHeaders);
+              if (!$successfullyCopied) {
+                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
+                               "Unable to get video information at url: $url - $response"),NULL,NULL);
+              }
 
               /* Extract the summary from the webpage contents */
               preg_match('/<meta content="(.+?)\. \w+ \d+, \d+.*" name="description">/i',
@@ -169,9 +190,12 @@ class ItemAddEmbedVideo extends ItemAddPlugin {
               $summary=$matches[1];
 
               /* Extract the title from the webpage contents */
-              preg_match('/<title>(.+?)\s+- Google Video<\/title>/i',
-                         $contents, $matches);
-              $title=$matches[1];
+              $title="Unknown";
+              if(preg_match('/<title>(.+?)\s+- Google Video<\/title>/i', $contents, $matches)) {
+                $title=$matches[1];
+              } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
+                $title=$matches[1];
+              }
 
               /* Extract the thumbnail URL from the webpage contents */
               preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
@@ -183,7 +207,7 @@ class ItemAddEmbedVideo extends ItemAddPlugin {
               $description = '<embed FlashVars="autoPlay=true" ';
               $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
               $description.= 'type="application/x-shockwave-flash" ';
-              $description.= 'src="'.$googlePlayer.'"?docId='.$doc_id.'"> ';
+              $description.= 'src="'.$googlePlayer.'?docId='.$doc_id.'"> ';
               $description.= '</embed>';
               $description.= "<br>$summary";
         
@@ -213,22 +237,19 @@ class ItemAddEmbedVideo extends ItemAddPlugin {
                 * Check to make sure the URL to the remote flv file is valid
                * (That the file exists at the URL given)
                 */
-              if (empty($extraHeaders)) {
-                  $extraHeaders = array('Referer' => str_replace('&amp;', '&', $url));
-              }
               list ($successfullyCopied, $response, $headers) =
-                GalleryCoreApi::fetchWebPage($url, $extraHeaders);
+                $this->fetchWebFileHeaders($url, $extraHeaders);
               if (!$successfullyCopied) {
-                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
-                               "Unable to locate a video at url: $url"),null,null);
-              }                                            
+                return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
+                             "Unable to find the video at url: $url - $response"),NULL,NULL);
+              }
               
               /*
                 * Format the description to hold a reference to the embedded video
                * This reference will be embedded using the G2 internal player,
                * or an external player if provided by the user.
                 */
-              if(!$useInternalFlvPlayer) {
+              if(!strcmp($useInternalFlvPlayer,"false")) {
 
                   /*
                     * The user has indicated they want to use an external flv player
@@ -321,19 +342,16 @@ class ItemAddEmbedVideo extends ItemAddPlugin {
           $tmpFile = $platform->tempnam($tmpDir, 'add');
           $tmpFile.= ".jpg";
           
-          if($debugOutput) {
+          if(!strcmp($debugOutput,"true")) {
               print "thumbnail: $thumbnail <br>";
           }
           
           /* Fetch the thumbnail and save it to a local file */
-          if (empty($extraHeaders)) {
-              $extraHeaders = array('Referer' => str_replace('&amp;', '&', $url));
-          }
           list ($successfullyCopied, $response, $headers) =
             GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
           if (!$successfullyCopied) {
               return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
-                           "Unable to copy thumbnail from url: $url"),null,null);
+                           "Unable to copy thumbnail from url: $url - $response"),null,null);
           }
           
           /* Obtain the mimeType of the thumbnail */
@@ -347,13 +365,14 @@ class ItemAddEmbedVideo extends ItemAddPlugin {
           $fileName = preg_replace("/&#\d+;/","",$fileName);
           
           /* General debug output */
-          if($debugOutput) {
+          if(!strcmp($debugOutput,"true")) {
               print "<p><a href=\"".$title."\" target=\"_blank\">";
               print "<img src=\"".$thumbnail."\">\n</a>".$summary."</p>";
               print "<p>$description</p>";
               print "thumbnail: $tmpFile <br>";
               print "mimeType: $mimeType <br>";
               print "fileName: $fileName <br>";
+              print "<br><br><b>Video Successfully Added to your Gallery Album</b><br><br>";
           }
 
           /* Make the gallery2 call to add this item to the album */
@@ -379,6 +398,115 @@ class ItemAddEmbedVideo extends ItemAddPlugin {
    return array(null, $error, $status);
  }
 
+ /**
+  * A simple function to resolve the value of a parameter from
+  * the default or override value if it exists.
+  */
+ function getParameter($params, $name) {
+   if(isset($params['override'][$name])) {
+     return($params['override'][$name]);
+   } else {
+     return($params['default'][$name]);
+   }
+ }
+
+ /**
+  * A simple function to get the headers only (no body) for a given URL
+  *
+  */
+ function fetchWebFileHeaders($url, $requestHeaders=array()) {
+     global $gallery;
+     
+     $requestMethod='GET';
+
+     /* Convert illegal characters */
+     $url = str_replace(' ', '%20', $url);
+     
+     /* Unescape ampersands, since if the URL comes from form input it will be escaped */
+     $url = str_replace('&amp;', '&', $url);
+
+     $platform =& $gallery->getPlatform();
+     
+     $urlComponents = parse_url($url);
+     if (empty($urlComponents['port'])) {
+         $urlComponents['port'] = 80;
+     }
+     if (empty($urlComponents['path'])) {
+         $urlComponents['path'] = '/';
+     }
+
+     $handle = @$platform->fsockopen(
+                                    $urlComponents['host'], $urlComponents['port'], $errno, $errstr, 5);
+     if (empty($handle)) {
+         $gallery->debug("Error $errno: '$errstr' requesting $url");
+         return array(null, null, null);
+     }
+     
+     $requestUri = $urlComponents['path'];
+     if (!empty($urlComponents['query'])) {
+         $requestUri .= '?' . $urlComponents['query'];
+     }
+     $headerLines = array('Host: ' . $urlComponents['host']);
+     foreach ($requestHeaders as $key => $value) {
+         $headerLines[] = $key . ': ' . $value;
+     }
+     
+     $success = $platform->fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s",
+                                                  $requestMethod,
+                                                  $requestUri,
+                                                  implode("\r\n", $headerLines),
+                                                  $requestBody));
+     if (!$success) {
+         /* Zero bytes written or false was returned */
+         $gallery->debug(
+                        "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''));
+        return array(null, null, null);
+     }
+     $platform->fflush($handle);
+     
+     
+     /*
+      * Read the status line.  fgets stops after newlines.  The first line is the protocol
+      * version followed by a numeric status code and its associated textual phrase.
+      */
+     $responseStatus = trim($platform->fgets($handle, 4096));
+     if (empty($responseStatus)) {
+         $gallery->debug('Empty http response code, maybe timeout');
+         return array(null, null, null);
+     }
+     
+     /* Read the headers */
+     $responseHeaders = array();
+     while (!$platform->feof($handle)) {
+         $line = trim($platform->fgets($handle, 4096));
+         if (empty($line)) {
+            break;
+        }
+       
+        /* Normalize the line endings */
+        $line = str_replace("\r", '', $line);
+        
+        list ($key, $value) = explode(':', $line, 2);
+        if (isset($responseHeaders[$key])) {
+            if (!is_array($responseHeaders[$key])) {
+              $responseHeaders[$key] = array($responseHeaders[$key]);
+            }
+            $responseHeaders[$key][] = trim($value);
+        } else {
+            $responseHeaders[$key] = trim($value);
+        }
+     }
+     $platform->fclose($handle);
+
+     if(preg_match("/Not found/i", $responseStatus)) {
+         $success = 0;
+     }
+
+     //print "success: $success <br>responseStatus: $responseStatus <br>responseHeaders: $responseHeaders <br>";
+     
+     return array($success, $responseStatus, $responseHeaders);
+ }
  /**
   * @see ItemAdd:loadTemplate
   */
@@ -411,24 +539,6 @@ class ItemAddEmbedVideo extends ItemAddPlugin {
     
     return array(null, $module->translate('Embed Video'));
  }
-
-
- /**
-  * ItemAddEmbedVideo::_getFeed
-  */
- function _getFeed($feed) {
-  
-     /* Open and return Feed with cURL for parsing */
-    $ch = curl_init();
-    $timeout = 0;
-    curl_setopt ($ch, CURLOPT_URL, $feed);
-    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
-    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
-    $xml = curl_exec($ch);
-    curl_close($ch);
-    
-    return $xml;    
- }
  
 }      
 ?>