Location: PHPKode > projects > Aukyla Document Management System > adms2/apps/ADMS/Application.php
<?php
/*
     Application.php, this is the main document management module
     Copyright (C) 2003-2005 Arend van Beelen, Auton Rijnsburg

     This program is free software; you can redistribute it and/or modify it
     under the terms of the GNU General Public License as published by the Free
     Software Foundation; either version 2 of the License, or (at your option)
     any later version.

     This program is distributed in the hope that it will be useful, but WITHOUT
     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
     FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
     more details.

     You should have received a copy of the GNU General Public License along
     with this program; if not, write to the Free Software Foundation, Inc.,
     59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

     For any questions, comments or whatever, you may mail me at: hide@address.com
*/

require_once('Config.php');
require_once('Constants.php');
require_once('Decoration.php');
require_once('Document.php');
require_once('Locale.php');
require_once('Login.php');
require_once('GUI.php');
require_once('Messages.php');
require_once('Menus.php');
require_once('MIME.php');
require_once('OpenDocument.php');
require_once('Signal.php');
require_once('String.php');
require_once('Tables.php');
require_once('URI.php');
require_once('Widgets.php');
require_once('XHTML.php');

require_once('ADMS/LocationWidgets.php');
require_once('ADMS/Utils.php');

/**
 * ADMS Application
 *
 * This class emits the following signals:
 * - ADMS::DocumentCreated($uri)
 * - ADMS::DocumentUpdated($uri)
 * - ADMS::DocumentRemoved($uri)
 * - ADMS::UploadDocumentAdded($uri)
 * - ADMS::LinkCreated($uri)
 * - ADMS::FolderCreated($uri)
 * - ADMS::FolderUpdated($uri)
 * - ADMS::FolderRemoved($uri)
 * - ADMS::DocumentCreateFailure($uri)
 * - ADMS::DocumentUpdateFailure($uri)
 * - ADMS::DocumentRemoveFailure($uri)
 * - ADMS::LinkCreateFailure($uri)
 * - ADMS::FolderCreateFailure($uri)
 * - ADMS::FolderRemoveFailure($uri)
 * - ADMS::EntryMoved($fromUri, $toUri)
 */
class ADMS_Application extends Container
{
	// constructor
	function __construct(Container $parent, $menu = null)
	{
		parent::__construct($parent);

		$this->config = new Config('adms', Login::username());
		$this->menu = (isset($menu) ? $menu : MainWindow::instance()->mainMenu());

		Locale::init('apps/ADMS');

		// determine the current directory and check whether it exists
		$this->view = (Config::request('ADMS_button') == i18n('Cancel') ? 'Browse' :
		                                                                  Config::request('ADMS_view', 'Browse'));
		$this->action = Config::request('ADMS_action');

		$this->readLocation();

		if($this->checkLocationAccess() == false)
		{
			return;
		}

		$this->locationChanged = false;
		$this->checkAction();

		if($this->locationChanged == true &&
		   $this->checkLocationAccess(false) == false)
		{
			return;
		}

		$this->saveLocation();

		$this->createMenuEntries();
	}

	private function readLocation()
	{
		for($i = 0; $i < 2; $i++)
		{
			$this->locationArray[$i] = Config::request("ADMS_location$i");
			if($this->locationArray[$i] == '')
			{
				$this->locationArray[$i] = Login::sessionVariable("ADMS_location$i", 'ADMS://docs/0');
			}
			if(URI::fileExists($this->locationArray[$i]) == false)
			{
				Messages::error(i18n('Sorry, the requested location does not exist.'));

				$this->locationArray[$i] = 'ADMS://docs/0';
				$this->view = 'Browse';
				$this->action = '';
			}
			$this->locationArray[$i] = String::substringBefore($this->locationArray[$i], '://').'://'.
			                           String::simplifyPath(String::substringAfter($this->locationArray[$i], '://'));
		}
	}

	private function checkLocationAccess($checkViewAndAction = true)
	{
		foreach($this->locationArray as $i => $location)
		{
			// check the access permissions for the directory
			$access = $this->accessArray[$i] = URI::permissions($location);

			// redirect the user to the root directory if he has no access
			if(($access & PERMISSION_READ) == false)
			{
				if($location == 'ADMS://docs/0/')
				{
					return false;
				}

				Messages::error(i18n('You do not have access to the requested location.'));

				$this->locationArray[$i] = 'ADMS://docs/0';
				$this->view = 'Browse';
				$this->action = '';
				$access = $this->accessArray[$i] = URI::permissions($this->locationArray[$i]);

				// block everything if he has no access to the root dir either
				if(($access & PERMISSION_READ) == false)
				{
					return false;
				}
			}

			if($checkViewAndAction == false || $i > 0)
			{
				continue;
			}

			// check the action and view against the permissions
			if(($access & PERMISSION_APPEND) != PERMISSION_APPEND)
			{
				if(String::startsWith($this->view, 'New') || String::startsWith($this->action, 'New'))
				{
					$this->view = 'Browse';
					$this->action = '';
				}
			}
			if(($access & PERMISSION_MODIFY) != PERMISSION_MODIFY)
			{
				if(String::startsWith($this->view, 'Edit') || String::startsWith($this->action, 'Edit'))
				{
					$this->view = 'Browse';
					$this->action = '';
				}
			}
			if(($access & PERMISSION_DELETE) != PERMISSION_DELETE)
			{
				if(String::startsWith($this->view, 'Delete') || String::startsWith($this->action, 'Delete'))
				{
					$this->view = 'Browse';
					$this->action = '';
				}
			}
		}

		if(URI::isFile($this->locationArray[0]))
		{
			$this->document = basename($this->locationArray[0]);
			$this->directory = dirname($this->locationArray[0]);
		}
		else
		{
			$this->document = '';
			$this->directory = $this->locationArray[0];
		}

		return true;
	}

	private function saveLocation()
	{
		foreach($this->locationArray as $i => $location)
		{
			if(MIME::type($location) == 'text/x-uri')
			{
				$location = dirname($location);
			}
			Login::setSessionVariable("ADMS_location$i", $location);
		}
	}

	private function createMenuEntries()
	{
		$this->access = URI::permissions("{$this->directory}/{$this->document}");
		if($this->document == '')
		{
			if($this->access & PERMISSION_APPEND)
			{
				$menuEntry = new MenuEntry($this->menu, i18n('New document'));
				$menuEntry->setLink(Config::globals('baseURL')."?view=ADMS&amp;ADMS_view=NewDocument");
				$menuEntry = new MenuEntry($this->menu, i18n('New link'));
				$menuEntry->setLink(Config::globals('baseURL')."?view=ADMS&amp;ADMS_view=NewLink");
				$menuEntry = new MenuEntry($this->menu, i18n('New folder'));
				$menuEntry->setLink(Config::globals('baseURL')."?view=ADMS&amp;ADMS_view=NewFolder");
			}
			if($this->access & PERMISSION_MODIFY)
			{
				$menuEntry = new MenuEntry($this->menu, i18n('Edit folder'));
				$menuEntry->setLink(Config::globals('baseURL')."?view=ADMS&amp;ADMS_view=EditFolder");
			}
		}
		else
		{
			if($this->access & PERMISSION_MODIFY)
			{
				$menuEntry = new MenuEntry($this->menu, i18n('Edit document'));
				$menuEntry->setLink(Config::globals('baseURL')."?view=ADMS&amp;ADMS_view=EditDocument");
				$menuEntry = new MenuEntry($this->menu, i18n('Attach file to document'));
				$menuEntry->setLink(Config::globals('baseURL')."?view=ADMS&amp;ADMS_view=AttachFile");
			}
			$title = String::stripSpecialChars(URI::metaData("{$this->directory}/{$this->document}", 'name', $this->document));
			$mimetype = MIME::type("{$this->directory}/{$this->document}");
			$extension = ($mimetype == '' ? '' : MIME::extension($mimetype));
			if(String::startsWith(Login::username(), 'anonymous') == false)
			{
				$menuEntry = new MenuEntry($this->menu, i18n('E-mail document'));
				$menuEntry->setLink(Config::globals('baseURL')."?view=ADMS&amp;ADMS_view=EmailDocument");
			}
			$menuEntry = new MenuEntry($this->menu, i18n('Download document'));
			$menuEntry->setLink(Config::globals('downloadURL')."?file={$this->directory}/{$this->document}&amp;name=$title$extension");
		}

		$locationString = ADMS_Utils::getLocationString($this->locationArray[0]);

		$menuEntry = new MenuEntry($this->menu, '');
		$menuEntry->setPriority(-500);
		new Image($menuEntry, 'resources/base/icons/buttons/info.png');
		new Tooltip($menuEntry, i18n('You are now in: <label style="font-weight: bold">%1</label>', htmlspecialchars($locationString)));
	}

	private function checkAction()
	{
		if(Config::request('ADMS_button') == i18n('Cancel'))
		{
			$oldLocation = Config::request('ADMS_oldLocation0');
			if($oldLocation != '')
			{
				$this->locationArray[0] = $oldLocation;
				$this->locationChanged = true;
			}

			return;
		}

		$formId = Config::request('ADMS_formSubmit');
		if($formId != '')
		{
			if(Login::sessionVariable("ADMS_{$formId}_submitted", 'false') == 'true')
			{
				Messages::error(i18n('You already submitted this form.'));
				return;
			}
			else
			{
				Login::setSessionVariable("ADMS_{$formId}_submitted", 'true');
			}
		}

		switch($this->action)
		{
			case 'SplitView': $this->splitView(); break;
			case 'CloseView': $this->closeView(); break;

			case 'NewDocument':
				switch(Config::request('ADMS_doctype'))
				{
					case 'ADMS_text/plain': $this->saveDocument(true);   break;
					case 'ADMS_upload':     $this->saveUploadDocument(); break;
				}
				break;

			case 'NewAttachement': $this->saveAttachement();  break;

			case 'NewLink':
				switch(Config::request('ADMS_doctype'))
				{
					case 'ADMS_internal': $this->saveDocumentLink(); break;
					case 'ADMS_external': $this->saveURLLink();      break;
				}
				break;

			case 'NewFolder':     $this->saveNewFolder();     break;
			case 'EditDocument':  $this->saveDocument(false); break;
			case 'EditFolder':    $this->updateFolder();      break;
			case 'DeleteEntry':   $this->deleteEntry();       break;
			case 'MoveEntries':   $this->moveEntries();       break;
			case 'Search':        $this->search();            break;
			case 'EmailDocument': $this->emailDocument();     break;
		}
	}

	private function splitView()
	{
		Login::setSessionVariable('ADMS_splitView', 'true');

		$this->locationArray[1] = $this->locationArray[0];
	}

	private function closeView()
	{
		Login::setSessionVariable('ADMS_splitView', false);
		Login::setSessionVariable("ADMS_location1", false);

		$this->locationArray[0] = $this->locationArray[Config::request('ADMS_pane', '0') == '0' ? 1 : 0];
		$this->locationChanged = true;
		unset($this->locationArray[1]);
	}

	private function saveDocument($new)
	{
		$title    = Config::request('ADMS_title');
		$comment  = Config::request('ADMS_comment');
		$mimetype = String::substringAfter(Config::request('ADMS_doctype'), 'ADMS_');

		if($new)
		{
			$uri = URI::uniquePath($this->directory, $title);
		}
		else
		{
			$uri = "{$this->directory}/{$this->document}";
			$this->updatePermissions($uri);
		}

		if(Document::hasEditor($mimetype) == false ||
		   Document::save('ADMS_document', $uri, $mimetype))
		{
			URI::setMetaData($uri, 'name', $title);
			URI::setMetaData($uri, 'mime-type', $mimetype);
			URI::setMetaData($uri, 'comment', $comment != '' ? $comment : false);

			if(String::startsWith($mimetype, 'application/vnd.oasis.opendocument.'))
			{
				$openDocument = new OpenDocument();
				$openDocument->load($uri);
				$openDocument->setTitle($title);
				$openDocument->setComments($comment);
			}

			Messages::confirm($new ? i18n('Document created successfully.') :
			                         i18n('Document updated.'));
			Signal::emit($new ? 'ADMS::DocumentCreated' : 'ADMS::DocumentUpdated', $uri);
		}
		else
		{
			Messages::error($new ? i18n('Could not create document.') :
			                       i18n('Could not update document.'));
			Signal::emit($new ? 'ADMS::DocumentCreateFailure' : 'ADMS::DocumentUpdateFailure', $uri);
		}

		$oldLocation = Config::request('ADMS_oldLocation0');
		if($oldLocation != '')
		{
			$this->locationArray[0] = $oldLocation;
			$this->locationChanged = true;
		}
	}

	private function saveUploadDocument()
	{
		$title    = Config::request('ADMS_title');
		$comment  = Config::request('ADMS_comment');
		$tmpURI   = Config::request('ADMS_uploadFile');
		$mimetype = Config::request('ADMS_mimetype');
		if($mimetype == '')
		{
			$mimetype = MIME::type($tmpURI);
		}

		$uri = URI::uniquePath($this->directory, $title);

		URI::copy($tmpURI, $uri);
		URI::setMetaData($uri, 'name', $title);
		URI::setMetaData($uri, 'mime-type', $mimetype);
		URI::setMetaData($uri, 'comment', $comment != '' ? $comment : false);

		if(String::startsWith($mimetype, 'application/vnd.oasis.opendocument.'))
		{
			$openDocument = new OpenDocument();
			$openDocument->load($uri);
			$openDocument->setTitle($title);
			$openDocument->setComments($comment);
		}

		Messages::confirm(i18n('Document added successfully.'));
		Signal::emit('ADMS::UploadDocumentAdded', $uri);
	}

	private function saveAttachement()
	{
		$filename = basename(Config::request('ADMS_filename'));
		$uri = URI::uniquePath($this->directory, $filename);

		$mimetype = MIME::type('upload://ADMS_file');
		$description = MIME::description($mimetype);
		$icon = (PageIcon::iconExists("base/icons/MIME/$mimetype") ? "base/icons/MIME/$mimetype" : 'base/icons/MIME/application/octet-stream');
		if(URI::copy('upload://ADMS_file', $uri))
		{
			URI::setMetaData($uri, 'name', $filename);
			URI::setMetaData($uri, 'mime-type', $mimetype);
			URI::setMetaData($uri, 'ADMS-file-type', 'attachement');
			URI::setPermissionsArray($uri, URI::permissionsArray($this->locationArray[0]));

			$attachements = URI::metaData($this->locationArray[0], 'ADMS-attachements');
			if($attachements != '')
			{
				$attachements .= ',';
			}
			$attachements .= basename($uri);
			URI::setMetaData($this->locationArray[0], 'ADMS-attachements', $attachements);
			URI::setMetaData($this->locationArray[0], 'mtime', time());

			Messages::confirm(i18n('File attached successfully.'));
		}
		else
		{
			Messages::error(i18n('Could not attach file.'));
		}
	}

	private function saveURLLink()
	{
		$title   = Config::request('ADMS_title');
		$comment = Config::request('ADMS_comment');

		$uri = URI::uniquePath($this->directory, $title);

		if(Document::save('ADMS_url', $uri, 'text/x-uri'))
		{
			URI::setMetaData($uri, 'name', $title);
			URI::setMetaData($uri, 'mime-type', 'text/x-uri');
			if($comment != '') URI::setMetaData($uri, 'comment', $comment);

			Messages::confirm(i18n('Link created successfully.'));
			Signal::emit('ADMS::LinkCreated', $uri);
		}
		else
		{
			Messages::error(i18n('Could not create link.'));
			Signal::emit('ADMS::LinkCreateFailure', $uri);
		}
	}

	private function saveNewFolder()
	{
		$uri = URI::uniquePath($this->directory, Config::request('ADMS_title'));

		if(URI::mkdir($uri))
		{
			URI::setMetaData($uri, 'mime-type', 'inode/directory');
			$this->updateFolder($uri);

			Messages::confirm(i18n('Folder created successfully.'));
			Signal::emit('ADMS::FolderCreated', $uri);
		}
		else
		{
			Messages::error(i18n('Could not create folder.'));
			Signal::emit('ADMS::FolderCreateFailure', $uri);
		}
	}

	private function updateFolder($dir = '')
	{
		$uri = ($dir != '' ? $dir : $this->directory);

		$title   =     Config::request('ADMS_title');
		$comment =     Config::request('ADMS_comment');
		$sort    =     Config::request('ADMS_sort');
		$header  =     Config::request('ADMS_header');
		$description = Config::request('ADMS_description');

		URI::setMetaData($uri, 'name', $title);
		URI::setMetaData($uri, 'comment', $comment != '' ? $comment : false);
		if($sort != '')
		{
			URI::setMetaData($uri, 'ADMS-sort', $sort);
		}
		if($header == 'true' && $description != '')
		{
			URI::setMetaData($uri, 'description', $description);
		}
		else
		{
			URI::setMetaData($uri, 'description');
		}

		$this->updatePermissions($uri);

		if($dir == '')
		{
			$oldLocation = Config::request('ADMS_oldLocation0');
			if($oldLocation != '')
			{
				$this->locationArray[0] = $oldLocation;
				$this->locationChanged = true;
			}

			Messages::confirm(i18n('Folder updated.'));
			Signal::emit('ADMS::FolderUpdated', $uri);
		}
	}

	private function updatePermissions($uri)
	{
		if(Config::request('ADMS_permissionsFormSent') != 'true' ||
		   (URI::permissions($uri) & PERMISSION_ADMINISTRATE) == false)
		{
			return;
		}

		$types = array('none' => PERMISSION_NONE,
		               'read' => PERMISSION_READ,
		               'append' => PERMISSION_APPEND,
		               'modify' => PERMISSION_MODIFY,
		               'delete' => PERMISSION_DELETE,
		               'administrate' => PERMISSION_ADMINISTRATE);

		$permissions = array('ip' => array(), 'user' => array(), 'group' => array(), 'other' => PERMISSION_NONE);

		foreach(Config::requests() as $var => $val)
		{
			if($val != 'true')
			{
				continue;
			}

			if(String::startsWith($var, 'ADMS_ip_'))
			{
				list($ADMS, $ip, $name) = explode('_', $var, 3);
				$type = String::substringAfter($name, '_', true);
				$name = str_replace('_', '.', String::substringBefore($name, '_', true));

				if(isset($permissions['ip'][$name]) == false)
				{
					$permissions['ip'][$name] = $types[$type];
				}
				else
				{
					$permissions['ip'][$name] |= $types[$type];
				}
			}
			if(String::startsWith($var, 'ADMS_user_'))
			{
				list($ADMS, $user, $name, $type) = explode('_', $var, 4);

				if(isset($permissions['user'][$name]) == false)
				{
					$permissions['user'][$name] = $types[$type];
				}
				else
				{
					$permissions['user'][$name] |= $types[$type];
				}
			}
			else if(String::startsWith($var, 'ADMS_group_'))
			{
				list($ADMS, $group, $name, $type) = explode('_', $var, 4);

				if(isset($permissions['group'][$name]) == false)
				{
					$permissions['group'][$name] = $types[$type];
				}
				else
				{
					$permissions['group'][$name] |= $types[$type];
				}
			}
			else if(String::startsWith($var, 'ADMS_other_'))
			{
				list($ADMS, $other, $type) = explode('_', $var, 3);

				$permissions['other'] |= $types[$type];
			}
		}

		if(URI::setPermissionsArray($uri, $permissions, Config::request('ADMS_applyRecursivePermissions') != '') == true)
		{
			Messages::confirm(i18n('Permissions updated.'));
		}
		else
		{
			Messages::error(i18n('Error while updating permissions.'));
		}
	}

	private function deleteEntry()
	{
		if(URI::isDir($this->locationArray[0]))
		{
			if(URI::rmdir($this->locationArray[0], true))
			{
				Messages::confirm(i18n('Folder removed.'));
				Signal::emit('ADMS::FolderRemoved', $this->locationArray[0]);
			}
			else
			{
				Messages::error(i18n('Could not remove folder.'));
				Signal::emit('ADMS::FolderRemoveFailure', $this->locationArray[0]);
			}
		}
		else
		{
			$attachements = URI::metaData($this->locationArray[0], 'ADMS-attachements');
			if(URI::unlink($this->locationArray[0]))
			{
				Messages::confirm(i18n('Document removed.'));
				Signal::emit('ADMS::DocumentRemoved', $this->locationArray[0]);

				if($attachements != '')
				{
					$attachements = explode(',', $attachements);
					foreach($attachements as $attachement)
					{
						$attachementFile = dirname($this->locationArray[0])."/$attachement";
						URI::unlink($attachementFile);
					}
				}
			}
			else
			{
				Messages::error(i18n('Could not remove document.'));
				Signal::emit('ADMS::DocumentRemoveFailure', $this->locationArray[0]);
			}
		}

		$this->locationArray[0] = dirname($this->locationArray[0]);
		$this->locationChanged = true;
	}

	private function moveEntries()
	{
		if(Config::request('ADMS_button') == 'left')
		{
			$sourceLocation = $this->locationArray[1];
			$targetLocation = $this->locationArray[0];
		}
		else if(Config::request('ADMS_button') == 'right')
		{
			$sourceLocation = $this->locationArray[0];
			$targetLocation = $this->locationArray[1];
		}

		if(String::simplifyPath($sourceLocation) == String::simplifyPath($targetLocation))
		{
			Messages::error(i18n('Won\'t move entries to their current location.'));
			return;
		}
		if(URI::isFile($targetLocation))
		{
			Messages::error(i18n('Can only move entries to a folder.'));
			return;
		}

		if(URI::isFile($sourceLocation))
		{
			Config::setRequest("ADMS_entry_$sourceLocation", 'true');
			$sourceLocation = dirname($sourceLocation);

			if(Config::request('ADMS_button') == 'left')
			{
				$this->locationArray[1] = $sourceLocation;
			}
			else if(Config::request('ADMS_button') == 'right')
			{
				$this->locationArray[0] = $sourceLocation;
			}
			$this->locationChanged = true;
		}

		$errors = false;
		$entryMoved = false;
		foreach(Config::requests() as $request => $value)
		{
			if(String::startsWith($request, 'ADMS_entry_') == false)
			{
				continue;
			}

			$entryMoved = true;

			$sourceDocument = String::substringAfter($request, 'ADMS_entry_');
			$attachements = URI::metaData($sourceDocument, 'ADMS-attachements');
			if(URI::rename($sourceDocument, $targetLocation, $realTarget) == false)
			{
				$errors = true;
			}
			else
			{
				if($attachements != '')
				{
					$attachements = explode(',', $attachements);
					$newAttachements = '';
					foreach($attachements as $attachement)
					{
						$attachementSource = "$sourceLocation/$attachement";
						if(URI::rename($attachementSource, $targetLocation, $realAttachementTarget) == false)
						{
							Messages::error("Failed moving attachement $attachementSource to $targetLocation.");
							$errors = true;
						}

						if($newAttachements != '')
						{
							$newAttachements .= ',';
						}
						$newAttachements .= basename($realAttachementTarget);
					}
					URI::setMetaData($realTarget, 'ADMS-attachements', $newAttachements);
				}

				Signal::emit('ADMS::EntryMoved', $sourceDocument, $realTarget);
			}
		}

		if($errors == false)
		{
			if($entryMoved == false)
			{
				Messages::error(i18n('No entries to move.'));
			}
			else
			{
				Messages::confirm(i18n('All entries moved successfully.'));
			}
		}
		else
		{
			Messages::error(i18n('Error moving some entries.'));
		}
	}

	private function search()
	{
		$this->locationArray[0] = 'ADMS_Search://'.Config::request('ADMS_keywords');
		$this->locationChanged = true;
		$this->view = 'Browse';
	}

	private function emailDocument()
	{
		$this->view = 'Browse';
		$file = $this->locationArray[0];
		if(String::startsWith(Login::username(), 'anonymous'))
		{
			Messages::error(i18n('You need to login to send an e-mail.'));
			return;
		}

		if(URI::isFile($file) == false)
		{
			Messages::error(i18n('Cannot e-mail folders.'));
			return;
		}

		$recipientUsers = explode(',', Config::request('ADMS_selectedRecipients'));
		if(sizeof($recipientUsers) == 0)
		{
			Messages::error(i18n('No recipients given for the mail.'));
			return;
		}

		$recipientAddresses = array();
		foreach($recipientUsers as $user)
		{
			$recipientAddresses[] = Login::userMail($user);
		}

		$from      = Login::fullName();
		$fromMail  = Login::userMail();
		$to        = implode(',', $recipientAddresses);
		$subject   = Config::request('ADMS_subject');
		$mimetype  = MIME::type($file);
		$title     = String::stripSpecialChars(URI::metaData($file, 'name', basename($file)));
		$extension = MIME::extension($mimetype);

		/*if($mimetype == 'application/vnd.oasis.opendocument.text' &&
		   Config::request('ADMS_convertToPdf') == 'true')
		{
			$convertCommand = $this->config->variable('pdfConvertCommand');
			$tmpFilename = AUKYLA_DIR."/data/apps/ADMS/PDF/$title$extension";
			copy($file, $tmpFilename);
			exec("$convertCommand $tmpFilename", $output, $result);
			if($result !== 0)
			{
				Messages::error(i18n('An error occurred when trying to convert the document to PDF.'));
				unlink($tmpFilename);
				return;
			}
			$fileContents = base64_encode(file_get_contents("$tmpFilename.pdf"));
			$extension = '.pdf';
		}
		else
		{
			$fileContents = base64_encode(URI::fileGetContents($file));
		}*/
		$fileContents = chunk_split(base64_encode(URI::fileGetContents($file)));

		if(mail($to, $subject, '',
		        "From: \"$from\" <$fromMail>\r\n".
		        "MIME-Version: 1.0\n".
		        "Content-Type: multipart/mixed; boundary=\"ADMS-12345\";\n".
		        "Content-Transfer-Encoding: 7bit\n".
		        "This part of the E-mail should never be seen. If\n".
		        "you are reading this, consider upgrading your e-mail\n".
		        "client to a MIME-compatible client.\n".
		        "--ADMS-12345\n".
		        "Content-Type: $mimetype; name=\"$title$extension\";\n".
		        "Content-Transfer-Encoding: base64\n".
		        "Content-Disposition: attachment\n\n".
		        "$fileContents\n".
		        "--ADMS-12345--\n") == true)
		{
			Messages::confirm(i18n('Mail sent.'));
		}
		else
		{
			Messages::error(i18n('An error occurred while sending the mail.'));
		}

		/*if($mimetype == 'application/vnd.oasis.opendocument.text' &&
		   Config::request('ADMS_convertToPdf') == 'true')
		{
			unlink($tmpFilename);
			unlink("$tmpFilename.pdf");
		}*/
	}

	// show the ADMS application
	public function show()
	{
		if(($this->access & PERMISSION_READ) == false)
		{
			if(String::startsWith(Login::username(), 'anonymous'))
			{
				new Paragraph($this, i18n('You need to be logged in to access this application.'));
			}
			else
			{
				new Paragraph($this, i18n('You do not have access to this application.'));
			}
		}
		else
		{
			switch($this->view)
			{
				case 'Browse':        $this->browse(); break;
				case 'NewDocument':   $this->newDocument(); break;
				case 'NewLink':       $this->newLink(); break;
				case 'NewFolder':     $this->editFolder(true); break;
				case 'EditDocument':  $this->editDocument(); break;
				case 'AttachFile':    $this->newAttachement(); break;
				case 'EditFolder':    $this->editFolder(false); break;
				case 'EmailDocument': $this->showEmailDocumentForm(); break;

				default:
					new Paragraph($this, i18n('The view you requested could not be found.'));
			}
		}

		parent::show();
	}

	private function browse()
	{
		if(Login::sessionVariable('ADMS_splitView') != 'true')
		{
			$parent = $this;
			$showLastAddedDocuments = $this->config->variable('showLastAddedDocuments', 'true');
			$showLastModifiedDocuments = $this->config->variable('showLastModifiedDocuments', 'false');
			if($showLastAddedDocuments == 'true' || $showLastModifiedDocuments == 'true')
			{
				if(URI::isFile($this->locationArray[0]))
				{
					$gridLayout = new GridLayout($this, 1);
					$gridLayout->addCssStyle('width: 100%');
					$parent = new Box($gridLayout);
				}
				else
				{
					$gridLayout = new GridLayout($this, 2);
					$gridLayout->setColumnWidths(array('75%', '25%'));
					$gridLayout->addCssStyle('width: 100%');
					$parent = new Box($gridLayout);
					$historyPane = new Box($gridLayout);

					$gridLayout->cell(0, 0)->addCssStyle('vertical-align: top');
					$gridLayout->cell(0, 1)->addCssStyle('vertical-align: top');

					if($showLastAddedDocuments == 'true')
					{
						$lastAddedPane = new Box($historyPane);
						$lastAddedPane->addCssStyle('border: thin solid black; width: 90%; padding: 1em; margin-bottom: 1em');
						$paragraph = new Paragraph($lastAddedPane, i18n('Last added documents:'));
						$paragraph->addCssStyle('font-weight: bold');
						new ADMS_HistoryWidget($lastAddedPane, 'ADMS_History://createdSince/'.(time() - 2678400).'/5');
					}
					if($showLastModifiedDocuments == 'true')
					{
						$lastModifiedPane = new Box($historyPane);
						$lastModifiedPane->addCssStyle('border: thin solid black; width: 90%; padding: 1em');
						$paragraph = new Paragraph($lastModifiedPane, i18n('Last modified documents:'));
						$paragraph->addCssStyle('font-weight: bold');
						new ADMS_HistoryWidget($lastModifiedPane, 'ADMS_History://modifiedSince/'.(time() - 2678400).'/5');
					}
				}
			}

			$this->showBrowsePane($parent, 0);
		}
		else
		{
			$this->browseSplitView();
		}
	}

	private function browseSplitView()
	{
		$form = new Form($this, Config::globals('baseURL').'?ADMS_action=MoveEntries');

		$gridLayout = new GridLayout($form, 3);
		$gridLayout->addCssStyle('width: 100%');
		$gridLayout->setColumnWidths(array('47%', '6%', '47%'));
		$leftPane = new Box($gridLayout);
		$middlePane = new Box($gridLayout);
		$rightPane = new Box($gridLayout);

		$gridLayout->cell(0, 0)->addCssStyle('vertical-align: top');
		$gridLayout->cell(0, 2)->addCssStyle('vertical-align: top');

		$leftPaneWritable = false;
		$rightPaneWritable = false;
		if(String::simplifyPath($this->locationArray[0]) !=
		   String::simplifyPath($this->locationArray[1]))
		{
			$leftPaneWritable  = (URI::isDir($this->locationArray[0]) &&
			                      (URI::permissions($this->locationArray[0]) & PERMISSION_APPEND) != 0);
			$rightPaneWritable = (URI::isDir($this->locationArray[1]) &&
			                      (URI::permissions($this->locationArray[1]) & PERMISSION_APPEND) != 0);
		}

		$this->showBrowsePane($leftPane, 0, $rightPaneWritable);

		$paragraph = new Paragraph($middlePane);
		$paragraph->addCssStyle('text-align: center');

		if($rightPaneWritable == true)
		{
			$button = new Button($paragraph, 'ADMS_button');
			$button->setValue('right');
			$button->addCssStyle('background: transparent; border: none; cursor: pointer');
			$rightImage = new Image($button, 'resources/base/icons/buttons/1rightarrow.png');
			$rightImage->setTitle(i18n('Move to the right'));
			$rightImage->setText(i18n('Move to the right'));
		}

		if($leftPaneWritable == true)
		{
			$button = new Button($paragraph, 'ADMS_button');
			$button->setValue('left');
			$button->addCssStyle('background: transparent; border: none; cursor: pointer');
			$leftImage = new Image($button, 'resources/base/icons/buttons/1leftarrow.png');
			$leftImage->setTitle(i18n('Move to the left'));
			$leftImage->setText(i18n('Move to the left'));
		}

		$this->showBrowsePane($rightPane, 1, $leftPaneWritable);
	}

	private function showBrowsePane($parent, $pane, $checkboxes = false)
	{
		$this->showBrowseButtons($parent, $pane);

		if(URI::isFile($this->locationArray[$pane]))
		{
			new ADMS_DocumentWidget($parent, $this->locationArray[$pane]);
		}
		else
		{
			if(String::startsWith($this->locationArray[$pane], 'ADMS_Search://'))
			{
				$directoryWidget = new ADMS_SearchWidget($parent, $this->locationArray[$pane]);
			}
			else
			{
				$directoryWidget = new ADMS_DirectoryWidget($parent, $this->locationArray[$pane]);
			}

			if(Login::sessionVariable('ADMS_splitView') == 'true')
			{
				$directoryWidget->setLocationIndex($pane);
				$directoryWidget->setEnableEditFunctions(false);
				if($checkboxes == true)
				{
					$directoryWidget->setAddCheckboxes(true);
				}
			}
		}
	}

	private function addFormSubmit($form)
	{
		$formId = Login::randomPassword(8);
		while(Login::sessionVariable("ADMS_{$formId}_submitted", 'false') == 'true')
		{
			$formId = Login::randomPassword(8);
		}
		$formSubmit = new HiddenInput($form, 'ADMS_formSubmit');
		$formSubmit->setValue($formId);
	}

	private function createFormHeader($type = 0, $new = true, $uri = '', $mimetype = '')
	{
		if($type == 0)
		{
			$askDetailsText = i18n('Please enter some details about the document.');
			$titleText      = i18n('Title of the document:');
			$titleError     = i18n('Please specify a title.');
			$action         = ($new ? 'NewDocument' : 'EditDocument');
		}
		else if($type == 1)
		{
			$askDetailsText = i18n('Please enter some details about the link.');
			$titleText      = i18n('Name of the link:');
			$titleError     = i18n('Please specify a name.');
			$action         = ($new ? 'NewLink' : 'EditLink');
		}
		else if($type == 2)
		{
			$askDetailsText = i18n('Please enter some details about the folder.');
			$titleText      = i18n('Name of the folder:');
			$titleError     = i18n('Please specify a name.');
			$action         = ($new ? 'NewFolder' : 'EditFolder');
		}

		if($new == false && $uri != '')
		{
			$title = URI::metaData($uri, 'name');
			$comment = URI::metaData($uri, 'comment');

			if(URI::permissions($uri) & PERMISSION_ADMINISTRATE)
			{
				$permissions = URI::permissionsArray($uri);
			}
			else
			{
				$permissions = '';
			}
		}
		else
		{
			$title = '';
			$comment = '';
			$permissions = '';

			if($uri != '' &&
			   String::startsWith($mimetype, 'application/vnd.oasis.opendocument.'))
			{
				$openDocument = new OpenDocument();
				$openDocument->load($uri);
				$title = $openDocument->title();
				$comment = $openDocument->comments();
			}
		}

		$form = new Form($this, Config::globals('baseURL')."?view=ADMS&amp;ADMS_action=$action&amp;ADMS_location0={$this->directory}/{$this->document}");
		$form->setId('ADMS_Form');
		$form->setErrorMessage($titleError);
		$form->useGridLayout(true);

		$this->addFormSubmit($form);

		$oldLocation = Config::request('ADMS_oldLocation0');
		if($oldLocation != '')
		{
			$oldLocationInput = new HiddenInput($form, 'ADMS_oldLocation0');
			$oldLocationInput->setValue($oldLocation);
		}

		new Paragraph($form, $askDetailsText);
		$titleInput = new TextInput($form, 'ADMS_title');
		$titleInput->setText($titleText);
		$titleInput->setValue(htmlspecialchars($title));
		$titleInput->setRequired(true);

		$commentInput = new TextInput($form, 'ADMS_comment');
		$commentInput->setText(i18n('Optional comments:'));
		$commentInput->setValue(htmlspecialchars($comment));

		if(is_array($permissions))
		{
			self::createPermissionsTable($form, $permissions);
		}

		return $form;
	}

	private static function createPermissionsTable(Form $form, $permissions)
	{
		new ExternalJavaScript($form, 'resources/apps/ADMS/permissionScripts.js');
		$hiddenInput = new HiddenInput($form, 'ADMS_permissionsFormSent');
		$hiddenInput->setValue('true');
		$permissionsParagraph = new Paragraph($form, i18n('Access Permissions:'));
		$permissionsParagraph->addCssStyle('font-weight: bold');
		$table = new Table($form);
		$table->setId('ADMS_permissionsTable');
		$table->addCssStyle('border: thin solid black; margin-left: 20px');
		$table->setColumnsAlternate(true);
		$row = new TableRow($table);
		$cell = new TableCell($row); $cell->addCssStyle('width: 10em'); new TableCell($row, i18n('Read')); new TableCell($row, i18n('Append')); new TableCell($row, i18n('Modify')); new TableCell($row, i18n('Delete')); new TableCell($row, i18n('Administrate')); $cell = new TableCell($row); $cell->addCssStyle('width: 8em');
		$availableUsers = Login::users();
		$availableGroups = Login::groups();

		// IP ranges
		$row = new TableRow($table);
		$row->setId('ADMS_ipsRow');
		$row->addCssStyle('display: '.(isset($permissions['ip']) ? 'table-row' : 'none'));
		$cell = new TableCell($row, i18n('IP ranges')); $cell->addCssStyle('font-weight: bold'); new TableCell($row); new TableCell($row); new TableCell($row); new TableCell($row); new TableCell($row); new TableCell($row);
		if(isset($permissions['ip']))
		{
			foreach($permissions['ip'] as $ipRange => $permission)
			{
				$ipRange = htmlspecialchars($ipRange);
				$row = self::createPermissionsTableRow($table, "ip_{$ipRange}", $ipRange, $permission);
				$cell = new TableCell($row); $button = new Button($cell, ''); $button->setValue(i18n('Delete'));
				$button->addJavascript('onclick', "ADMS_removeRow('ip', '$ipRange'); return false;");
			}
		}

		// users
		$row = new TableRow($table);
		$row->setId('ADMS_usersRow');
		$row->addCssStyle('display: '.(isset($permissions['user']) ? 'table-row' : 'none'));
		$cell = new TableCell($row, i18n('Users')); $cell->addCssStyle('font-weight: bold'); new TableCell($row); new TableCell($row); new TableCell($row); new TableCell($row); new TableCell($row); new TableCell($row);
		if(isset($permissions['user']))
		{
			foreach($permissions['user'] as $user => $permission)
			{
				$user = htmlspecialchars($user);
				$row = self::createPermissionsTableRow($table, "user_{$user}", $user, $permission);
				$cell = new TableCell($row); $button = new Button($cell, ''); $button->setValue(i18n('Delete'));
				$button->addJavascript('onclick', "ADMS_removeRow('user', '$user'); return false;");
				$key = array_search($user, $availableUsers);
				if($key !== false)
				{
					unset($availableUsers[$key]);
				}
			}
		}

		// groups
		$row = new TableRow($table);
		$row->setId('ADMS_groupsRow');
		$row->addCssStyle('display: '.(isset($permissions['group']) ? 'table-row' : 'none'));
		$cell = new TableCell($row, i18n('Groups')); $cell->addCssStyle('font-weight: bold'); new TableCell($row); new TableCell($row); new TableCell($row); new TableCell($row); new TableCell($row); new TableCell($row);
		if(isset($permissions['group']))
		{
			foreach($permissions['group'] as $group => $permission)
			{
				$group = htmlspecialchars($group);
				$row = self::createPermissionsTableRow($table, "group_{$group}", $group, $permission);
				$cell = new TableCell($row); $button = new Button($cell, ''); $button->setValue(i18n('Delete'));
				$button->addJavascript('onclick', "ADMS_removeRow('group', '$group'); return false;");
				$key = array_search($group, $availableGroups);
				if($key !== false)
				{
					unset($availableGroups[$key]);
				}
			}
		}

		// other
		$row = new TableRow($table);
		$row->setId('ADMS_othersRow');
		$cell = new TableCell($row, i18n('Other')); $cell->addCssStyle('font-weight: bold'); new TableCell($row); new TableCell($row); new TableCell($row); new TableCell($row); new TableCell($row); new TableCell($row);
		$permission = $permissions['other'];
		self::createPermissionsTableRow($table, 'other', '', $permission);

		$row = new TableRow($table);
		$cell = new TableCell($row);
		$cell->setColumnSpan(7);
		$usersInput = new SelectInput($cell, 'ADMS_usersSelect');
		$usersInput->setOptions($availableUsers);
		$usersInput->addCssStyle('width: 10em');
		$button = new Button($cell, 'ADMS_userAddButton');
		$button->setValue(i18n('Add user'));
		$button->setEnabled(sizeof($availableUsers) > 0);
		$button->addJavascript('onclick', "ADMS_addRow('user', '".i18n('Delete')."'); return false;");
		$groupsInput = new SelectInput($cell, 'ADMS_groupsSelect');
		$groupsInput->setOptions($availableGroups);
		$groupsInput->addCssStyle('width: 10em');
		$button = new Button($cell, 'ADMS_groupAddButton');
		$button->setValue(i18n('Add group'));
		$button->setEnabled(sizeof($availableGroups) > 0);
		$button->addJavascript('onclick', "ADMS_addRow('group', '".i18n('Delete')."'); return false;");
		$row = new TableRow($table);
		$cell = new TableCell($row);
		$cell->setColumnSpan(7);
		$groupsInput = new TextInput($cell, 'ADMS_ipInput');
		$button = new Button($cell, 'ADMS_ipAddButton');
		$button->setValue(i18n('Add IP range'));
		$button->addJavascript('onclick', "ADMS_addIpRow('".i18n('Delete')."'); return false;");

		$recursiveCheckbox = new CheckboxInput($form, 'ADMS_applyRecursivePermissions');
		$recursiveCheckbox->setText(i18n('Apply permissions recursively.'));
		$recursiveCheckbox->addCssStyle('margin-left: 20px');
	}

	private static function createPermissionsTableRow(Table $table, $type, $name, $permission)
	{
		$row = new TableRow($table);
		$row->setId("ADMS_$type");
		$cell = new TableCell($row, $name);
		$hiddenInput = new HiddenInput($cell, "ADMS_{$type}_none");
		$hiddenInput->setValue('true');
		$cell = new TableCell($row); $checkbox = new CheckboxInput($cell, "ADMS_{$type}_read");         $checkbox->setChecked($permission & PERMISSION_READ);
		$cell = new TableCell($row); $checkbox = new CheckboxInput($cell, "ADMS_{$type}_append");       $checkbox->setChecked($permission & PERMISSION_APPEND);
		$cell = new TableCell($row); $checkbox = new CheckboxInput($cell, "ADMS_{$type}_modify");       $checkbox->setChecked($permission & PERMISSION_MODIFY);
		$cell = new TableCell($row); $checkbox = new CheckboxInput($cell, "ADMS_{$type}_delete");       $checkbox->setChecked($permission & PERMISSION_DELETE);
		$cell = new TableCell($row); $checkbox = new CheckboxInput($cell, "ADMS_{$type}_administrate"); $checkbox->setChecked($permission & PERMISSION_ADMINISTRATE);

		return $row;
	}

	private function newDocument()
	{
		// if the user clicked the cancel button, go back to browsing
		if(Config::request('ADMS_button') == i18n('Cancel'))
		{
			$this->browse();
			return;
		}

		// show the first form
		if(Config::request('ADMS_doctype') == '')
		{
			new PageIcon($this, 'base/icons/MIME/unknown');

			$paragraph = new Paragraph($this);
			$paragraph->setId('ADMS_uploadingMessage');
			$paragraph->setCssStyle('display: none; border: thin solid black; margin: 2px; background-color: #ffc; width: 70%');
			$image = new Image($paragraph, 'resources/base/icons/buttons/info.png');
			$image->setCssStyle('vertical-align: middle');
			new Label($paragraph, i18n('The file is being sent. Please be patient.'));

			$form = new Form($this, Config::globals('baseURL')."?view=ADMS&amp;ADMS_view=NewDocument");
			$form->setId('ADMS_NewDocument');
			$form->addJavaScript('onsubmit', "if(document.getElementById('ADMS_upload').checked == true) document.getElementById('ADMS_uploadingMessage').style.display = 'block';");
			new Paragraph($form, i18n('Select one of the following document types to add:'));
			$radioGroup = new RadioGroup($form, 'ADMS_doctype');
			$radioButton = new RadioButton($radioGroup, 'ADMS_text/plain');
			$radioButton->setText(i18n('Plain text'));
			$radioButton->setChecked(true);
			$radioButton = new RadioButton($radioGroup, 'ADMS_upload');
			$radioButton->setText(i18n('Use this document: '));
			$fileInput = new FileInput($radioButton, 'ADMS_file');
			$fileInput->addJavaScript('onclick', "document.getElementById('ADMS_upload').checked = true;");
			$buttonBox = new Box($form);
			$button = new Button($buttonBox, 'ADMS_button');
			$button->setValue(i18n('Next'));
			$button->setConfirm(true);
			$button = new Button($buttonBox, 'ADMS_button');
			$button->setValue(i18n('Cancel'));

			$form->addJavaScriptCheck("document.getElementById('ADMS_upload').checked == true && ".
			                          "document.getElementById('ADMS_file').value == ''",
			                          i18n('Please select a file to upload.'));
		}
		// redirect to the second form
		else
		{
			switch(Config::request('ADMS_doctype'))
			{
				case 'ADMS_text/plain':
					$this->editDocument(true);
					break;

				case 'ADMS_upload':
					$this->newUploadDocument();
					break;

				default:
					$this->browse();
			}
		}
	}

	private function newUploadDocument()
	{
		$mimetype = MIME::type('upload://ADMS_file');
		$description = MIME::description($mimetype);
		$icon = (PageIcon::iconExists("base/icons/MIME/$mimetype") ? "base/icons/MIME/$mimetype" : 'base/icons/MIME/application/octet-stream');
		$tmpURI = URI::uniquePath('tmp://', URI::metaData('upload://ADMS_file', 'name'));
		URI::copy('upload://ADMS_file', $tmpURI);

		if(String::startsWith($mimetype, 'application/vnd.oasis.opendocument.'))
		{
			$openDocument = new OpenDocument();
			$openDocument->load($tmpURI);
			$openDocument->scaleImages(800, 600);
		}

		new PageIcon($this, $icon);

		$form = $this->createFormHeader(0, true, $tmpURI, $mimetype);
		$hiddenInput = new HiddenInput($form, 'ADMS_doctype');
		$hiddenInput->setValue('ADMS_upload');
		$hiddenInput = new HiddenInput($form, 'ADMS_uploadFile');
		$hiddenInput->setValue(htmlspecialchars($tmpURI));
		$hiddenInput = new HiddenInput($form, 'ADMS_mimetype');
		$hiddenInput->setValue($mimetype);
		new Paragraph($form, i18n("The document you uploaded is of type: %1", $description));
		$buttonBox = new Box($form);
		$button = new Button($buttonBox, 'ADMS_button');
		$button->setValue(i18n('Finish'));
		$button->setConfirm(true);
		$button = new Button($buttonBox, 'ADMS_button');
		$button->setValue(i18n('Cancel'));
		if(Document::hasViewer($mimetype))
		{
			new Ruler($form);
			$previewParagraph = new Paragraph($form, i18n('Preview:'));
			$previewParagraph->addCssStyle('font-weight: bold');
			new DocumentViewer($form, $tmpURI, $mimetype);
		}
	}

	private function newAttachement()
	{
		// if the user clicked the cancel button, go back to browsing
		if(Config::request('ADMS_button') == i18n('Cancel'))
		{
			$this->browse();
			return;
		}

		new PageIcon($this, 'base/icons/MIME/unknown');

		$form = new Form($this, Config::globals('baseURL')."?view=ADMS&amp;ADMS_action=NewAttachement");
		$form->setId('ADMS_NewDocument');
		$form->addJavaScript('onsubmit', "document.getElementById('ADMS_filename').value = document.getElementById('ADMS_file').value;");
		new Paragraph($form, i18n('Please select a file to attach to the document:'));
		$hiddenInput = new HiddenInput($form, 'ADMS_filename');
		$fileInput = new FileInput($form, 'ADMS_file');
		$fileInput->setRequired(true);
		$fileInput->setText(i18n('Select a file:'));
		$buttonBox = new Box($form);
		$button = new Button($buttonBox, 'ADMS_button');
		$button->setValue(i18n('Finish'));
		$button->setConfirm(true);
		$button = new Button($buttonBox, 'ADMS_button');
		$button->setValue(i18n('Cancel'));
	}

	private function newLink()
	{
		// if the user clicked the cancel button, go back to browsing
		if(Config::request('ADMS_button') == i18n('Cancel'))
		{
			$this->browse();
			return;
		}

		new PageIcon($this, 'base/icons/MIME/text/x-uri');

		// show the first form
		/*if(Config::request('ADMS_doctype') == '')
		{
			$form = new Form($this, Config::globals('baseURL')."?view=ADMS&amp;ADMS_view=NewLink&amp;ADMS_location0={$this->directory}");
			new Paragraph($form, i18n('Add a new link ...'));
			$radioGroup = new RadioGroup($form, 'ADMS_doctype');
			$radioButton = new RadioButton($radioGroup, 'ADMS_internal');
			$radioButton->setText(i18n('to an internal document.'));
			$radioButton->setChecked(true);
			$radioButton = new RadioButton($radioGroup, 'ADMS_external');
			$radioButton->setText(i18n('to an external URL.'));
			$buttonBox = new Box($form);
			$button = new Button($buttonBox, 'ADMS_button');
			$button->setValue(i18n('Next'));
			$button->setConfirm(true);
			$button = new Button($buttonBox, 'ADMS_button');
			$button->setValue(i18n('Cancel'));
		}
		// redirect to the second form
		else
		{
			switch(Config::request('ADMS_doctype'))
			{
				case 'ADMS_internal': $this->newDocumentLink(); break;
				case 'ADMS_external': $this->newURLLink(); break;

				default:
					$this->browse();
			}
		}*/
		$this->newURLLink();
	}

	/*private function newDocumentLink()
	{
		if($this->document == '')
		{
			$this->viewDirectory(false, false, '&amp;ADMS_doctype=ADMS_internal');
		}
	}*/

	private function newURLLink()
	{
		$form = $this->createFormHeader(1);
		$hiddenInput = new HiddenInput($form, 'ADMS_doctype');
		$hiddenInput->setValue('ADMS_external');
		$urlInput = new TextInput($form, 'ADMS_url');
		$urlInput->setText(i18n('Please enter the URL to link to: '));
		$urlInput->setValue('http://');
		$buttonBox = new Box($form);
		$button = new Button($buttonBox, 'ADMS_button');
		$button->setValue(i18n('Finish'));
		$button->setConfirm(true);
		$button = new Button($buttonBox, 'ADMS_button');
		$button->setValue(i18n('Cancel'));

		$form->addJavaScriptCheck("document.getElementById('url').value == '' || ".
		                          "document.getElementById('url').value == 'http://'",
		                          i18n('Please enter a URL to link to.'));
	}

	private function editDocument($new = false)
	{
		$uri = $new ? '' : "{$this->directory}/{$this->document}";
		$mimetype = $new ? String::substringAfter(Config::request('ADMS_doctype'), 'ADMS_') :
		                   MIME::type($uri);

		new PageIcon($this, "base/icons/MIME/$mimetype");

		$form = $this->createFormHeader(0, $new, $uri);
		$hiddenInput = new HiddenInput($form, 'ADMS_doctype');
		$hiddenInput->setValue("ADMS_$mimetype");
		if(Document::hasEditor($mimetype))
		{
			new DocumentEditor($form, 'ADMS_document', $uri, $mimetype);
		}
		else if(String::startsWith($mimetype, 'application/vnd.oasis.opendocument.'))
		{
			$paragraph = new Paragraph($form);
			$name = String::stripSpecialChars(URI::metaData($uri, 'name')).
			        MIME::extension($mimetype);
			$line = new Line($paragraph);
			$link = new Link($line, Config::globals('editURL')."?file=$uri&amp;name=$name&amp;username={$_COOKIE['username']}&amp;sessionid={$_COOKIE['sessionid']}");
			$link->setText(i18n('Edit document with OpenOffice.org'));
			$line = new Line($paragraph, i18n('Right-click the link and select Copy Link Location, then open the link in OpenOffice.org.'));
		}
		$buttonBox = new Box($form);
		$button = new Button($buttonBox, 'ADMS_button');
		$button->setValue($new ? i18n('Finish') : i18n('OK'));
		$button->setConfirm(true);
		$button = new Button($buttonBox, 'ADMS_button');
		$button->setValue(i18n('Cancel'));

		return $form;
	}

	private function editFolder($new = false)
	{
		new PageIcon($this, 'base/icons/MIME/inode/directory');

		$description = $new ? '' : URI::metaData($this->directory, 'description');

		$form = $this->createFormHeader(2, $new, $this->directory);
		$sortInput = new SelectInput($form, 'ADMS_sort');
		$sortInput->setText(i18n('Entries in this folder will be sorted:'));
		$sortInput->setOptions(array('alphabetical' => i18n('Alphabetically'),
		                             'newestFirst'  => i18n('Newest first')));
		$value = ($new ? $this->config->variable('sortListings', 'alphabetical') :
		                 URI::metaData($this->directory, 'ADMS-sort', 'alphabetical'));
		$sortInput->setValue($value);
		$headerBox = new CheckboxInput($form, 'ADMS_header');
		$headerBox->setText(i18n('Has header text.'));
		$headerBox->setChecked($description != '');
		$headerBox->addJavaScript('onclick', "descBlock = document.getElementById('ADMS_descriptionBlock'); ".
		                                     "if(descBlock.style.display == 'none') { ".
		                                         "descBlock.style.display = 'block'; ".
		                                     "} else { ".
		                                         "descBlock.style.display = 'none'; ".
		                                     "}");
		$display = ($description == '' ? 'none' : 'block');
		$box = new Box($headerBox, 'ADMS_descriptionBlock');
		$box->addCssStyle("display: $display; height: 210px");
		$textArea = new TextArea($box, 'ADMS_description');
		$textArea->setValue(htmlspecialchars($description));
		$textArea->setColumns(80);
		$textArea->addCssStyle('height: 200px');
		$buttonBox = new Box($form);
		$button = new Button($buttonBox, 'ADMS_button');
		$button->setValue($new ? i18n('Finish') : i18n('OK'));
		$button->setConfirm(true);
		$button = new Button($buttonBox, 'ADMS_button');
		$button->setValue(i18n('Cancel'));
	}

	private function showBrowseButtons($parent, $index = 0)
	{
		if(String::startsWith(Login::username(), 'anonymous') == false)
		{
			if(Login::sessionVariable('ADMS_splitView') == 'true')
			{
				$link = new Link($parent, Config::globals('baseURL')."?view=ADMS&amp;ADMS_action=CloseView&amp;ADMS_pane=$index");
				$link->setText(i18n('[Close View]'));
				$link->addCssStyle('float: right');
			}
			else
			{
				$link = new Link($parent, Config::globals('baseURL')."?view=ADMS&amp;ADMS_action=SplitView");
				$link->setText(i18n('[Split View]'));
				$link->addCssStyle('float: right');
			}
		}

		$backLocation = Config::request("ADMS_oldLocation$index");
		if($backLocation == '')
		{
			$backLocation = dirname($this->locationArray[$index]);
		}
		$paragraph = new Paragraph($parent);
		if(String::startsWith($backLocation, 'ADMS://docs/0') ||
		   String::startsWith($backLocation, 'ADMS_Search://'))
		{
			$link = new Link($paragraph, Config::globals('baseURL')."?view=ADMS&amp;ADMS_location$index=$backLocation");
			$link->setText(i18n('Back'));
			$link->setCssStyle('font-weight: bold');
		}
		else
		{
			$label = new Label($paragraph, i18n('Back'));
			$label->setCssStyle('font-weight: bold');
		}
		new Label($paragraph, ' | ');
		$link = new Link($paragraph, Config::globals('baseURL')."?view=ADMS&amp;ADMS_location$index=ADMS://docs/0");
		$link->setText(i18n('Home'));
		$link->addCssStyle('font-weight: bold');
	}

	private function showEmailDocumentForm()
	{
		new PageIcon($this, 'base/icons/email');

		$name = URI::metaData($this->locationArray[0], 'name', basename($this->locationArray[0]));
		$mimeType = MIME::type($this->locationArray[0]);

		new ExternalJavaScript($this, 'resources/apps/ADMS/mailScripts.js');
		$form = new Form($this, Config::globals('baseURL').'?view=ADMS&amp;ADMS_view=Browse&amp;ADMS_action=EmailDocument');
		$form->useGridLayout(true);
		$form->addJavaScript('onsubmit', 'ADMS_updateSelectedRecipients();');
		$form->setErrorMessage(i18n('Please select at least one recipient.'));
		$this->addFormSubmit($form);
		new Paragraph($form, i18n('Mailing document <label style="font-weight: bold">%1</label>.', htmlspecialchars($name)));
		new Paragraph($form, i18n('Please enter a subject for the mail and select the recipients.'));
		$subjectInput = new TextInput($form, 'ADMS_subject');
		$subjectInput->setText(i18n('Subject:'));
		$subjectInput->setValue($name);
		$subjectInput->addCssStyle('width: 24em');
		$recipientsInput = new SelectInput($form, 'ADMS_recipientsSelect');
		$recipientsInput->setText(i18n('Recipients:'));
		$recipientsInput->setRequired(true);
		$recipientsInput->setMultiple(true, 10);
		$recipientsInput->addCssStyle('width: 25em');
		$options = array();
		foreach(Login::users() as $user)
		{
			$email = Login::userMail($user);
			if($email != '')
			{
				$fullName = Login::fullname($user);
				$options[$user] = htmlspecialchars("$fullName <$email>");
			}
		}
		asort($options);
		$recipientsInput->setOptions($options);
		/*if($mimeType == 'application/vnd.oasis.opendocument.text')
		{
			$pdfCheckbox = new CheckboxInput($form, 'ADMS_convertToPdf');
			$pdfCheckbox->setText(i18n('Send this document as PDF.'));
		}*/

		$buttonBox = new Box($form);
		$button = new Button($buttonBox, 'ADMS_button');
		$button->setValue(i18n('Send Mail'));
		$button->setConfirm(true);
		$button = new Button($buttonBox, 'ADMS_button');
		$button->setValue(i18n('Cancel'));
	}

	private $view;
	private $action;
	private $fileSystem;
	private $accessArray;
	private $config;
	private $directory;
	private $document;
	private $locationArray;
	private $locationChanged;
	private $menu;
}

?>
Return current item: Aukyla Document Management System