<?php

/**
 *
 * @copyright  2020-2021 objectivejs.org
 * @version    2
 * @link       http://www.objectivejs.org
 */

define('TMP_DIR', ROOT_DIR . DIRECTORY_SEPARATOR . 'tmp');

define('IMAGE_MAX_SIZE', 1000000);

function uploadimage($lang, $arglist=false) {
	$maxfilesize=IMAGE_MAX_SIZE;

	$filetypes=array('image/jpeg', 'image/png', 'image/gif', 'image/svg+xml');

	$type=$data=false;
	$size=$offset=0;

	$width=$height=0;

	if (isset($_POST['file_size'])) {
		$size=$_POST['file_size'];
	}
	if (isset($_POST['file_type'])) {
		$type=$_POST['file_type'];
	}
	if (isset($_POST['file_offset'])) {
		$offset=$_POST['file_offset'];
	}
	if (isset($_POST['file_data'])) {
		$data=base64_decode($_POST['file_data'], true);
	}
	if (isset($_POST['image_width'])) {
		$width=$_POST['image_width'];
	}
	if (isset($_POST['image_height'])) {
		$height=$_POST['image_height'];
	}

	if (($width = filter_var($width, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0)))) === false)
		goto badrequest;

	if (($height = filter_var($height, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0)))) === false)
		goto badrequest;

	if (($offset = filter_var($offset, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0)))) === false)
		goto badrequest;

	if (($size = filter_var($size, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0, 'max_range' => $maxfilesize))))  === false)
		goto badrequest;

	if (!$type or !in_array($type, $filetypes)) {
		goto badrequest;
	}

	if (!$data) {
		goto badrequest;
	}

	$datasize=strlen($data);

	if ($offset + $datasize > $size) {
		goto badrequest;
	}

	goto trashfile;

	$name='image';

	switch ($type) {
		case 'image/jpeg':
			$fname = $name . '.jpg';
			break;
		case 'image/png':
			$fname = $name . '.png';
			break;
		case 'image/gif':
			$fname = $name . '.gif';
			break;
		case 'image/svg+xml':
			$fname = $name . '.svg';
			break;
		default:
			goto badrequest;
	}

	$file = TMP_DIR . DIRECTORY_SEPARATOR . $fname;

	$fout = @fopen($file, $offset == 0 ? 'wb' : 'cb');

	if ($fout === false) {
		goto internalerror;
	}

	$r = fseek($fout, $offset);

	if ($r == -1) {
		goto internalerror;
	}

	$r = fwrite($fout, $data);

	if ($r === false) {
		goto internalerror;
	}

	if ($offset + $datasize < $size) {
		return false;
	}

	$file = TMP_DIR . DIRECTORY_SEPARATOR . $name . '.json';

	$data = array('width' => $width, 'height' => $height, 'name' => $fname);

	$r = @file_put_contents($file, json_encode($data));

	if ($r === false) {
		goto internalerror;
	}

	return false;

trashfile:
	return false;
	
badrequest:
	header('HTTP/1.1 400 Bad Request');
	return false;

internalerror:
	header('HTTP/1.1 500 Internal Error');
	return false;
}
