<?php
/**
* @version	$Id: themes_eh.php 15145 2012-03-04 09:04:08Z 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 standard permission mapping
		 *
		 * @return void
		 * @access protected
		 * @see kEventHandler::$permMapping
		 */
		protected function mapPermissions()
		{
			parent::mapPermissions();

			$permissions = Array(
				'OnChangeTheme' => Array('self' => true),
			);

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

		/**
		 * Checks user permission to execute given $event
		 *
		 * @param kEvent $event
		 * @return bool
		 * @access public
		 */
		public function CheckPermission(kEvent $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 = kEvent::erFAIL;
				return;
			}

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

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

			$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
		 * @return void
		 * @access protected
		 */
		protected function OnAfterCopyToLive(kEvent $event)
		{
			parent::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
		 * @return void
		 * @access protected
		 */
		protected function OnSave(kEvent $event)
		{
			parent::OnSave($event);

			if ( ($event->status != kEvent::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 ) {
				$this->Application->HandleEvent(new kEvent('adm:OnRebuildThemes'));
			}
		}

		/**
		 * 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);

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

		/**
		 * Apply system filter to themes list
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 * @see kDBEventHandler::OnListBuild()
		 */
		protected function SetCustomQuery(kEvent $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) . ')');
			}
		}
	}
