<?php
	require_once(dirname(__FILE__).'/class.adminview.php');

	class AKB_LAYOUT extends AdminView
	{
		var $_templatePath = '';

		/**
		* Constructor
		* Setup some variables for this class
		*
		* @return void
		*/
		function AKB_LAYOUT()
		{
			$this->_SetTemplatePath();
			$this->_SetValidExtensions();
		}

		/**
		* HanldeToDo
		* The default page handler, routes requests to the right functions
		*
		* @return void
		*/
		function HandleToDo($Do)
		{
			switch (strtolower($Do)) {
				case 'restoretemplate':
					if ($_SESSION['user']->verify('template', 'edit')) {
						$GLOBALS['AKB_CLASS_TEMPLATE']->PrintHeader();
						$this->RestoreTemplate();
						$GLOBALS['AKB_CLASS_TEMPLATE']->PrintFooter();
					} else {
						$this->NoPermission();
					}
					break;
				case 'saveupdatedtemplate':
					if ($_SESSION['user']->verify('template', 'edit')) {
						$GLOBALS['AKB_CLASS_TEMPLATE']->PrintHeader();
						$this->SaveUpdatedTemplate();
						$GLOBALS['AKB_CLASS_TEMPLATE']->PrintFooter();
					} else {
						$this->NoPermission();
					}
					break;
				case 'edittemplate':
					if ($_SESSION['user']->verify('template', 'edit')) {
						$GLOBALS['AKB_CLASS_TEMPLATE']->PrintHeader();
						$this->EditLayout();
						$GLOBALS['AKB_CLASS_TEMPLATE']->PrintFooter();
					} else {
						$this->NoPermission();
					}
					break;
				default:
					if ($_SESSION['user']->verify('template', 'edit')) {
						$GLOBALS['AKB_CLASS_TEMPLATE']->PrintHeader();
						$this->ManageLayouts();
						$GLOBALS['AKB_CLASS_TEMPLATE']->PrintFooter();
					} else {
						$this->NoPermission();
					}
			}
		}

		/**
		* RestoreTemplate
		* Restore a template from the backup copy
		*
		* @return void
		*/
		function RestoreTemplate()
		{
			if (!$_SESSION['user']->verify('template', 'edit')) {
				$this->NoPermission();
				return;
			}

			// Restore a template from a backup copy
			if (isset($_GET['template']) && isset($_GET['file'])) {
				$template = $_GET['template'];
				$file = $_GET['file'];
				$templatePath = sprintf('%s/%s/%s', $this->_GetTemplatePath(), $template, $file);
				$restorePath = sprintf('%s/%s/Backup/%s', $this->_GetTemplatePath(), $template, $file);

				if (file_exists($restorePath)) {
					// Copy the backup of the template
					if (@copy($restorePath, $templatePath)) {
						$this->ManageLayouts(sprintf(GetLang('TemplateRestoredSuccessfully'), $file), MSG_SUCCESS, $template);
					} else {
						// Couldn't save the template
						$rfile = sprintf('%s/%s/%s', $this->_GetTemplatePath(), $template, $file);
						$this->ManageLayouts(sprintf(GetLang('TemplateNotSaved'), realpath($rfile)), MSG_ERROR, $template);
					}
				} else {
					$this->ManageLayouts(sprintf(GetLang('TemplateHasNoBackup'), $file), MSG_ERROR, $template);
				}
			} else {
				$this->ManageLayouts();
			}
		}

		/**
		* _CommitFile
		* Write a file to disk after changes have been made to it
		*
		* @param string $Template The name of the template
		* @param string $File The name of the file
		* @param string $FileData the data to write to disk
		*
		* @return bool Was the update succesful ?
		*/
		function _CommitFile($Template, $File, $FileData)
		{
			if (!$_SESSION['user']->verify('template', 'edit')) {
				$this->NoPermission();
				return;
			}

			// Perform some data validation on the template and file variables
			$Template = $this->_MakeSafeData($Template);
			$File = $this->_MakeSafeData($File);
			$FileData = stripslashes($FileData);

			// Save the file data to the specifed template file
			if ($fp = @fopen(sprintf('%s/%s/%s', $this->_GetTemplatePath(), $Template, $File), 'wb')) {
				if (fwrite($fp, $FileData, strlen($FileData))) {
					@fclose($fp);
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		}

		/**
		* SaveUpdatedTemplate
		* Update a file and display a message depending on if the update worked
		*
		* @return void
		*/
		function SaveUpdatedTemplate()
		{
			if (!$_SESSION['user']->verify('template', 'edit')) {
				$this->NoPermission();
				return;
			}

			if (isset($GLOBALS['BreadcrumEntries'][GetLang("EditTemplateTitle")])) {
				unset($GLOBALS['BreadcrumEntries'][GetLang("EditTemplateTitle")]);
			}

			
			// Get the template data from viewstate
			if (isset($_POST['filedata'])) {
				$GLOBALS['BreadcrumEntries'][GetLang("ManageTemplates")] = "index.php?ToDo=viewTemplates";
			
				$template = $_POST['template'];
				$file = $_POST['file'];
				$fileData = $_POST['filedata'];

				$outfile = realpath(sprintf('%s/%s/%s', $this->_GetTemplatePath(), $template, $file));

				if (is_writeable($outfile) && $this->_CommitFile($template, $file, $fileData)) {
					$_GET['template'] = $template;
					$_GET['file'] = $file;

					if (isset($_POST['Save'])) {
						$this->EditLayout(sprintf(GetLang('TemplateUpdatedSuccessfully'), $file), MSG_SUCCESS, $template, $file);
					} else {
						$this->ManageLayouts(sprintf(GetLang('TemplateUpdatedSuccessfully'), $file), MSG_SUCCESS, $template, $file);
					}
				} elseif (!is_writeable($outfile)) {
					$GLOBALS['Title'] = GetLang('TemplateNotSaved');
					$GLOBALS['Message'] = MessageBox(sprintf(GetLang('TemplateWrongPermissions'), $outfile), MSG_ERROR);
					$GLOBALS['ButtonText'] = GetLang('TryAgain');

					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('messagetryagain');
					$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
				} else {
					// Couldn't save the template
					$rfile = sprintf('%s/%s/%s', $this->_GetTemplatePath(), $template, $file);
					$this->ManageLayouts(sprintf(GetLang('TemplateNotSaved'), $rfile), MSG_ERROR, $template);
				}
			} else {
				// Couldn't save the template
				$this->ManageLayouts();
			}
		}

		/**
		* EditLayout
		* Display the screen for editing a template, panel etc
		*
		* @param string $MsgDesc The text of any messages to display
		* @param int $MsgStatus The type of message
		* @param string $Template the name of the template being edited
		* @param string $File The name of the file being edited
		*
		* @return void
		*/
		function EditLayout($MsgDesc = '', $MsgStatus = '', $Template = '', $File = '')
		{
			if (!$_SESSION['user']->verify('template', 'edit')) {
				$this->NoPermission();
				return;
			}

			if ($Template != '') {
				$_GET['template'] = $Template;
				$_GET['file'] = $File;

				$MsgDesc = str_replace('Panels/', '', $MsgDesc);

				if ($MsgDesc != '') {
					$GLOBALS['Message'] = MessageBox($MsgDesc, $MsgStatus);
				}
			}

			if (isset($_GET['template']) && isset($_GET['file'])) {
				$template = $_GET['template'];
				$file = $_GET['file'];
				$GLOBALS['FileData'] = $this->_GetFileData($template, $file);
				$GLOBALS['Template'] = $template;
				$GLOBALS['File'] = $file;
				$GLOBALS['ContentsHeader'] = sprintf(GetLang('TemplateContent'), $file);
				$GLOBALS['ContentsHeader'] = str_replace('Panels/', '', $GLOBALS['ContentsHeader']);

				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('layout.form');
				$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
			} else {
				$this->ManageLayouts();
			}
		}

		/**
		* _MakeSafeData
		* Kill any risky patterns from the string
		*
		* @param string $Val The value to sanitise
		*
		* @return string The safe string
		*/
		function _MakeSafeData($Val)
		{
			// Kill any risky patterns from the string
			$Val = eregi_replace("\.{1,}/", "", $Val);
			$Val = str_replace("\\", "", $Val);

			return $Val;
		}

		/**
		* _GetFileData
		* Get the contents of a template file from its file or from the form
		*
		* @param string $Template the name of the template
		* @param string $File the name of the file
		*
		* @return string The contents of the file
		*/
		function _GetFileData($Template, $File)
		{
			$fileData = '';

			// Perform some data validation on the template and file variables
			$Template = $this->_MakeSafeData($Template);
			$File = $this->_MakeSafeData($File);

			// Get the data from the file
			if ($fp = fopen(sprintf('%s/%s/%s', $this->_GetTemplatePath(), $Template, $File), 'rb')) {
				// The template is open, let's get its contents
				while (!feof($fp)) {
					$fileData .= fgets($fp, 4096);
				}

				fclose($fp);
			}

			return htmlspecialchars($fileData, ENT_QUOTES, $GLOBALS['charset']);
		}

		/**
		* ManageLayouts
		* Show a list of files that compose the current template
		*
		* @param string $MsgDesc The text of any messages to display
		* @param int $MsgStatus The type of message
		* @param string $Template the name of the template being displayed
		*
		* @return void
		*/
		function ManageLayouts($MsgDesc = "", $MsgStatus = "", $Template = "")
		{
			if (!$_SESSION['user']->verify('template', 'edit')) {
				$this->NoPermission();
				return;
			}

			$arrTpl = "";
			$GLOBALS['BreadcrumEntries'][GetLang("ManageTemplates")] = "index.php?ToDo=viewTemplates";
			$GLOBALS["FolderName"] = GetLang("LayoutFiles");
			$GLOBALS["Title"] = GetLang("ExpandLayoutFiles");
			$GLOBALS['FileType'] = "layout";
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("layout.tree.row");
			$GLOBALS["LayoutGrid"] = $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
			$GLOBALS["Counter"] = 0;
			$GLOBALS['Message'] = '';
			$GLOBALS['Nav'] = '';

			if (isset($_GET["t"])) {
				$template = $_GET["t"];
			} else {
				$template = $GLOBALS["template"];
			}

			if ($Template != "") {
				$template = $Template;
			}

			$templatePath = sprintf("%s/%s", $this->_GetTemplatePath(), $template);

			if (is_dir($templatePath)) {
				$GLOBALS["LayoutIntro"] = GetLang("TemplateIntro");

				// Get a list of all files in this template and output them with
				// both edit and restore original links

				$arrTpl = $this->_GetTemplateFilesAsArray($template);
				$GLOBALS["Template"] = $template;

				foreach ($arrTpl as $tpl) {
					$GLOBALS["FileName"] = $tpl;
					$GLOBALS["FileType1"] = GetLang("HTMLTemplateFile");
					$GLOBALS["TemplateFile"] = $tpl;
					$GLOBALS["Counter"]++;
					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("layout.manage.row");
					$GLOBALS["LayoutGrid"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
				}

				$GLOBALS["Counter"]++;

				$GLOBALS["LayoutMax"] = $GLOBALS["Counter"];

				// Add the panel files
				$GLOBALS["FolderName"] = GetLang("PanelFiles");
				$GLOBALS["Title"] = GetLang("ExpandPanelFiles");
				$GLOBALS["FileType"] = "panel";
				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("layout.tree.row");
				$GLOBALS["LayoutGrid"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);

				$arrPanels = $this->_GetPanelFilesAsArray($template);

				foreach ($arrPanels as $panel) {
					$GLOBALS["FileName"] = $panel;
					$GLOBALS["TemplateFile"] = sprintf("Panels/%s", $panel);
					$GLOBALS["Counter"]++;

					// Workout the file type
					if (is_numeric(strpos($panel, ".php"))) {
						$GLOBALS["FileType1"] = GetLang("PHPPanelFile");
					} else {
						$GLOBALS["FileType1"] = GetLang("HTMLPanelFile");
					}

					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("layout.manage.row");
					$GLOBALS["LayoutGrid"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
				}

				$GLOBALS["Counter"]++;

				$GLOBALS["PanelMax"] = $GLOBALS["Counter"];

				// Add the style files
				$GLOBALS["FolderName"] = GetLang("StyleFiles");
				$GLOBALS["Title"] = GetLang("ExpandStyleFiles");
				$GLOBALS["FileType"] = "stylesheet";
				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("layout.tree.row");
				$GLOBALS["LayoutGrid"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);

				$arrStyles = $this->_GetStyleFilesAsArray($template);

				foreach ($arrStyles as $style) {
					$GLOBALS["FileName"] = $style;
					$GLOBALS["TemplateFile"] = sprintf("Styles/%s", $style);
					$GLOBALS["Counter"]++;

					$GLOBALS["FileType1"] = GetLang("CSSFile");

					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("layout.manage.row");
					$GLOBALS["LayoutGrid"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
				}

				$GLOBALS["Counter"]++;

				$GLOBALS["StyleMax"] = $GLOBALS["Counter"];

				// Add the snippet files
				$GLOBALS["FolderName"] = GetLang("SnippetFiles");
				$GLOBALS["Title"] = GetLang("ExpandSnippetFiles");
				$GLOBALS["FileType"] = "snippet";
				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("layout.tree.row");
				$GLOBALS["LayoutGrid"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);

				$arrPanels = $this->_GetSnippetFilesAsArray($template);

				foreach ($arrPanels as $panel) {
					$GLOBALS["FileName"] = $panel;
					$GLOBALS["TemplateFile"] = sprintf("Snippets/%s", $panel);
					$GLOBALS["Counter"]++;

					// Workout the file type
					if (is_numeric(strpos($panel, ".php"))) {
						$GLOBALS["FileType1"] = GetLang("PHPSnippetFile");
					} else {
						$GLOBALS["FileType1"] = GetLang("HTMLSnippetFile");
					}

					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("layout.manage.row");
					$GLOBALS["LayoutGrid"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
				}

				$GLOBALS["Counter"]++;

				$GLOBALS["SnippetMax"] = $GLOBALS["Counter"];
			} else {
				// Bad template directory chosen
				$GLOBALS["LayoutIntro"] = MessageBox(GetLang("TemplateDoesntExist"), MSG_ERROR);
				$GLOBALS["DisplayGrid"] = "none";
				$template = $GLOBALS["template"];
			}

			$MsgDesc = str_replace("Panels/", "", $MsgDesc);
			$MsgDesc = str_replace("Styles/", "", $MsgDesc);
			$MsgDesc = str_replace("Snippets/", "", $MsgDesc);
			if ($MsgDesc != '') {
				$GLOBALS["Message"] = MessageBox($MsgDesc, $MsgStatus);
			}

			$GLOBALS["TemplateList"] = $this->_GetTemplateOptions($template);
			$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("layout.manage");
			$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
		}

		/**
		* _SetTemplatePath
		* Set the filesystem path to the templates directory
		*
		* @return void
		*/
		function _SetTemplatePath()
		{
			$this->_templatePath = dirname(__FILE__).'/../../../templates';
		}

		/**
		* _GetTemplatePath
		* Return the filsystem path to the template
		*
		* @return string The path
		*/
		function _GetTemplatePath()
		{
			return $this->_templatePath;
		}

		/**
		* _GetTemplateOptions
		* Get the html for displaying the list of installed templates as options
		*
		* @param string $SelectedTemplate
		*
		* @return string The html for the options
		*/
		function _GetTemplateOptions($SelectedTemplate)
		{
			// Get a list of templates and return them as option tags
			$output = "";
			$templatePath = $this->_GetTemplatePath();
			$arrFiles = array();

			if ($handle = opendir($templatePath)) {
				while (false !== ($file = readdir($handle))) {
					if ($file != '.' && $file != '..' && $file != 'CVS') {
						$arrFiles[] = $file;
					}
				}

				closedir($handle);
				sort($arrFiles);

				foreach ($arrFiles as $key=>$file) {
					if (strtolower($file) == strtolower($SelectedTemplate)) {
						$sel = 'SELECTED';
					} else {
						$sel = '';
					}

					$output .= sprintf('<option value="%s" %s>%s</option>', $file, $sel, $file);
					$GLOBALS['templates'][] = $file;
				}
			}

			return $output;
		}

		/**
		* _GetTemplateFilesAsArray
		* Get the list of files in a template as an array
		*
		* @param string $SelectedTemplate The template to get the list for
		*
		* @return array The list of files
		*/
		function _GetTemplateFilesAsArray($SelectedTemplate)
		{
			// Get a list of templates and return them as an array
			$arrTpl = array();
			$templatePath = sprintf('%s/%s', $this->_GetTemplatePath(), $SelectedTemplate);

			if ($handle = opendir($templatePath)) {
				while (false !== ($file = readdir($handle))) {
					$arrTmp = explode('.', $file);
					$extension = strtolower($arrTmp[sizeof($arrTmp)-1]);

					if ($file != '.' && $file != '..' && in_array($extension, $this->_GetValidExtensions())) {
						$arrTpl[] = $file;
					}
				}

				closedir($handle);
				sort($arrTpl);
			}

			return $arrTpl;
		}

		/**
		* _GetPanelFilesAsArray
		* Get the list of panels files in a template as an array
		*
		* @param string $SelectedTemplate The template to get the list for
		*
		* @return array The list of panel files
		*/
		function _GetPanelFilesAsArray($SelectedTemplate)
		{
			// Get a list of templates and return them as an array
			$arrPanel = array();
			$templatePath = sprintf("%s/%s/Panels", $this->_GetTemplatePath(), $SelectedTemplate);

			if ($handle = opendir($templatePath)) {
				while (false !== ($file = readdir($handle))) {
					$arrTmp = explode(".", $file);
					$extension = strtolower($arrTmp[sizeof($arrTmp)-1]);

					if ($file != "." && $file != ".." && in_array($extension, $this->_GetValidExtensions())) {
						$arrPanel[] = $file;
					}
				}

				closedir($handle);
				sort($arrPanel);
			}

			return $arrPanel;
		}

		/**
		* _GetStyleFilesAsArray
		* Get the list of style files in a template as an array
		*
		* @param string $SelectedTemplate The template to get the list for
		*
		* @return array The list of style files
		*/
		function _GetStyleFilesAsArray($SelectedTemplate)
		{
			// Get a list of templates and return them as an array
			$arrPanel = array();
			$templatePath = sprintf("%s/%s/Styles", $this->_GetTemplatePath(), $SelectedTemplate);

			if ($handle = opendir($templatePath)) {
				while (false !== ($file = readdir($handle))) {
					$arrTmp = explode('.', $file);
					$extension = strtolower($arrTmp[sizeof($arrTmp)-1]);

					if ($file != '.' && $file != '..' && in_array($extension, $this->_GetValidExtensions())) {
						$arrPanel[] = $file;
					}
				}

				closedir($handle);
				sort($arrPanel);
			}

			return $arrPanel;
		}

		/**
		* _GetSnippetFilesAsArray
		* Get the list of snippet files in a template as an array
		*
		* @param string $SelectedTemplate The template to get the list for
		*
		* @return array The list of style files
		*/
		function _GetSnippetFilesAsArray($SelectedTemplate)
		{
			// Get a list of templates and return them as an array
			$arrPanel = array();
			$templatePath = sprintf("%s/%s/Snippets", $this->_GetTemplatePath(), $SelectedTemplate);

			if ($handle = opendir($templatePath)) {
				while (false !== ($file = readdir($handle))) {
					$arrTmp = explode('.', $file);
					$extension = strtolower($arrTmp[sizeof($arrTmp)-1]);

					if ($file != '.' && $file != '..' && in_array($extension, $this->_GetValidExtensions())) {
						$arrPanel[] = $file;
					}
				}

				closedir($handle);
				sort($arrPanel);
			}

			return $arrPanel;
		}

		/**
		* _SetValidExtensions
		* Setup the list of valid file extensions
		*
		* @return void
		*/
		function _SetValidExtensions()
		{
			$this->_tplExtensions = array('htm', 'html', 'css', 'xslt');
		}

		/**
		* _GetValidExtensions
		* Returns the list of valid file extensions (without the leading .)
		*
		* @return array The array of file extensions
		*/
		function _GetValidExtensions()
		{
			return $this->_tplExtensions;
		}



	}

?>