<?php
/**
* @version	$Id: phrases_event_handler.php 12734 2009-10-20 19:28:11Z 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 PhrasesEventHandler extends kDBEventHandler
	{
		/**
		 * Apply some special processing to
		 * object beeing recalled before using
		 * it in other events that call prepareObject
		 *
		 * @param Object $object
		 * @param kEvent $event
		 * @access protected
		 */
		function prepareObject(&$object, &$event)
		{
			// don't call parent

			if ($event->Special == 'import') {
				$object->setRequired('LangFile', true);
				$object->setRequired('Phrase', false);
				$object->setRequired('Translation', false);

				// allow multiple phrase types to be selected during import
				$field_options = $object->GetFieldOptions('PhraseType');
				$field_options['type'] = 'string';
				$object->SetFieldOptions('PhraseType', $field_options);
			}
		}

		/**
		 * Allow to create phrases from front end in debug mode with DBG_PHRASES constant set
		 *
		 * @param kEvent $event
		 */
		function CheckPermission(&$event)
		{
			if (!$this->Application->isAdmin && $this->Application->isDebugMode() && constOn('DBG_PHRASES')) {
				$allow_events = Array ('OnCreate', 'OnUpdate');

				if (in_array($event->Name, $allow_events)) {
					return true;
				}
			}

			return parent::CheckPermission($event);
		}

		function mapPermissions()
		{
			parent::mapPermissions();

			$permissions = Array (
				'OnItemBuild' => Array('self' => true, 'subitem' => true),
				'OnNew' => Array('self' => true, 'subitem' => true),
				'OnPrepareUpdate' => Array('self' => true, 'subitem' => true),
			);

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

		/**
		 * Forces new label in case if issued from get link
		 *
		 * @param kEvent $event
		 */
		function OnNew(&$event)
		{
			parent::OnNew($event);
			$label = $this->Application->GetVar('phrases_label');

			$object =& $event->getObject( $label ? Array('live_table' => true, 'skip_autoload' => true) : Array('skip_autoload' => true) );
			if ($label) {
				$object->SetDBField('Phrase', $label);
				// phrase is created in language, used to display phrases
				$object->SetDBField('LanguageId', $this->Application->GetVar('m_lang'));
				$object->SetDBField('PhraseType', 1);

				$primary_language = $this->Application->GetDefaultLanguageId();
				$live_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
				$sql = 'SELECT Translation FROM %s WHERE Phrase = %s';
				$primary_value = $this->Conn->GetOne( sprintf($sql, $live_table, $this->Conn->qstr($label) ) );
				$object->SetDBField('PrimaryTranslation', $primary_value);
			}

			$last_module = $this->Application->GetVar('last_module');
			if ($last_module) {
				$object->SetDBField('Module', $last_module);
			}

			if ($event->Special == 'export' || $event->Special == 'import') {
				$object->SetDBField('PhraseType', '|0|1|2|');
				$modules = $this->Conn->GetCol('SELECT Name FROM '.TABLE_PREFIX.'Modules');
				$object->SetDBField('Module', '|'.implode('|', $modules).'|' );
			}
		}

		/**
		 * Prepares existing phrase editing
		 *
		 * @param kEvent $event
		 */
		function OnPrepareUpdate(&$event)
		{
			$language_id = $this->Application->GetVar('m_lang');
			$label = $this->Application->GetVar('phrases_label');

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

			$sql = 'SELECT ' . $label_idfield . '
					FROM ' . $table_name . '
					WHERE Phrase = '.$this->Conn->qstr($label).' AND LanguageId = '.(int)$language_id;
			$this->Application->SetVar($event->getPrefixSpecial() . '_id', $this->Conn->GetOne($sql));

			$event->redirect = false;
		}

		/**
		 * Forces create to use live table
		 *
		 * @param kEvent $event
		 */
		function OnCreate(&$event)
		{
			if ( $this->Application->GetVar($event->Prefix . '_label') ) {
				$object =& $event->getObject( Array('skip_autoload' => true) );

				if ($this->Application->GetVar('m_lang') != $this->Application->GetVar('lang_id')) {
					$object->SwitchToLive();
				}
			}

			parent::OnCreate($event);
		}

		/**
		 * Set last change info, when phrase is created
		 *
		 * @param kEvent $event
		 */
		function OnBeforeItemCreate(&$event)
		{
			parent::OnBeforeItemCreate($event);

			$this->_setPhraseKey($event);
			$this->_setLastUpdated($event);
		}

		/**
		 * Update last change info, when phrase is updated
		 *
		 * @param kEvent $event
		 */
		function OnBeforeItemUpdate(&$event)
		{
			parent::OnBeforeItemUpdate($event);

			$this->_setPhraseKey($event);
			$this->_setLastUpdated($event);
		}

		/**
		 * Set's phrase key, used for phrase updating and loading
		 *
		 * @param kEvent $event
		 */
		function _setPhraseKey(&$event)
		{
			$object =& $event->getObject();
			/* @var $object kDBItem */

			$object->SetDBField('PhraseKey', mb_strtoupper($object->GetDBField('Phrase')));
		}

		/**
		 * Save phrase change date & ip translation was made from
		 *
		 * @param kEvent $event
		 */
		function _setLastUpdated(&$event)
		{
			$object =& $event->getObject();
			/* @var $object kDBItem */

			if ($object->GetOriginalField('Translation') != $object->GetDBField('Translation')) {
				$object->SetDBField('LastChanged_date', adodb_mktime() );
				$object->SetDBField('LastChanged_time', adodb_mktime() );
				$object->SetDBField('LastChangeIP', $_SERVER['REMOTE_ADDR']);
			}

			$this->Application->Session->SetCookie('last_module', $object->GetDBField('Module'));
		}

		/**
		 * Changes default module to custom (when available)
		 *
		 * @param kEvent $event
		 */
		function OnAfterConfigRead(&$event)
		{
			parent::OnAfterConfigRead($event);

			if ($this->Application->findModule('Name', 'Custom')) {
				$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
				$fields['Module']['default'] = 'Custom';
				$this->Application->setUnitOption($event->Prefix, 'Fields', $fields);
			}
		}

	}