<?php

require_once (__DIR__.'/util.php');

use Vn\Lib;
use Vn\Lib\UserException;

/**
 * Uploads a file creating its corresponding sizes.
 **/
class Upload extends Vn\Web\JsonRequest
{
	function run ($db)
	{
		$util = new Util ($this->app);

		// Checks schema.
		
		$regexp = '/[^a-z0-9_]/';

		if (empty ($_REQUEST['schema']) || preg_match ($regexp, $_REQUEST['schema']) !== 0)
			throw new UserException (s('BadSchemaName'), 'badSchemaName');

		$schema = $_REQUEST['schema'];
		$info = $util->loadInfo ($schema);
		
		if (!$info)
			throw new UserException (s('SchemaNotExists'), 'schemaNotExists');

		// Checks file name and identifier.

		$query = sprintf (
			'SHOW INDEX FROM `%1$s`.`%2$s` WHERE Key_name = \'PRIMARY\''
			,$info['schema']
			,$info['table']
		);				
		$pk = $db->getRow ($query);

		if (!empty ($_REQUEST['id']) && empty ($_REQUEST['name']))
		{
			$query = sprintf (
				'SELECT `%3$s` FROM `%1$s`.`%2$s` WHERE `%4$s` = #id'
				,$info['schema']
				,$info['table']
				,$info['column']
				,$pk['Column_name']
			);
			$_REQUEST['name'] = $db->getValue ($query,
				['id' => $_REQUEST['id']]);
		}

		if (empty ($_REQUEST['name']) || preg_match ($regexp, $_REQUEST['name']) !== 0)
			throw new UserException (s('BadFileName'), 'badFileName');

		// Checks permissions.
		
		if (!empty ($_REQUEST['id']))
		{
			$filterColumn = $pk['Column_name'];
			$filterValue = $_REQUEST['id'];
		}
		else
		{
			$filterColumn = $info['column'];
			$filterValue = $_REQUEST['name'];
		}

		$query = sprintf (
			'UPDATE `%1$s`.`%2$s` SET `%3$s` = #name WHERE `%4$s` = #filter LIMIT 1'
			,$info['schema']
			,$info['table']
			,$info['column']
			,$filterColumn
		);
		$params = [
			'name' => $_REQUEST['name'],
			'filter' => $filterValue
		];
		
		if (!$db->query ($query, $params))
			throw new UserException (s('PermissionDenied'), 'permissionDenied');
		
		// Checks for file errors.
		
		if (empty ($_FILES['image']['name']))
			throw new UserException (s('FileNotChoosed'), 'fileNotChoosed');

		if ($_FILES['image']['error'] != 0)
		{
			switch ($_FILES['image']['error'])
			{
		        case UPLOAD_ERR_INI_SIZE:
		            $message = 'ErrIniSize';
		            break;
		        case UPLOAD_ERR_FORM_SIZE:
		            $message = 'ErrFormSize';
		            break;
		        case UPLOAD_ERR_PARTIAL:
		            $message = 'ErrPartial';
		            break;
		        case UPLOAD_ERR_NO_FILE:
		            $message = 'ErrNoFile';
		            break;
		        case UPLOAD_ERR_NO_TMP_DIR:
		            $message = 'ErrNoTmpDir';
		            break;
		        case UPLOAD_ERR_CANT_WRITE:
		            $message = 'ErrCantWrite';
		            break;
		        case UPLOAD_ERR_EXTENSION:
		            $message = 'ErrExtension';
		            break;
		        default:
		            $message = 'ErrDefault';
		            break;
		    }

			throw new Lib\Exception (s($message), 'uploadError');
		}
		
		$maxSize = $db->getValue ('SELECT max_size FROM image_config');

		if ($_FILES['image']['size'] > $maxSize * 1048576)
			throw new UserException (sprintf (s('FileSizeError'), $maxSize), 'fileSizeError');

		// Resizes and saves the image.

		$fileName = "{$_REQUEST['name']}.png";
		$schemaPath = "{$util->dataDir}/$schema";
		$fullFile = "$schemaPath/full/$fileName";
		$symbolicSrc = "../full/$fileName";
	
		$image = Image::create ($_FILES['image']['tmp_name']);
		Image::resizeSave ($image, $fullFile, $info['max_height'], $info['max_width']);

		foreach ($info['sizes'] as $size => $i)
		{
			$dstFile = "$schemaPath/$size/$fileName";
			Image::resizeSave ($image, $dstFile, $i['height'], $i['width'], $i['crop'], $symbolicSrc);
		}

		imagedestroy ($image);
		unlink ($_FILES['image']['tmp_name']);
		return TRUE;
	}
}

?>
