<?php

function pa($array) {
	echo '<pre>';
	print_r($array);
	echo '</pre>';
}

function error($message) {
	echo $message;
}

function getObjectsAsArray($objects, $keys) {
	if(!$objects)
		return "";
	$return = array();
	if(is_array($objects)) {
		foreach($objects as $object) {
			$return[] = array();
			foreach($keys as $key) {
				$keyCall = 'get' . ucfirst($key);
				$return[sizeof($return) - 1][$key] = $object->$keyCall();
			}
		}
	} else {
		foreach($keys as $key) {
			$keyCall = 'get' . ucfirst($key);
			$return[0][$key] = $object->$keyCall();
		}
	}

	return $return;
}

function scanDocuments($path) {
	global $db;
	global $CONFIG;



	$files = recursiveScanDir($path);
	$allDocuments = getObjectsAsArray(Document::getAllDocuments(), array("id", "fileName", "path", "labelId", "draft", "created", "lastChange", "type", "mailUid"));

	handleFile($files, $allDocuments);

	if(sizeof($allDocuments) > 0) { // Documents got removed
	    foreach($allDocuments as $document) {
	        Document::removeDocumentByID($document['id']);
	    }
	}

	$newDocumentsNumber = sizeof($allDocuments);

	return array(
	    "new" => $newDocumentsNumber
	);


}

function handleFile($filename, &$allDocuments) {
	global $db;
	global $CONFIG;

	if(is_array($filename)) {
		foreach($filename as $dir) {
			handleFile($dir, $allDocuments);
		}
	} else {
		$found = false;
		foreach($allDocuments as $key => $document) {
			if($document['fileName'] == explode('/', $filename)[sizeof(explode('/', $filename)) - 1]) {
				$labelPath = Label::getLabelById($document['labelId'])->getPath();


				if(str_replace($CONFIG['documentPath'], "", $filename) == $labelPath . "/" . $document['path'] . $document['fileName']) {
					// found
					// update stuff
					unset($allDocuments[$key]); // remove from array
					$found = true;
					break;
				}

				// same filename, path unknown
			}
		}

		if(!$found) {
			$fileTime = date("Y-m-d H:i:s", filemtime($filename));

			$path = explode('/', str_replace($CONFIG['documentPath'], "", $filename));
			$labelPath = $path[0];
			unset($path[0]);
			unset($path[sizeof($path)]);
			$path = implode('/', $path) . '/';
			if($path == '/') {
				$path = "";
			}

			Document::addDocument('file', explode('/', $filename)[sizeof(explode('/', $filename)) - 1], $path, Label::getLabelByPath($labelPath)->getId(), '', $fileTime, $fileTime);
		}
	}


}

function searchMails() {
	global $user;
	$mailboxes = Mailbox::getAllMailBoxes();


	foreach($mailboxes as $mailbox) {
		$mailbox->listFolders();
		foreach($mailbox->getFolders() as $folder) {
			$mbFolder = MailboxFolder::getMailboxFolderByName($folder);
			if($mbFolder != false) {
				$mailbox->changeFolder($mbFolder->getFolderName());

				$messageCount = imap_num_msg($mailbox->getMailbox());

				for($i = 1; $i <= $messageCount; ++$i) {
				    $headers = imap_header($mailbox->getMailbox(), $i);

					if(!Mail::getMailByMailInfo($mbFolder->getId(), $headers->Msgno)) {
						$mail = new Mail(NULL, imap_utf8($headers->from[0]->mailbox . '@' . $headers->from[0]->host), imap_utf8($headers->subject), $mbFolder->getId(), $headers->Msgno);

						$mail->save();
					}
				}
			}
		}
	}
}


function getEditableLink($elementId, $type, $pk, $title, $value, $class = '') {
	if($type == 'text' || $type == 'password') {
		$class = 'editable-element-text';
	} else if($type == 'select' && $elementId == 'protocol') {
		$class = 'editable-element-select-protocol';
	} else if($type == 'select' && $elementId == 'use-ssl') {
		$class = 'editable-element-select-use-ssl';
		if($value == '/ssl') {
			$value = 'On';
		} else {
			$value = 'Off';
		}
	} else if($type == 'select' && $elementId == 'no-valid-cert') {
		$class = 'editable-element-select-no-valid-cert';
		if($value == '/novalidate-cert') {
			$value = 'On';
		} else {
			$value = 'Off';
		}
	} else if($type == 'select' && $elementId == 'mailaccount') {
		$class = 'editable-element-select-mailaccount';
	}
	$link = '<a href="#" id="' . $elementId . '" class="' . $class . '" data-type="' . $type . '" data-pk="' . $pk . '" data-url="ajax.php" data-title="' . $title . '">' . $value . '</a>';
	return $link;
}

function getExcerptFromString($string, $count = 50) {
	if(strlen($string) > $count) {
		$string = substr($string, 0, $count);
  		$string = substr($string, 0, strrpos($string, " "));
		$string = $string . " ...";
	}

	return $string;
}

function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

function endsWith($haystack, $needle)
{
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }

    return (substr($haystack, -$length) === $needle);
}

function recursiveScanDir($dir, &$results = array()){
    $files = scandir($dir);

    foreach($files as $key => $value){
        $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
        if(!is_dir($path)) {
            $results[] = $path;
        } else if(is_dir($path) && $value != "." && $value != "..") {
			$results[$path] = array();
			recursiveScanDir($path, $results[$path]);
        }
    }

    return $results;
}

function in_array_r($needle, &$haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
			echo $item;
            return true;
        }
    }

    return false;
}

?>
