<?php
/**
* @version	$Id: file_eh.php 14241 2011-03-16 20:24:35Z 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 standart permission mapping
		 *
		 */
		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
		 */
		function OnBeforeItemCreate(&$event)
		{
			$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
		 */
		function OnBeforeItemUpdate(&$event)
		{
			$object =& $event->getObject();

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

		function SetCustomQuery(&$event)
		{
			parent::SetCustomQuery($event);

			$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)
		{
			$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 = erSTOP;
		}
	}