]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - lib/imagefile.php
Changed thumbnail-only chmod to attachment-general chmod as recommended by mmn.
[quix0rs-gnu-social.git] / lib / imagefile.php
index 535afaacb678ff58d4d932bf05bf88b774a97453..926617e6a26df9ff5c9dd8463e787c4725944e5a 100644 (file)
@@ -47,27 +47,27 @@ class ImageFile
 {
     var $id;
     var $filepath;
-    var $barename;
+    var $filename;
     var $type;
     var $height;
     var $width;
     var $rotate=0;  // degrees to rotate for properly oriented image (extrapolated from EXIF etc.)
-    var $animated = false;  // Animated image? (has more than 2 frames)
+    var $animated = null;  // Animated image? (has more than 1 frame). null means untested
 
     function __construct($id=null, $filepath=null, $type=null, $width=null, $height=null)
     {
         $this->id = $id;
         $this->filepath = $filepath;
+        $this->filename = basename($filepath);
 
         $info = @getimagesize($this->filepath);
 
-        if (!(
-            ($info[2] == IMAGETYPE_GIF && function_exists('imagecreatefromgif')) ||
-            ($info[2] == IMAGETYPE_JPEG && function_exists('imagecreatefromjpeg')) ||
-            $info[2] == IMAGETYPE_BMP ||
-            ($info[2] == IMAGETYPE_WBMP && function_exists('imagecreatefromwbmp')) ||
-            ($info[2] == IMAGETYPE_XBM && function_exists('imagecreatefromxbm')) ||
-            ($info[2] == IMAGETYPE_PNG && function_exists('imagecreatefrompng')))) {
+        if (
+            ($info[2] == IMAGETYPE_GIF && !function_exists('imagecreatefromgif')) ||
+            ($info[2] == IMAGETYPE_JPEG && !function_exists('imagecreatefromjpeg')) ||
+            ($info[2] == IMAGETYPE_WBMP && !function_exists('imagecreatefromwbmp')) ||
+            ($info[2] == IMAGETYPE_XBM && !function_exists('imagecreatefromxbm')) ||
+            ($info[2] == IMAGETYPE_PNG && !function_exists('imagecreatefrompng'))) {
 
             // TRANS: Exception thrown when trying to upload an unsupported image file format.
             throw new UnsupportedMediaException(_('Unsupported image format.'), $this->filepath);
@@ -97,6 +97,8 @@ class ImageFile
                 }
                 // If we ever write this back, Orientation should be set to '1'
             }
+        } elseif ($this->type === IMAGETYPE_GIF) {
+            $this->animated = $this->isAnimatedGif();
         }
 
         Event::handle('FillImageFileMetadata', array($this));
@@ -107,6 +109,9 @@ class ImageFile
         $imgPath = null;
         $media = common_get_mime_media($file->mimetype);
         if (Event::handle('CreateFileImageThumbnailSource', array($file, &$imgPath, $media))) {
+            if (empty($file->filename)) {
+                throw new UnsupportedMediaException(_('File without filename could not get a thumbnail source.'));
+            }
             switch ($media) {
             case 'image':
                 $imgPath = $file->getPath();
@@ -204,16 +209,16 @@ class ImageFile
 
     /**
      * Copy the image file to the given destination.
-     * For obscure formats, this will automatically convert to PNG;
-     * otherwise the original file will be copied as-is.
+     *
+     * This function may modify the resulting file. Please use the
+     * returned ImageFile object to read metadata (width, height etc.)
      *
      * @param string $outpath
-     * @return string filename
+     * @return ImageFile the image stored at target path
      */
     function copyTo($outpath)
     {
-        return $this->resizeTo($outpath, array('width' =>$this->width,
-                                               'height'=>$this->height));
+        return new ImageFile(null, $this->resizeTo($outpath));
     }
 
     /**
@@ -232,38 +237,50 @@ class ImageFile
         $box['w'] = isset($box['w']) ? intval($box['w']) : $this->width;
         $box['h'] = isset($box['h']) ? intval($box['h']) : $this->height;
 
-        // Doublecheck that parameters are sane and integers.
-        if ($box['width'] < 1 || $box['width'] > common_config('thumbnail', 'maxsize')
-                || $box['height'] < 1 || $box['height'] > common_config('thumbnail', 'maxsize')
-                || $box['w'] < 1 || $box['x'] >= $this->width
-                || $box['h'] < 1 || $box['y'] >= $this->height) {
-            // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile->scaleToFit
-            common_debug("Boundary box parameters for resize of {$this->filepath} : ".var_export($box,true));
-            throw new ServerException('Bad thumbnail size parameters.');
-        }
-
         if (!file_exists($this->filepath)) {
             // TRANS: Exception thrown during resize when image has been registered as present, but is no longer there.
             throw new Exception(_('Lost our file.'));
         }
 
-        // Don't crop/scale if it isn't necessary
+        // Don't rotate/crop/scale if it isn't necessary
         if ($box['width'] === $this->width
-            && $box['height'] === $this->height
-            && $box['x'] === 0
-            && $box['y'] === 0
-            && $box['w'] === $this->width
-            && $box['h'] === $this->height
-            && $this->type == $this->preferredType()) {
-
-            @copy($this->filepath, $outpath);
-            return $outpath;
+                && $box['height'] === $this->height
+                && $box['x'] === 0
+                && $box['y'] === 0
+                && $box['w'] === $this->width
+                && $box['h'] === $this->height
+                && $this->type == $this->preferredType()) {
+            if ($this->rotate == 0) {
+                // No rotational difference, just copy it as-is
+                @copy($this->filepath, $outpath);
+
+                // And set chmod
+                @chmod($outpath, common_config('attachments', 'chmod');
+                return $outpath;
+            } elseif (abs($this->rotate) == 90) {
+                // Box is rotated 90 degrees in either direction,
+                // so we have to redefine x to y and vice versa.
+                $tmp = $box['width'];
+                $box['width'] = $box['height'];
+                $box['height'] = $tmp;
+                $tmp = $box['x'];
+                $box['x'] = $box['y'];
+                $box['y'] = $tmp;
+                $tmp = $box['w'];
+                $box['w'] = $box['h'];
+                $box['h'] = $tmp;
+            }
         }
 
+
         if (Event::handle('StartResizeImageFile', array($this, $outpath, $box))) {
             $this->resizeToFile($outpath, $box);
         }
 
+        if (!file_exists($outpath)) {
+            throw new UseFileAsThumbnailException($this->id);
+        }
+
         return $outpath;
     }
 
@@ -337,6 +354,9 @@ class ImageFile
             throw new Exception(_('Unknown file type'));
         }
 
+        // Always chmod 0644 (default) to have other processes (e.g. queue daemon read it)
+        @chmod($outpath, common_config('attachments', 'chmod');
+
         imagedestroy($image_src);
         imagedestroy($image_dest);
     }
@@ -490,6 +510,41 @@ class ImageFile
                     is_null($cw) ? $width : intval($cw),
                     is_null($ch) ? $height : intval($ch));
     }
+
+    /**
+     * Animated GIF test, courtesy of frank at huddler dot com et al:
+     * http://php.net/manual/en/function.imagecreatefromgif.php#104473
+     * Modified so avoid landing inside of a header (and thus not matching our regexp).
+     */
+    protected function isAnimatedGif()
+    {
+        if (!($fh = @fopen($this->filepath, 'rb'))) {
+            return false;
+        }
+
+        $count = 0;
+        //an animated gif contains multiple "frames", with each frame having a
+        //header made up of:
+        // * a static 4-byte sequence (\x00\x21\xF9\x04)
+        // * 4 variable bytes
+        // * a static 2-byte sequence (\x00\x2C)
+        // In total the header is maximum 10 bytes.
+
+        // We read through the file til we reach the end of the file, or we've found
+        // at least 2 frame headers
+        while(!feof($fh) && $count < 2) {
+            $chunk = fread($fh, 1024 * 100); //read 100kb at a time
+            $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
+            // rewind in case we ended up in the middle of the header, but avoid
+            // infinite loop (i.e. don't rewind if we're already in the end).
+            if (!feof($fh) && ftell($fh) >= 9) {
+                fseek($fh, -9, SEEK_CUR);
+            }
+        }
+
+        fclose($fh);
+        return $count > 1;
+    }
 }
 
 //PHP doesn't (as of 2/24/2010) have an imagecreatefrombmp so conditionally define one