<?php 
	include('../functions.php');
	include('../login/auth.php');
	
	//Init
	$app = isset($_GET['app']) && is_numeric($_GET['app']) ? mysqli_real_escape_string($mysqli, (int)$_GET['app']) : exit;
	$is_grapesjs_upload = isset($_FILES['files']) || (isset($_GET['response']) && $_GET['response']=='json');
	$files_key = $is_grapesjs_upload ? 'files' : 'upload';
	if(!isset($_FILES[$files_key])) exit;
	
	$time = time();
	$uploads_path = sendy_uploads_path($app, '', __DIR__.'/../../uploads', true);
	if(!is_writable($uploads_path))
		@chmod($uploads_path, 0777);
	if(!is_writable($uploads_path))
		sendy_upload_json_error(_('Unable to upload image. Please ensure the /uploads/ folder permission is set to 777.'));
	
	//get smtp settings
	$app_path = APP_PATH;
	$q = 'SELECT custom_domain, custom_domain_protocol, custom_domain_enabled FROM apps WHERE id = '.$app.' AND userID = '.get_app_info('main_userID').' LIMIT 1';
	$r = mysqli_query($mysqli, $q);
	if ($r && mysqli_num_rows($r) > 0)
	{
	    while($row = mysqli_fetch_array($r))
	    {
			$custom_domain = $row['custom_domain'];
			$custom_domain_protocol = $row['custom_domain_protocol'];
			$custom_domain_enabled = $row['custom_domain_enabled'];
			if($custom_domain!='' && $custom_domain_enabled)
			{
				$parse = parse_url(APP_PATH);
				$domain = $parse['host'];
				$protocol = $parse['scheme'];
				$app_path = str_replace($domain, $custom_domain, APP_PATH);
				$app_path = str_replace($protocol, $custom_domain_protocol, $app_path);
			}
			else $app_path = APP_PATH;
	    }  
	}
	else sendy_upload_json_error(_('Unable to upload image. Brand not found.'));
	
	if($is_grapesjs_upload)
	{
		$file_names = is_array($_FILES[$files_key]['name']) ? $_FILES[$files_key]['name'] : array($_FILES[$files_key]['name']);
		$file_tmps = is_array($_FILES[$files_key]['tmp_name']) ? $_FILES[$files_key]['tmp_name'] : array($_FILES[$files_key]['tmp_name']);
		$file_errors = is_array($_FILES[$files_key]['error']) ? $_FILES[$files_key]['error'] : array($_FILES[$files_key]['error']);
		$uploaded_assets = array();
		
		for($i=0;$i<count($file_names);$i++)
		{
			$file_name = $file_names[$i];
			$file = $file_tmps[$i];
			$file_error = isset($file_errors[$i]) ? (int)$file_errors[$i] : UPLOAD_ERR_OK;
			if($file_name=='' || $file=='') continue;
			if($file_error!==UPLOAD_ERR_OK) continue;
			
			$extension_explode = explode('.', $file_name);
			$extension = strtolower($extension_explode[count($extension_explode)-1]);
			$extension2 = count($extension_explode) > 1 ? strtolower($extension_explode[count($extension_explode)-2]) : '';
			if($extension2=='php' || $file_name=='.htaccess') continue;
			
			$allowed = array("jpeg", "jpg", "gif", "png", "webp");
			if(in_array($extension, $allowed) && sendy_upload_is_valid_image($file, $extension))
			{
				$upload_name = $time.'-'.ran_string(6, 6, false, false, true).'.'.$extension;
				if(move_uploaded_file($file, $uploads_path.'/'.$upload_name))
					$uploaded_assets[] = array('src' => sendy_uploads_url($app_path, $app, $upload_name));
			}
		}
		
		if(!count($uploaded_assets))
			sendy_upload_json_error(_('Please upload only these file formats: jpeg, jpg, gif, png or webp.'));
		
		header('Content-Type: application/json');
		echo json_encode(array('data' => $uploaded_assets));
	}
	else
	{
		$file = $_FILES[$files_key]['tmp_name'];
		$file_name = $_FILES[$files_key]['name'];
		$extension_explode = explode('.', $file_name);
		$extension = $extension_explode[count($extension_explode)-1];
		$extension2 = count($extension_explode) > 1 ? $extension_explode[count($extension_explode)-2] : '';
		if($extension2=='php' || $file_name=='.htaccess') exit;
		
		//Check filetype
		$allowed = array("jpeg", "jpg", "gif", "png");
		if(in_array(strtolower($extension), $allowed) && sendy_upload_is_valid_image($file, strtolower($extension))) //if file is an image, allow upload
		{
			//Upload file
			move_uploaded_file($file, $uploads_path.'/'.$time.'.'.$extension);
			
			// Required: anonymous function reference number as explained above.
			$funcNum = (int)$_GET['CKEditorFuncNum'] ;
			
			// Check the $_FILES array and save the file. Assign the correct path to a variable ($url).
			$url = sendy_uploads_url($app_path, $app, $time.'.'.$extension);
			// Usually you will only assign something here if the file could not be uploaded.
			$message = '';
			
			echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');</script>";
		}
		else exit;
	}

	function sendy_upload_is_valid_image($file, $extension)
	{
		if(!is_uploaded_file($file))
			return false;
		
		$image_info = @getimagesize($file);
		if($image_info===false || !isset($image_info['mime']))
			return false;
		
		$allowed_mimes = array(
			'jpeg' => array('image/jpeg'),
			'jpg' => array('image/jpeg'),
			'gif' => array('image/gif'),
			'png' => array('image/png'),
			'webp' => array('image/webp')
		);
		
		return isset($allowed_mimes[$extension]) && in_array($image_info['mime'], $allowed_mimes[$extension]);
	}
	
	function sendy_upload_json_error($message)
	{
		if(isset($_GET['response']) && $_GET['response']=='json')
		{
			header('Content-Type: application/json');
			http_response_code(400);
			echo json_encode(array('error' => $message));
			exit;
		}
		
		exit;
	}
?>
