<?php
/**
* @version	$Id: themes_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 ThemesEventHandler extends kDBEventHandler {

		/**
		 * Allows to override standart permission mapping
		 *
		 */
		function mapPermissions()
		{
			parent::mapPermissions();
			$permissions = Array(
				'OnChangeTheme' => Array('self' => true),
			);

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

		/**
		 * Permission check override
		 *
		 * @param kEvent $event
		 */
		function CheckPermission(&$event)
		{
			if ($event->Name == 'OnItemBuild') {
				// check permission without using $event->getSection(),
				// so first cache rebuild won't lead to "ldefault_Name" field being used
				return true;
			}

			return parent::CheckPermission($event);
		}

		/**
		 * Allows to set selected theme as primary
		 *
		 * @param kEvent $event
		 */
		function OnSetPrimary(&$event)
		{
			if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
				$event->status = erFAIL;
				return;
			}

			$ids = $this->StoreSelectedIDs($event);
			if ($ids) {
				$id = array_shift($ids);
				$this->setPrimary($id);

				$rebuild_event = new kEvent('adm:OnRebuildThemes');
				$this->Application->HandleEvent($rebuild_event);
			}

			$this->clearSelectedIDs($event);
		}

		function setPrimary($id)
		{
			$id_field = $this->Application->getUnitOption($this->Prefix, 'IDField');
			$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');

			$sql = 'UPDATE '.$table_name.'
					SET PrimaryTheme = 0';
			$this->Conn->Query($sql);


			$sql = 'UPDATE '.$table_name.'
					SET PrimaryTheme = 1, Enabled = 1
					WHERE '.$id_field.' = '.$id;
			$this->Conn->Query($sql);
		}

		/**
		 * Set's primary theme (when checkbox used on editing form)
		 *
		 * @param kEvent $event
		 */
		function OnAfterCopyToLive(&$event)
		{
			$object =& $this->Application->recallObject($event->Prefix.'.-item', null, Array('skip_autoload' => true, 'live_table' => true));
			/* @var $object kDBItem */

			$object->Load($event->getEventParam('id'));

			if ($object->GetDBField('PrimaryTheme')) {
				$this->setPrimary($event->getEventParam('id'));
			}
		}

		/**
		 * Also rebuilds theme files, when enabled theme is saved
		 *
		 * @param kEvent $event
		 */
		function OnSave(&$event)
		{
			parent::OnSave($event);

			if (($event->status != erSUCCESS) || !$event->getEventParam('ids')) {
				return ;
			}

			$ids = $event->getEventParam('ids');

			$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
			$table_name = $this->Application->getUnitOption($event->Prefix, 'TableName');

			$sql = 'SELECT COUNT(*)
					FROM ' . $table_name . '
					WHERE ' . $id_field . ' IN (' . $ids . ') AND (Enabled = 1)';
			$enabled_themes = $this->Conn->GetOne($sql);

			if ($enabled_themes) {
				$rebuild_event = new kEvent('adm:OnRebuildThemes');
				$this->Application->HandleEvent($rebuild_event);
			}
		}

		/**
		 * Allows to change the theme
		 *
		 * @param kEvent $event
		 */
		function OnChangeTheme(&$event)
		{
			if ($this->Application->isAdminUser) {
				// for structure theme dropdown
				$this->Application->StoreVar('theme_id', $this->Application->GetVar('theme'));
				$this->Application->StoreVar('RefreshStructureTree', 1);
				return ;
			}

			$this->Application->SetVar('t', 'index');
			$this->Application->SetVar('m_cat_id', 0);

			if (MOD_REWRITE) {
				$mod_rewrite_helper =& $this->Application->recallObject('ModRewriteHelper');
				/* @var $mod_rewrite_helper kModRewriteHelper */

				$mod_rewrite_helper->removePages();
			}

			$this->Application->SetVar('m_theme', $this->Application->GetVar('theme'));
		}

		/**
		 * Apply system filter to themes list
		 *
		 * @param kEvent $event
		 */
		function SetCustomQuery(&$event)
		{
			parent::SetCustomQuery($event);

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

			if (in_array($event->Special, Array ('enabled', 'selected', 'available')) || !$this->Application->isAdminUser) {
				// "enabled" special or Front-End
				$object->addFilter('enabled_filter', '%1$s.Enabled = ' . STATUS_ACTIVE);
			}

			// site domain theme picker
			if ($event->Special == 'selected' || $event->Special == 'available') {
				$edit_picker_helper =& $this->Application->recallObject('EditPickerHelper');
				/* @var $edit_picker_helper EditPickerHelper */

				$edit_picker_helper->applyFilter($event, 'Themes');
			}

			// apply domain-based theme filtering
			$themes = $this->Application->siteDomainField('Themes');

			if (strlen($themes)) {
				$themes = explode('|', substr($themes, 1, -1));
				$object->addFilter('domain_filter', '%1$s.ThemeId IN (' . implode(',', $themes) . ')');
			}
		}
	}
