<?php
/* PageCookery Framework
*
* Author: Explon
*
* Copyright (C) 2009 Explon <explon@gmail.com>
*/

class Upload
{
	
	/**
	 * Upload a file
	 *
	 * @param array $data $_FILES['field name']
	 * @param string $saveto Save to a directory (if directory not exists, it's will auto create it)
	 * @param string $allowtype allow file type, use comma split multiple type
	 * @param string $assign_name if this value is string, file will save with this filename, else will auto create a filename
	 * @return string return saved filename or error code
	 */
	
	 /*
		Error Code:

		-1: file type is disallow
		-2: upload failed
	*/
	
	static function Save($data = array(), $saveto = '', $allowtype = 'jpg,gif,png', $assign_name = false)
	{
		$ext = Helper::GetFileExt($data['name']);
		
		if ($ext == 'jpg' OR $ext == 'gif' OR $ext == 'png')
		{
			if (!self::IsImage($data['tmp_name']))
			{
				return '-1';
			}
		}
			
		if ($allowtype != '*')
		{
			$allow_ext = explode(',', $allowtype);
			
			if (!in_array($ext, $allow_ext))
			{
				return '-1';
			}
		}
		
		$saveto_array = explode('/', str_replace('./', '', $saveto));
		
		foreach ($saveto_array AS $dir)
		{
			$_mkdir .= $dir . '/';

			@mkdir($_mkdir, 0777);
		}
		
		if ($assign_name)
		{
			$filename = $assign_name;
		}
		else
		{
			$filename = md5(microtime() . rand(1, 99999999)) . '.' . $ext;
		}
		
		if (file_exists($saveto . $filename))
		{
			@unlink($saveto . $filename);
		}
		
		if (!move_uploaded_file($data['tmp_name'], $saveto . $filename))
		{
			return '-2';
		}
		
		return $filename;
	}
	
	/**
	 * Check file is or not an image
	 *
	 * @param string $location image file location
	 * @return bool
	 */
	
	static function IsImage($location)
	{
		$imageinfo = @getimagesize($location);

		if (!is_array($imageinfo))
		{
			return false;
		}
		else if ($imageinfo[2] == 2 OR $imageinfo[2] == 1 OR $imageinfo[2] == 3)
		{
			return true;
		}
		
		return false;
	}
}
