<?php

/**
 *
 * @copyright  2020-2023 objectivejs.org
 * @version    3
 * @link       http://www.objectivejs.org
 */

require_once 'validatefilename.php';
require_once 'models/wall.inc';

function wallupload($lang, $arglist=false) {
	if (!isset($_SESSION['wall_id'])) {
		goto badrequest;
	}

	$wall_id=$_SESSION['wall_id'];

	$maxfilesize=WALL_FILE_MAX_SIZE;
	$filetypes=WALL_FILE_TYPES;

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

	if (isset($_POST['file_name'])) {
		$name=$_POST['file_name'];
	}
	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 (!$name or !validate_filename($name)) {
		goto badrequest;
	}

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

	if (!is_numeric($offset) or $offset < 0) {
		goto badrequest;
	}

	if (!is_numeric($size) or $size < 0 or ($maxfilesize and $size > $maxfilesize)) {
		goto badrequest;
	}

	if (!$data) {
		goto badrequest;
	}

	$datasize=strlen($data);

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

	$file=wall_file($wall_id, $name);

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

	if (!wall_init_file($wall_id, $name, $file, $type)) {
		goto internalerror;
	}

	return false;

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

internalerror:
	@unlink($file);

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