<?php
/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

class WV_Uploader_Image extends WV_Uploader {
	const NO_IMAGE      = 5;
	const IMAGE_TOO_BIG = 6;

	protected $allowedFormats;
	protected $maxWidth;
	protected $maxHeight;

	public function __construct($formKey, $maxSize = 0, $allowedFormats = array('jpg', 'png', 'gif'), $allowedMimeTypes = array()) {
		parent::__construct($formKey, $maxSize, $allowedMimeTypes);
		$this->setFormats($allowedFormats);
		$this->setMaxDimensions(0, 0);
	}

	public function upload($destination) {
		$this->checkUploadConditions();

		$imageinfo = @getimagesize($this->getTempName()); // E_NOTICE / E_WARNING bei Lesefehlern bewusst ausblenden

		if (!$imageinfo) {
			throw new WV_Exception_Uploader(self::NO_IMAGE);
		}

		list($width, $height, $type) = $imageinfo;

		if (!in_array($type, $this->allowedFormats)) {
			throw new WV_Exception_Uploader(self::NO_IMAGE);
		}

		if ($this->maxWidth > 0 && $width > $this->maxWidth) {
			throw new WV_Exception_Uploader(self::IMAGE_TOO_BIG);
		}

		if ($this->maxHeight > 0 && $height > $this->maxHeight) {
			throw new WV_Exception_Uploader(self::IMAGE_TOO_BIG);
		}

		return $this->moveFile($destination);
	}

	public function setFormats($allowedFormats) {
		static $knownFormats = array(
			'gif'  => IMAGETYPE_GIF,
			'jpg'  => IMAGETYPE_JPEG,
			'jpeg' => IMAGETYPE_JPEG,
			'png'  => IMAGETYPE_PNG,
			'psd'  => IMAGETYPE_PSD,
			'tiff' => IMAGETYPE_TIFF_MM,
			'xbm'  => IMAGETYPE_XBM,
			'bmp'  => IMAGETYPE_BMP
		);

		$this->allowedFormats = array();
		$allowedFormats       = sly_makeArray($allowedFormats);

		foreach ($allowedFormats as $format) {
			$format = trim(strtolower($format));

			if ($format[0] == '.') {
				$format = substr($format, 1);
			}

			if (isset($knownFormats[$format])) {
				$this->allowedFormats[] = $knownFormats[$format];
			}
		}

		return count($this->allowedFormats);
	}

	public function setMaxDimensions($width, $height) {
		return $this->setMaxWidth($width) && $this->setMaxHeight($height);
	}

	public function setMaxWidth($width) {
		$this->maxWidth = abs(intval($width));
		return true;
	}

	public function setMaxheight($height) {
		$this->maxHeight = abs(intval($height));
		return true;
	}
}
