<?php

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

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

define('AUDIO_MAX_SIZE', 10*1000000);

function uploadaudio($lang, $arglist=false) {
	$maxfilesize=AUDIO_MAX_SIZE;

	$filetypes=array('audio/mpeg', 'audio/mp3', 'audio/ogg', 'video/ogg');

	$type=$data=false;
	$size=$offset=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=explode(';base64,', $_POST['file_data']);
		$data=is_array($data) && isset($data[1]) ? base64_decode($data[1]) : false;
	}

	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='sound';

	switch ($type) {
		case 'audio/mpeg':
		case 'audio/mp3':
			$fname = $name . '.mp3';
			break;
		case 'audio/ogg':
		case 'video/ogg':
			$fname = $name . '.ogg';
			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;
	}

	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;
}
