<?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");
	try {
		$newfiles = Array();

		// Check if dialog_attachments is set
		if(isset($_REQUEST["dialog_attachments"])) {
			// Check if the file is uploaded correctly and is not above the MAX_FILE_SIZE
			if(isset($_FILES["attachments"]) && is_array($_FILES["attachments"])) {
				$FILES = Array();
				
				if(isset($_FILES['attachments']['name']) && is_array($_FILES['attachments']['name'])){
					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]
						);
						
						$FILES[] = $FILE;
					}
				}

				foreach($FILES as $FILE) {
					if (!empty($FILE["size"]) && !(isset($_POST["MAX_FILE_SIZE"]) && $FILE["size"] > $_POST["MAX_FILE_SIZE"])) {
						// Create unique tmpname
						$tmpname = tempnam(TMP_PATH, stripslashes($FILE["name"]));

						// Move the uploaded file the the tmpname
						$result = move_uploaded_file($FILE["tmp_name"], $tmpname);

						if($FILE["type"] == "message/rfc822") {
							/**
							 * 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.
							 */
							$FILE["type"] = "application/octet-stream";
						}

						// Check if there are no files uploaded
						if(!isset($_SESSION["files"])) {
							$_SESSION["files"] = array();
						}
						
						// Check if no files are uploaded with this dialog_attachments
						if(!isset($_SESSION["files"][$_REQUEST["dialog_attachments"]])) {
							$_SESSION["files"][$_REQUEST["dialog_attachments"]] = array();
						}

						// stripping path details
						$tmpname = basename($tmpname);

						// Add file information to the session
						$_SESSION["files"][$_REQUEST["dialog_attachments"]][$tmpname] = Array(
							"name"       => stripslashes($FILE["name"]),
							"size"       => $FILE["size"],
							"type"       => $FILE["type"],
							"sourcetype" => 'default'
						);

						$newfiles[] = $tmpname;
					}
				}
			} else if(isset($_POST["deleteattachment"]) && isset($_POST["type"])) { // Delete uploaded file
				// Check if the delete file is an uploaded or an attachment of a MAPI iMessage
				if($_POST["type"] == "new") {
					// Get the tmpname of the uploaded file
					$tmpname = urldecode($_POST["deleteattachment"]);

					if(isset($_SESSION["files"][$_REQUEST["dialog_attachments"]][$tmpname])) {
						unset($_SESSION["files"][$_REQUEST["dialog_attachments"]][$tmpname]);
						// Delete file
						if (is_file($tmpname)) {
							unlink($tmpname);
						} 
					} 
				} else { // The file is an attachment of a MAPI iMessage
					// Set the correct array structure
					if(!isset($_SESSION["deleteattachment"])) {
						$_SESSION["deleteattachment"] = array();
					}
					
					if(!isset($_SESSION["deleteattachment"][$_REQUEST["dialog_attachments"]])) {
						$_SESSION["deleteattachment"][$_REQUEST["dialog_attachments"]] = array();
					}
					
					// Push the number of the attachment to the array structure
					array_push($_SESSION["deleteattachment"][$_REQUEST["dialog_attachments"]], $_POST["deleteattachment"]);
				}
			}
		} else if($_GET && isset($_GET["attachment_id"])) { // this is to upload the file to server when the doc is send via OOo
			// check wheather the doc is already moved
			if(file_exists("/tmp/".$_GET["attachment_id"])){
				// Create unique tmpname	
				$tmpname = tempnam(TMP_PATH, stripslashes($_GET["name"]));
				// Move the uploaded file to tmpname loaction
				rename("/tmp/".$_GET["attachment_id"], $tmpname);
						
				// Check if there are no files uploaded
				if(!isset($_SESSION["files"])) {
					$_SESSION["files"] = array();
				}
				
				// Check if no files are uploaded with this attachmentid
				if(!isset($_SESSION["files"][$_GET["attachment_id"]])) {
					$_SESSION["files"][$_GET["attachment_id"]] = array();
				}

				// Add file information to the session
				$_SESSION["files"][$_GET["attachment_id"]][basename($tmpname)] = Array(
					"name"       => stripslashes($_GET["name"]),
					"size"       => filesize($tmpname),
					"type"       => mime_content_type($tmpname),
					"sourcetype" => 'default'
				);
			}else{
				// Check if no files are uploaded with this attachmentid
				if(isset($_SESSION["files"][$_GET["attachment_id"]])) {
					$_SESSION["files"][$_GET["attachment_id"]] = array();
				}
			}
		}

		// 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());
			
			if(isset($_SESSION["files"]) && isset($_SESSION["files"][$_REQUEST["dialog_attachments"]])) {
				foreach($_SESSION["files"][$_REQUEST["dialog_attachments"]] 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);
		}
	}
?>
