<?php
/**
* @version	$Id: file_eh.php 15065 2012-01-17 15:11:29Z 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);

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

			$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);

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

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

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

			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)
		{
			$object =& $event->getObject();
			/* @var $object kDBItem */

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

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

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