<?php
/**
* @version	$Id: form_submissions_eh.php 13251 2010-03-17 10:26:06Z 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 FormSubmissionsEventHandler extends kDBEventHandler {

		function CheckPermission(&$event)
		{
			if (!$this->Application->isAdmin) {
				if ($event->Name == 'OnCreate') {
					// anybody can submit forms on front
					return true;
				}
			}
			
			$section = $event->getSection();
			$form_id = $this->Application->GetVar('form_id');

			$event->setEventParam('PermSection', $section . ':' . $form_id);
			
			return parent::CheckPermission($event);
		}

		function mapPermissions()
		{
			parent::mapPermissions();
			$permissions = Array(
				'OnEdit'				=>	Array('self' => 'view', 'subitem' => 'view'),
			);
			$this->permMapping = array_merge($this->permMapping, $permissions);
		}

		/**
		 * Returns filter block based on field element type
		 *
		 * @param string $element_type
		 * @return string
		 */
		function _getFilterBlock($element_type)
		{
			$mapping = Array (
				'text' => 'grid_like_filter',
				'select' => 'grid_options_filter',
				'radio' => 'grid_options_filter',
				'checkbox' => 'grid_options_filter',
				'password' => 'grid_like_filter',
				'textarea' => 'grid_like_filter',
				'label' => 'grid_like_filter',
			);

			return $mapping[$element_type];
		}

		function OnBuildFormFields(&$event)
		{
			$form_id = $this->Application->GetVar('form_id');
			if (!$form_id) return ;

			$conf_fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
			$conf_grids = $this->Application->getUnitOption($event->Prefix, 'Grids');

			$helper =& $this->Application->recallObject('InpCustomFieldsHelper');

			$sql = 'SELECT *
					FROM ' . TABLE_PREFIX . 'FormFields
					WHERE FormId = ' . (int)$form_id . '
					ORDER BY Priority DESC';
			$fields = $this->Conn->Query($sql, 'FormFieldId');

			foreach ($fields as $field_id => $options) {
				$conf_fields['fld_'.$field_id] = Array('type'=>'string', 'default'=>$options['DefaultValue']);
				if ($options['Required']) {
					$conf_fields['fld_'.$field_id]['required'] = 1;
				}
				if ($options['Validation'] == 1) {
					$conf_fields['fld_'.$field_id]['formatter'] = 'kFormatter';
					$conf_fields['fld_'.$field_id]['regexp'] = '/^(' . REGEX_EMAIL_USER . '@' . REGEX_EMAIL_DOMAIN . ')$/i';
				}
				if ($options['DisplayInGrid']) {
					$title = $options['Prompt'];
					if (substr($title, 0,1) == '+') {
						$this->Application->Phrases->AddCachedPhrase('form_col_title'.$field_id, substr($title,1));
						$title = 'form_col_title'.$field_id;
					}
					$conf_grids['Default']['Fields']['fld_'.$field_id] = Array('title'=>$title, 'no_special' => 1, 'nl2br' => 1, 'first_chars' => 200, 'filter_block' => $this->_getFilterBlock($options['ElementType']));
					if ($options['Validation'] == 1)
					{
						$conf_grids['Default']['Fields']['fld_'.$field_id]['data_block'] = 'grid_email_td';
					}
				}
				if ($options['ElementType'] == 'radio' || $options['ElementType'] == 'select') {
					$conf_fields['fld_'.$field_id]['options'] = $helper->GetValuesHash( $options['ValueList'] );
					$conf_fields['fld_'.$field_id]['formatter'] = 'kOptionsFormatter';
				}
				if ($options['ElementType'] == 'password') {
					$conf_fields['fld_'.$field_id]['formatter'] = 'kPasswordFormatter';
					$conf_fields['fld_'.$field_id]['encryption_method'] = 'plain';
					$conf_fields['fld_'.$field_id]['verify_field'] = 'fld_'.$field_id.'_verify';
				}
			}

			$this->Application->setUnitOption($event->Prefix, 'Fields', $conf_fields);
			$this->Application->setUnitOption($event->Prefix, 'Grids', $conf_grids);
		}

		function SetCustomQuery(&$event)
		{
			$object =& $event->getObject();
			$form_id = $this->Application->GetVar('form_id');
			$object->addFilter('form_filter','%1$s.FormId = '.$form_id);
		}

		function getPassedID(&$event)
		{
			if (!$this->Application->isAdminUser) {
				// no way to see other user's form submission by giving it's ID directly in url
				return 0;
			}

			return parent::getPassedID($event);
		}

		/**
		 * Creates new form submission from Front-End
		 *
		 * @param kEvent $event
		 */
		function OnCreate(&$event)
		{
			parent::OnCreate($event);

			if ($event->status != erSUCCESS) {
				return ;
			}

			$this->Application->EmailEventAdmin('FORM.SUBMITTED');
//			$this->Application->EmailEventUser('FORM.SUBMITTED', null, 'to_email' => '');

			$event->SetRedirectParam('opener', 's');
			$event->SetRedirectParam('m_cat_id', 0);

			$theme =& $this->Application->recallObject('theme.current');
			/* @var $theme kDBItem */

			$template = $this->Application->GetVar('success_template');
			$alias_template = $theme->GetField('TemplateAliases', $template);

			$event->redirect = $alias_template ? $alias_template : $template;
		}
	}