<?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] = $objects->$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"));

	handleFile($files, $allDocuments);

	if(sizeof($allDocuments) > 0 && $allDocuments) { // 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;

		if($allDocuments) {
			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();
	$lastMailOption = Option::getOptionByKey("lastMailSearch");
	if($lastMailOption == false) {
		$lastMailOption = new Option(-1, 'lastMailSearch', 0);
	}
	$date = date("d-M-Y", $lastMailOption->getValue());

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

					$search = imap_search($mailbox->getMailbox(), 'SINCE "' . $date . '"');

					if($search) {
						foreach($search as $message) {
							$headers = imap_header($mailbox->getMailbox(), $message);

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

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

	$lastMailOption->setValue(time());
	$lastMailOption->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;
}

?>
