<?php
/**
* @version	$Id: topics_event_handler.php 16515 2017-01-20 14:12:04Z alex $
* @package	In-Bulletin
* @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 TopicsEventHandler extends kCatDBEventHandler {

		/**
		 * Checks topic lock permission
		 *
		 * @param kEvent $event
		 * @return bool
		 * @access public
		 */
		public function CheckPermission(kEvent $event)
		{
			if ( $event->Name == 'OnTopicLockToggle' ) {
				/** @var kCatDBItem $object */
				$object = $event->getObject();

				if ( !$object->isLoaded() ) {
					$event->status = kEvent::erPERM_FAIL;
					return false;
				}

				$category_id = $object->GetDBField('CategoryId');
				$perm_status = $this->Application->CheckPermission('TOPIC.LOCK', 0, $category_id);

				if ( !$perm_status ) {
					$event->status = kEvent::erPERM_FAIL;
				}

				return $perm_status;
			}

			if ( $event->Name == 'OnToogleCategoryTopicsSubscribe' || $event->Name == 'OnToogleTopicPostsSubscribe' ) {
				return $this->Application->LoggedIn();
			}

			return parent::CheckPermission($event);
		}

		/**
		 * Lock or unlock topic
		 *
		 * @param kEvent $event
		 */
		function OnToggleLock($event)
		{
			/** @var kDBItem $object */
			$object = $event->getObject();

			$new_type = $object->GetDBField('TopicType') ? 0 : 1;
			$object->SetDBField('TopicType', $new_type);
			$object->Update();
		}

		/**
		 * Cache topic owner
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 */
		protected function OnBeforeItemUpdate(kEvent $event)
		{
			parent::OnBeforeItemUpdate($event);

			$this->cacheItemOwner($event, 'OwnerId', 'PostedBy');
		}

		/**
		 * Cache topic owner
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 */
		protected function OnBeforeItemCreate(kEvent $event)
		{
			parent::OnBeforeItemCreate($event);

			$this->cacheItemOwner($event, 'OwnerId', 'PostedBy');

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

			if ( !$object->GetDBField('TodayDate') ) {
				$object->SetDBField('TodayDate', adodb_date('Y-m-d'));
			}

			/** @var PostHelper $post_helper */
			$post_helper = $this->Application->recallObject('PostHelper');

			$object->SetDBField('TopicText', $post_helper->CensorText($object->GetDBField('TopicText')));
		}

		/**
		 * Creates 1st post when topic is created
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 */
		protected function OnAfterItemCreate(kEvent $event)
		{
			parent::OnAfterItemCreate($event);

			if ( $event->Special == '-item' ) {
				// don't create first post when cloning
				return ;
			}

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

			/** @var kDBItem $post */
			$post = $this->Application->recallObject($event->Prefix . '-post', null, Array ('skip_autoload' => true));

			$post->SetDBField('Pending', $object->GetDBField('Status') == STATUS_ACTIVE ? 0 : 1);
			$post->SetDBField('Subject', '');
			$post->SetDBField('PostingText', $object->GetDBField('PostingText'));

			$post->SetDBField('ShowSignatures', $object->GetDBField('ShowSignatures'));
			$post->SetDBField('DisableSmileys', $object->GetDBField('DisableSmileys'));
			$post->SetDBField('DisableBBCodes', $object->GetDBField('DisableBBCodes'));

			$post->Create();

			// need to update category topic count here
		}

		/**
		 * Approves 1st post when topic got approved
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 */
		protected function OnAfterItemUpdate(kEvent $event)
		{
			parent::OnAfterItemUpdate($event);

			if ( !$this->Application->isAdminUser ) {
				return;
			}

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

			if ( $object->GetDBField('Posts') == 1 ) {
				/** @var kDBItem $post */
				$post = $this->Application->recallObject($event->Prefix . '-post', null, Array ('skip_autoload' => true));

				$main_status = $object->GetDBField('Status');
				$post->Load($object->GetDBField('LastPostId'));
				if ( $post->isLoaded() ) {
					$post->SetDBField('Pending', $main_status == STATUS_ACTIVE ? 0 : 1);
					$post->Update();
				}
			}
		}

		/**
		 * Makes first post body field non-required when topic has posts already
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 */
		protected function OnAfterItemLoad(kEvent $event)
		{
			parent::OnAfterItemLoad($event);

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

			if ( $object->GetDBField('Posts') > 0 || !$this->Application->isAdminUser ) {
				$object->setRequired('PostingText', false);
			}
		}

		/**
		 * Locks or unlocks topic
		 *
		 * @param kEvent $event
		 */
		function OnTopicLockToggle($event)
		{
			/** @var kCatDBItem $object */
			$object = $event->getObject();

			$topic_type = $object->GetDBField('TopicType');
			$object->SetDBField('TopicType', $topic_type == 1 ? 0 : 1);
			$object->Update();
		}

		/**
		 * Sets default values to posting options based on persistent session
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 */
		protected function OnAfterConfigRead(kEvent $event)
		{
			parent::OnAfterConfigRead($event);

			if ( !$this->Application->LoggedIn() ) {
				return;
			}

			$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
			$fields['NotifyOwnerOnChanges']['default'] = (int)$this->Application->RecallPersistentVar('owner_notify');
			$this->Application->setUnitOption($event->Prefix, 'Fields', $fields);

			$virtual_fields = $this->Application->getUnitOption($event->Prefix, 'VirtualFields');
			$virtual_fields['DisableBBCodes']['default'] = (int)!$this->Application->RecallPersistentVar('bbcode');
			$virtual_fields['DisableSmileys']['default'] = (int)!$this->Application->RecallPersistentVar('smileys');
			$virtual_fields['ShowSignatures']['default'] = (int)$this->Application->RecallPersistentVar('show_sig');
			$this->Application->setUnitOption($event->Prefix, 'VirtualFields', $virtual_fields);
		}

		/**
		 * [HOOK] Allows to add cloned subitem to given prefix
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 */
		protected function OnCloneSubItem(kEvent $event)
		{
			parent::OnCloneSubItem($event);

			if ( $event->MasterEvent->Prefix == 'rev' ) {
				$clones = $this->Application->getUnitOption($event->MasterEvent->Prefix, 'Clones');
				$subitem_prefix = $event->Prefix . '-' . $event->MasterEvent->Prefix;

				$clones[$subitem_prefix]['ConfigMapping'] = Array (
					'PerPage'				=>	'Perpage_TopicReviews',

					'ReviewDelayInterval'	=>	'topic_ReviewDelay_Interval',
					'ReviewDelayValue'		=>	'topic_ReviewDelay_Value',
				);

				$this->Application->setUnitOption($event->MasterEvent->Prefix, 'Clones', $clones);
			}
		}

		/**
		 * Subscribes/unsubscribes to new topics in given current category
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 */
		protected function OnToogleCategoryTopicsSubscribe(kEvent $event)
		{
			/** @var PostHelper $post_helper */
			$post_helper = $this->Application->recallObject('PostHelper');

			$manager = $post_helper->getSubscriptionManager('CategoryTopics');

			if ( $manager->subscribed() ) {
				$manager->unsubscribe();
			}
			else {
				$manager->subscribe();
			}
		}

		/**
		 * Subscribes/unsubscribes to new posts in current topic
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 */
		protected function OnToogleTopicPostsSubscribe(kEvent $event)
		{
			/** @var kDBItem $object */
			$object = $event->getObject();

			/** @var PostHelper $post_helper */
			$post_helper = $this->Application->recallObject('PostHelper');

			$manager = $post_helper->getSubscriptionManager('TopicPosts', Array ($object->GetID()));

			if ( $manager->subscribed() ) {
				$manager->unsubscribe();
			}
			else {
				$manager->subscribe();
			}
		}

		/**
		 * Adds fields for forum preferences.
		 *
		 * @param kEvent $event Event.
		 *
		 * @return void
		 */
		protected function OnModifyUserProfileConfig(kEvent $event)
		{
			$checkbox_field = array(
				'type' => 'int',
				'formatter' => 'kOptionsFormatter', 'options' => array(1 => 'la_Yes', 0 => 'la_No'), 'use_phrases' => 1,
				'default' => 0,
			);
			$text_field = array('type' => 'string', 'default' => '');

			$new_virtual_fields = array(
				'show_sig' => $checkbox_field,
				'Perpage_Topics' => $text_field,
				'Perpage_Postings' => $text_field,
				'owner_notify' => $checkbox_field,
				'bb_pm_notify' => $checkbox_field,
				'bbcode' => $checkbox_field,
				'smileys' => $checkbox_field,
				'bb_signatures' => $checkbox_field,
				'my_signature' => $text_field,
			);

			$virtual_fields = $this->Application->getUnitOption(
				$event->MasterEvent->Prefix,
				'VirtualFields',
				array()
			);
			$this->Application->setUnitOption(
				$event->MasterEvent->Prefix,
				'VirtualFields',
				array_merge($virtual_fields, $new_virtual_fields)
			);
		}

	}
