rcube_image.php 17.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
<?php

/**
 +-----------------------------------------------------------------------+
 | This file is part of the Roundcube Webmail client                     |
 |                                                                       |
 | Copyright (C) The Roundcube Dev Team                                  |
 | Copyright (C) Kolab Systems AG                                        |
 |                                                                       |
 | Licensed under the GNU General Public License version 3 or            |
 | any later version with exceptions for skins & plugins.                |
 | See the README file for a full license statement.                     |
 |                                                                       |
 | PURPOSE:                                                              |
 |   Image resizer and converter                                         |
 +-----------------------------------------------------------------------+
 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
 | Author: Aleksander Machniak <alec@alec.pl>                            |
 +-----------------------------------------------------------------------+
*/

/**
 * Image resizer and converter
 *
 * @package    Framework
 * @subpackage Utils
 */
class rcube_image
{
    const TYPE_GIF = 1;
    const TYPE_JPG = 2;
    const TYPE_PNG = 3;
    const TYPE_TIF = 4;

    /** @var array Image file type to extension map */
    public static $extensions = [
        self::TYPE_GIF => 'gif',
        self::TYPE_JPG => 'jpg',
        self::TYPE_PNG => 'png',
        self::TYPE_TIF => 'tif',
    ];

    /** @var string Image file location */
    private $image_file;


    /**
     * Class constructor
     *
     * @param string $filename Image file name/path
     */
    function __construct($filename)
    {
        $this->image_file = $filename;
    }

    /**
     * Get image properties.
     *
     * @return array|null Hash array with image props like type, width, height
     */
    public function props()
    {
        $gd_type  = null;
        $channels = null;
        $width    = null;
        $height   = null;

        // use GD extension
        if (function_exists('getimagesize') && ($imsize = @getimagesize($this->image_file))) {
            $width   = $imsize[0];
            $height  = $imsize[1];
            $gd_type = $imsize[2];
            $type    = image_type_to_extension($gd_type, false);

            if (isset($imsize['channels'])) {
                $channels = $imsize['channels'];
            }
        }

        // use ImageMagick
        if (empty($type) && ($data = $this->identify())) {
            list($type, $width, $height) = $data;
            $channels = null;
        }

        if (!empty($type)) {
            return [
                'type'     => $type,
                'gd_type'  => $gd_type,
                'width'    => $width,
                'height'   => $height,
                'channels' => $channels,
            ];
        }
    }

    /**
     * Resize image to a given size. Use only to shrink an image.
     * If an image is smaller than specified size it will be not resized.
     *
     * @param int    $size           Max width/height size
     * @param string $filename       Output filename
     * @param bool   $browser_compat Convert to image type displayable by any browser
     *
     * @return string|false Output type on success, False on failure
     */
    public function resize($size, $filename = null, $browser_compat = false)
    {
        $result  = false;
        $rcube   = rcube::get_instance();
        $convert = self::getCommand('im_convert_path');
        $props   = $this->props();

        if (empty($props)) {
            return false;
        }

        if (!$filename) {
            $filename = $this->image_file;
        }

        // use Imagemagick
        if ($convert || class_exists('Imagick', false)) {
            $p['out'] = $filename;
            $p['in']  = $this->image_file;
            $type     = $props['type'];

            if (!$type && ($data = $this->identify())) {
                $type = $data[0];
            }

            $type = strtr($type, ["jpeg" => "jpg", "tiff" => "tif", "ps" => "eps", "ept" => "eps"]);
            $p['intype'] = $type;

            // convert to an image format every browser can display
            if ($browser_compat && !in_array($type, ['jpg', 'gif', 'png'])) {
                $type = 'jpg';
            }

            // If only one dimension is greater than the limit convert doesn't
            // work as expected, we need to calculate new dimensions
            $scale = $size / max($props['width'], $props['height']);

            // if file is smaller than the limit, we do nothing
            // but copy original file to destination file
            if ($scale >= 1 && $p['intype'] == $type) {
                $result = ($this->image_file == $filename || copy($this->image_file, $filename)) ? '' : false;
            }
            else {
                $valid_types = "bmp,eps,gif,jp2,jpg,png,svg,tif";

                if (in_array($type, explode(',', $valid_types))) { // Valid type?
                    if ($scale >= 1) {
                        $width  = $props['width'];
                        $height = $props['height'];
                    }
                    else {
                        $width  = intval($props['width']  * $scale);
                        $height = intval($props['height'] * $scale);
                    }

                    // use ImageMagick in command line
                    if ($convert) {
                        $p += [
                            'type'    => $type,
                            'quality' => 75,
                            'size'    => $width . 'x' . $height,
                        ];

                        $result = rcube::exec($convert
                            . ' 2>&1 -flatten -auto-orient -colorspace sRGB -strip'
                            . ' -quality {quality} -resize {size} {intype}:{in} {type}:{out}', $p);
                    }
                    // use PHP's Imagick class
                    else {
                        try {
                            $image = new Imagick($this->image_file);

                            try {
                                // it throws exception on formats not supporting these features
                                $image->setImageBackgroundColor('white');
                                $image->setImageAlphaChannel(11);
                                $image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
                            }
                            catch (Exception $e) {
                                // ignore errors
                            }

                            $image->setImageColorspace(Imagick::COLORSPACE_SRGB);
                            $image->setImageCompressionQuality(75);
                            $image->setImageFormat($type);
                            $image->stripImage();
                            $image->scaleImage($width, $height);

                            if ($image->writeImage($filename)) {
                                $result = '';
                            }
                        }
                        catch (Exception $e) {
                            rcube::raise_error($e, true, false);
                        }
                    }
                }
            }

            if ($result === '') {
                @chmod($filename, 0600);
                return $type;
            }
        }

        // do we have enough memory? (#1489937)
        if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' && !$this->mem_check($props)) {
            return false;
        }

        // use GD extension
        if ($props['gd_type']) {
            if ($props['gd_type'] == IMAGETYPE_JPEG && function_exists('imagecreatefromjpeg')) {
                $image = imagecreatefromjpeg($this->image_file);
                $type  = 'jpg';
            }
            else if ($props['gd_type'] == IMAGETYPE_GIF && function_exists('imagecreatefromgif')) {
                $image = imagecreatefromgif($this->image_file);
                $type  = 'gif';
            }
            else if ($props['gd_type'] == IMAGETYPE_PNG && function_exists('imagecreatefrompng')) {
                $image = imagecreatefrompng($this->image_file);
                $type  = 'png';
            }
            else {
                // @TODO: print error to the log?
                return false;
            }

            if ($image === false) {
                return false;
            }

            $scale = $size / max($props['width'], $props['height']);

            // Imagemagick resize is implemented in shrinking mode (see -resize argument above)
            // we do the same here, if an image is smaller than specified size
            // we do nothing but copy original file to destination file
            if ($scale >= 1) {
                $result = $this->image_file == $filename || copy($this->image_file, $filename);
            }
            else {
                $width     = intval($props['width']  * $scale);
                $height    = intval($props['height'] * $scale);
                $new_image = imagecreatetruecolor($width, $height);

                if ($new_image === false) {
                    return false;
                }

                // Fix transparency of gif/png image
                if ($props['gd_type'] != IMAGETYPE_JPEG) {
                    imagealphablending($new_image, false);
                    imagesavealpha($new_image, true);
                    $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
                    imagefilledrectangle($new_image, 0, 0, $width, $height, $transparent);
                }

                imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, $props['width'], $props['height']);
                $image = $new_image;

                // fix orientation of image if EXIF data exists and specifies orientation (GD strips the EXIF data)
                if ($this->image_file && $type == 'jpg' && function_exists('exif_read_data')) {
                    $exif = @exif_read_data($this->image_file);
                    if ($exif && !empty($exif['Orientation'])) {
                        switch ($exif['Orientation']) {
                            case 3:
                                $image = imagerotate($image, 180, 0);
                                break;
                            case 6:
                                $image = imagerotate($image, -90, 0);
                                break;
                            case 8:
                                $image = imagerotate($image, 90, 0);
                                break;
                        }
                    }
                }

                if ($props['gd_type'] == IMAGETYPE_JPEG) {
                    $result = imagejpeg($image, $filename, 75);
                }
                elseif($props['gd_type'] == IMAGETYPE_GIF) {
                    $result = imagegif($image, $filename);
                }
                elseif($props['gd_type'] == IMAGETYPE_PNG) {
                    $result = imagepng($image, $filename, 6, PNG_ALL_FILTERS);
                }
            }

            if ($result) {
                @chmod($filename, 0600);
                return $type;
            }
        }

        // @TODO: print error to the log?
        return false;
    }

    /**
     * Convert image to a given type
     *
     * @param int    $type     Destination file type (see class constants)
     * @param string $filename Output filename (if empty, original file will be used
     *                         and filename extension will be modified)
     *
     * @return bool True on success, False on failure
     */
    public function convert($type, $filename = null)
    {
        $rcube   = rcube::get_instance();
        $convert = self::getCommand('im_convert_path');

        if (!$filename) {
            $filename = $this->image_file;

            // modify extension
            if ($extension = self::$extensions[$type]) {
                $filename = preg_replace('/\.[^.]+$/', '', $filename) . '.' . $extension;
            }
        }

        // use ImageMagick in command line
        if ($convert) {
            $p['in']   = $this->image_file;
            $p['out']  = $filename;
            $p['type'] = self::$extensions[$type];

            $result = rcube::exec($convert . ' 2>&1 -colorspace sRGB -strip -flatten -quality 75 {in} {type}:{out}', $p);

            if ($result === '') {
                chmod($filename, 0600);
                return true;
            }
        }

        // use PHP's Imagick class
        if (class_exists('Imagick', false)) {
            try {
                $image = new Imagick($this->image_file);

                $image->setImageColorspace(Imagick::COLORSPACE_SRGB);
                $image->setImageCompressionQuality(75);
                $image->setImageFormat(self::$extensions[$type]);
                $image->stripImage();

                if ($image->writeImage($filename)) {
                    @chmod($filename, 0600);
                    return true;
                }
            }
            catch (Exception $e) {
                rcube::raise_error($e, true, false);
            }
        }

        // use GD extension (TIFF isn't supported)
        $props = $this->props();

        // do we have enough memory? (#1489937)
        if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' && !$this->mem_check($props)) {
            return false;
        }

        if ($props['gd_type']) {
            if ($props['gd_type'] == IMAGETYPE_JPEG && function_exists('imagecreatefromjpeg')) {
                $image = imagecreatefromjpeg($this->image_file);
            }
            else if ($props['gd_type'] == IMAGETYPE_GIF && function_exists('imagecreatefromgif')) {
                $image = imagecreatefromgif($this->image_file);
            }
            else if ($props['gd_type'] == IMAGETYPE_PNG && function_exists('imagecreatefrompng')) {
                $image = imagecreatefrompng($this->image_file);
            }
            else {
                // @TODO: print error to the log?
                return false;
            }

            if ($type == self::TYPE_JPG) {
                $result = imagejpeg($image, $filename, 75);
            }
            else if ($type == self::TYPE_GIF) {
                $result = imagegif($image, $filename);
            }
            else if ($type == self::TYPE_PNG) {
                $result = imagepng($image, $filename, 6, PNG_ALL_FILTERS);
            }

            if (!empty($result)) {
                @chmod($filename, 0600);
                return true;
            }
        }

        // @TODO: print error to the log?
        return false;
    }

    /**
     * Checks if image format conversion is supported (for specified mimetype).
     *
     * @param string $mimetype Mimetype name
     *
     * @return bool True if specified format can be converted to another format
     */
    public static function is_convertable($mimetype = null)
    {
        $rcube = rcube::get_instance();

        // @TODO: check if specified mimetype is really supported
        return class_exists('Imagick', false) || self::getCommand('im_convert_path');
    }

    /**
     * ImageMagick based image properties read.
     */
    private function identify()
    {
        $rcube = rcube::get_instance();

        // use ImageMagick in command line
        if ($cmd = self::getCommand('im_identify_path')) {
            $args = ['in' => $this->image_file, 'format' => "%m %[fx:w] %[fx:h]"];
            $id   = rcube::exec($cmd . ' 2>/dev/null -format {format} {in}', $args);

            if ($id) {
                return explode(' ', strtolower($id));
            }
        }

        // use PHP's Imagick class
        if (class_exists('Imagick', false)) {
            try {
                $image = new Imagick($this->image_file);

                return [
                    strtolower($image->getImageFormat()),
                    $image->getImageWidth(),
                    $image->getImageHeight(),
                ];
            }
            catch (Exception $e) {
                // ignore
            }
        }
    }

    /**
     * Check if we have enough memory to load specified image
     *
     * @param array Hash array with image props like channels, width, height
     *
     * @return bool True if there's enough memory to process the image, False otherwise
     */
    private function mem_check($props)
    {
        // image size is unknown, we can't calculate required memory
        if (!$props['width']) {
            return true;
        }

        // channels: CMYK - 4, RGB - 3
        $multip = ($props['channels'] ?: 3) + 1;

        // calculate image size in memory (in bytes)
        $size = $props['width'] * $props['height'] * $multip;

        return rcube_utils::mem_check($size);
    }

    /**
     * Get the configured command and make sure it is safe to use.
     * We cannot trust configuration, and escapeshellcmd() is useless.
     *
     * @param string $opt_name Configuration option name
     *
     * @return bool|string The command or False if not set or invalid
     */
    private static function getCommand($opt_name)
    {
        static $error = [];

        $cmd = rcube::get_instance()->config->get($opt_name);

        if (empty($cmd)) {
            return false;
        }

        if (preg_match('/^(convert|identify)(\.exe)?$/i', $cmd)) {
            return $cmd;
        }

        // Executable must exist, also disallow network shares on Windows
        if ($cmd[0] != "\\" && file_exists($cmd)) {
            return $cmd;
        }

        if (empty($error[$opt_name])) {
            rcube::raise_error("Invalid $opt_name: $cmd", true, false);
            $error[$opt_name] = true;
        }

        return false;
    }
}