<?php
/**
* @version	$Id: file_eh.php 16513 2017-01-20 14:10:53Z 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 FileEventHandler extends kDBEventHandler {

		/**
		 * Allows to override standard permission mapping
		 *
		 * @return void
		 * @access protected
		 * @see kEventHandler::$permMapping
		 */
		protected function mapPermissions()
		{
			parent::mapPermissions();

			$permissions = Array (
				'OnDownloadFile' => Array ('subitem' => 'view'),
			);

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

		/**
		 * Remembers user, who is created file record. Makes file primary if no other files are uploaded.
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 */
		protected function OnBeforeItemCreate(kEvent $event)
		{
			parent::OnBeforeItemCreate($event);

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

			$object->SetDBField('CreatedById', $this->Application->RecallVar('user_id'));
		}

		/**
		 * Resets primary file mark when more then one file is marked as primary
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 */
		protected function OnBeforeItemUpdate(kEvent $event)
		{
			parent::OnBeforeItemUpdate($event);

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

			if ( !$object->GetDBField('FileName') ) {
				$object->SetDBField('FileName', basename($object->GetDBField('FilePath')));
			}
		}

		/**
		 * Apply any custom changes to list's sql query
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 * @see kDBEventHandler::OnListBuild()
		 */
		protected function SetCustomQuery(kEvent $event)
		{
			parent::SetCustomQuery($event);

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

			if ( !$this->Application->isAdminUser ) {
				$object->addFilter('active_filter', '%1$s.Status = ' . STATUS_ACTIVE);
			}
		}

		/**
		 * Returns file contents associated with item
		 *
		 * @param kEvent $event
		 */
		function OnDownloadFile($event)
		{
			/** @var kDBItem $object */
			$object = $event->getObject();

			/** @var FileHelper $file_helper */
			$file_helper = $this->Application->recallObject('FileHelper');

			$filename = $object->GetField('FilePath', 'full_path');
			$file_helper->DownloadFile($filename);

			$event->status = kEvent::erSTOP;
		}
	}