<?php
	/**
	* Upload Attachment
	* This file is used to upload an file.
	*/
	// required to handle php errors
	require_once("server/exceptions/class.ZarafaErrorException.php");
	// required to send data in JSON
	require_once("server/core/class.json.php");
	// Include backwards compatibility
	require_once("server/sys_get_temp_dir.php");

	// Get Attachment data from state
	$attachment_state = new AttachmentState();
	$attachment_state->open();

	try {
		$newfiles = Array();

		// Check if dialog_attachments is set
		if(isset($_REQUEST["dialog_attachments"])) {
			// Check if attachments have been uploaded
			if(isset($_FILES["attachments"]) && is_array($_FILES["attachments"])) {
				$FILES = Array();

				if(isset($_FILES['attachments']['name']) && is_array($_FILES['attachments']['name'])){
					// Parse all information from the updated files,
					// validate the contents and add it to the $FILES array.
					foreach($_FILES['attachments']['name'] as $key => $name){
						$FILE = Array(
							'name'     => $_FILES['attachments']['name'][$key],
							'type'     => $_FILES['attachments']['type'][$key],
							'tmp_name' => $_FILES['attachments']['tmp_name'][$key],
							'error'    => $_FILES['attachments']['error'][$key],
							'size'     => $_FILES['attachments']['size'][$key]
						);

						/**
						 * check content type that is send by browser because content type for
						 * eml attachments will be message/rfc822, but this content type is used 
						 * for message-in-message embedded objects, so we have to send it as 
						 * application/octet-stream.
						 */
						if ($FILE["type"] == "message/rfc822") {
							$FILE["type"] = "application/octet-stream";
						}

						// validate the FILE object to see if the size doesn't exceed
						// the configured MAX_FILE_SIZE
						if (!empty($FILE['size']) && !(isset($_POST["MAX_FILE_SIZE"]) && $FILE["size"] > $_POST["MAX_FILE_SIZE"])) {
							$FILES[] = $FILE;
						}
					}
				}

				// Go over all files and register them
				foreach($FILES as $FILE) {
					// Parse the filename, strip it from
					// any illegal characters.
					$filename = basename(stripslashes($FILE["name"]));

					// Move the uploaded file into the attachment state
					$attachid = $attachment_state->addUploadedAttachmentFile($_REQUEST["dialog_attachments"], $filename, $FILE["tmp_name"], array(
						"name"       => $filename,
						"size"       => $FILE["size"],
						"type"       => $FILE["type"],
						"sourcetype" => 'default'
					));

					$newfiles[] = $attachid;
				}
			} else if(isset($_POST["deleteattachment"]) && isset($_POST["type"])) { // Delete uploaded file
				// Parse the filename, strip it from
				// any illegal characters
				$filename = basename(stripslashes(urldecode($_POST["deleteattachment"])));

				// Check if the delete file is an uploaded or an attachment of a MAPI iMessage
				if ($_POST["type"] == "new") {
					// Delete the file instance and unregister the file
					$attachment_state->deleteUploadedAttachmentFile($_REQUEST["dialog_attachments"], $filename);
				} else { // The file is an attachment of a MAPI iMessage
					// Set the correct array structure
					$attachment_state->addDeletedAttachment($_REQUEST["dialog_attachments"], $filename);
				}
			}
		} else if($_GET && isset($_GET["attachment_id"])) { // this is to upload the file to server when the doc is send via OOo

			$providedFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $_GET['attachment_id'];

			// check wheather the doc is already moved
			if (file_exists($providedFile)) {
				$filename = basename(stripslashes($_GET["name"]));

				// Move the uploaded file to the session
				$attachment_state->addProvidedAttachmentFile($_REQUEST["attachment_id"], $filename, $providedFile, array(
					"name"       => $filename,
					"size"       => filesize($tmpname),
					"type"       => mime_content_type($tmpname),
					"sourcetype" => 'default'
				));
			}else{
				// Check if no files are uploaded with this attachmentid
				$attachment_state->clearAttachmentFiles($_GET["attachment_id"]);
			}
		}

		// Return the file data output when client has request this page through the load==upload_attachment
		if(get('load', false, false, STRING_REGEX) == 'upload_attachment'){
			$return = Array(
				'success'=>true,
				'files'=> Array()
			);

			$files = $attachment_state->getAttachmentFiles($_REQUEST["dialog_attachments"]);
			if ($files) {
				foreach($files as $tmpname => $file){
					$newfileIndicator = in_array($tmpname, $newfiles);
					$return['files'][] = Array(
						'tmpname' => $tmpname,
						'filename' => $file["name"],
						'size' => $file["size"],
						'newfile' => $newfileIndicator
					);
				}
			}

			echo JSON::Encode($return);
		}
	} catch (ZarafaErrorException $e) {
		/**
		 * Return Exception message only if uploading attachment is done through
		 * attachment dialog, not by drag n drop.
		 */
		if(get('load', false, false, STRING_REGEX) == 'upload_attachment'){
			$return = Array(
				'success'=>false,
				'error' => array(
					"type" => ERROR_GENERAL,
					"info" => array(
						"file" => $e->getFileLine(),
						"display_message" => _("Could not upload attachment."),
						"original_message" => $e->getMessage()
					)
				)
			);

			echo JSON::Encode($return);
		}
	}

	$attachment_state->close();
?>
