<?php
/**
* @version	$Id: theme_file_eh.php 14241 2011-03-16 20:24:35Z alex $
* @package	In-Portal
* @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license      GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/

	defined('FULL_PATH') or die('restricted access!');

	class ThemeFileEventHandler extends kDBEventHandler {

		/**
		 * Allows to override standart permission mapping
		 *
		 */
		function mapPermissions()
		{
			parent::mapPermissions();

			$permissions = Array (
				'OnLoadBlock' => Array ('subitem' => true),
				'OnSaveBlock' => Array ('subitem' => true),
				'OnSaveLayout' => Array ('subitem' => true),
			);

			$this->permMapping = array_merge($this->permMapping, $permissions);
		}

		/**
		 * Changes permission section to one from REQUEST, not from config
		 *
		 * @param kEvent $event
		 */
		function CheckPermission(&$event)
		{
			if ($event->Name == 'OnLoadBlock' || $event->Name == 'OnSaveBlock') {
				return $this->Application->isAdminUser;
			}

			return parent::CheckPermission($event);
		}

		/**
		 * Loads template contents into virtual field
		 *
		 * @param kEvent $event
		 */
		function OnAfterItemLoad(&$event)
		{
			parent::OnAfterItemLoad($event);

			$object =& $event->getObject();
			/* @var $object kDBItem */

			$filename = $this->_getTemplatePath($object);

			if (file_exists($filename)) {
				$object->SetDBField('FileContents', file_get_contents($filename));
			}
			else {
				$object->SetError('FileContents', 'template_file_missing', 'la_error_TemplateFileMissing');
			}
		}

		/**
		 * Trim contents of edited template
		 *
		 * @param kEvent $event
		 */
		function OnBeforeItemUpdate(&$event)
		{
			parent::OnBeforeItemUpdate($event);

			$object =& $event->getObject();
			/* @var $object kDBItem */

			$file_data = $object->GetDBField('FileContents');

			$file_data = str_replace("\r\n", "\n", $file_data);
			$file_data = str_replace("\r", "\n", $file_data);

			$object->SetDBField('FileContents', trim($file_data));
		}

		/**
		 * Saves updated content to template
		 *
		 * @param kEvent $event
		 */
		function OnAfterItemUpdate(&$event)
		{
			parent::OnAfterItemUpdate($event);

			$object =& $event->getObject();
			/* @var $object kDBItem */

			$filename = $this->_getTemplatePath($object);

			if (file_exists($filename) && is_writable($filename)) {
				$fp = fopen($filename, 'w');
				fwrite($fp, $object->GetDBField('FileContents'));
				fclose($fp);

				$themes_helper =& $this->Application->recallObject('ThemesHelper');
				/* @var $themes_helper kThemesHelper */

				$meta_info = $themes_helper->parseTemplateMetaInfo($filename);
				$file_description = array_key_exists('desc', $meta_info) ? $meta_info['desc'] : '';

				$object->SetDBField('Description', $file_description);
				$object->SetDBField('FileMetaInfo', serialize($meta_info));
				$object->Update();
			}
		}

		/**
		 * Returns full path to template file
		 *
		 * @param kDBItem $object
		 * @return string
		 */
		function _getTemplatePath(&$object)
		{
			$theme =& $this->Application->recallObject('theme');
			/* @var $theme kDBItem */

			$path = FULL_PATH . '/themes/' . $theme->GetDBField('Name');

			$path .= $object->GetDBField('FilePath') . '/' . $object->GetDBField('FileName');

			return $path;
		}

		/**
		 * Loads block data based on it's name in request
		 *
		 * @param kEvent $event
		 */
		function OnLoadBlock(&$event)
		{
			parent::OnNew($event);

			$object =& $event->getObject();
			/* @var $object kDBItem */

			$template_helper =& $this->Application->recallObject('TemplateHelper');
			/* @var $template_helper TemplateHelper */

			$template_helper->InitHelper($object);

			$object->SetDBField('FileName', $template_helper->blockInfo('template_file'));
			$object->SetDBField('BlockPosition', $template_helper->blockInfo('start_pos') . ' - ' . $template_helper->blockInfo('end_pos'));
			$object->SetDBField('FileContents', $template_helper->blockInfo('content'));

		}

		/**
		 * Saves changed template block
		 *
		 * @param kEvent $event
		 */
		function OnSaveBlock(&$event)
		{
			$object =& $event->getObject( Array('skip_autoload' => true) );
			/* @var $object kDBItem */

			$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
			if ($items_info) {
				list ($id, $field_values) = each($items_info);
				$object->SetFieldsFromHash($field_values);
				$object->setID($id);
			}

			$status = $object->Validate();

			$template_helper =& $this->Application->recallObject('TemplateHelper');
			/* @var $template_helper TemplateHelper */

			$template_helper->InitHelper($object);

			$status = $status && $template_helper->saveBlock($object);

			if ($status) {
				$event->SetRedirectParam('opener', 'u');
			}
			else {
				$event->status = erFAIL;
			}
		}

		/**
		 * Saves layout on given template
		 *
		 * @param kEvent $event
		 */
		function OnSaveLayout(&$event)
		{
			$event->status = erSTOP;
			if (($this->Application->GetVar('ajax') != 'yes') || (EDITING_MODE != EDITING_MODE_DESIGN)) {
				return ;
			}

			$target_order = $this->Application->GetVar('target_order');

			$template_helper =& $this->Application->recallObject('TemplateHelper');
			/* @var $template_helper TemplateHelper */

			if ($template_helper->moveTemplateElements($target_order)) {
				echo 'OK';
				return ;
			}

			echo 'FAILED';
		}
	}