<?php
/**
* @version	$Id: forms_eh.php 12960 2009-12-20 13:11: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 FormsEventHandler extends kDBEventHandler {

	/**
	 * Allows to override standart permission mapping
	 *
	 */
	function mapPermissions()
	{
		parent::mapPermissions();
		$permissions = Array(
			// user can view any form on front-end
			'OnItemBuild'	=>	Array('self' => true),
		);

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

	function OnCreateSubmissionNodes(&$event)
	{
		if (defined('IS_INSTALL') && IS_INSTALL) {
			// skip any processing, because Forms table doesn't exists until install is finished
			return ;
		}
		$sections = $this->Application->getUnitOption($event->Prefix, 'Sections');

		$forms = $this->Conn->GetCol('SELECT Title, FormId FROM '.TABLE_PREFIX.'Forms ORDER BY Title ASC', 'FormId');
		if (!$forms || count($forms) == 0) {
			return;
		}

		$form_subsection = Array(
			'parent'		=>	'in-portal:forms',
			'icon'			=>	'form_submission',
			'label'			=>	'',
			'url'			=>	Array('t' => 'submissions/submissions_list', 'pass' => 'm,form'),
			'permissions'	=>	Array('view', 'add', 'edit', 'delete'),
			'priority'		=>	1,
			'type'			=>	stTREE,
		);

		$priority = 1;
		foreach ($forms as $form_id => $form_name) {
			$this->Application->Phrases->AddCachedPhrase('form_sub_label_'.$form_id, $form_name);
			$this->Application->Phrases->AddCachedPhrase('la_description_in-portal:submissions:'.$form_id, $form_name.' Submissions');
			$form_subsection['label'] = 'form_sub_label_'.$form_id;
			$form_subsection['url']['form_id'] = $form_id;
			$form_subsection['priority'] = $priority++;
			$sections['in-portal:submissions:'.$form_id] = $form_subsection;
		}

		$this->Application->setUnitOption($event->Prefix, 'Sections', $sections);
	}

	function OnSave(&$event)
	{
		parent::OnSave($event);
		if ($event->status == erSUCCESS) {

			$this->OnCreateFormFields($event);

			$this->Conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName = "sections_parsed"');
			$this->Application->StoreVar('RefreshStructureTree', 1);
		}
	}

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

		if ($event->status == erSUCCESS) {
			$this->Conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName = "sections_parsed"');
			$this->Application->StoreVar('RefreshStructureTree', 1);
		}
	}

	/**
		 * Dynamically fills customdata config
		 *
		 * @param kEvent $event
		 */
		function OnCreateFormFields(&$event)
		{
			$cur_fields = $this->Conn->Query('DESCRIBE '.TABLE_PREFIX.'FormSubmissions', 'Field');
			$cur_fields = array_keys($cur_fields);

			// keep all fields, that are not created on the fly (includes ones, that are added during customizations)
			foreach ($cur_fields as $field_index => $field_name) {
				if (!preg_match('/^fld_[\d]+/', $field_name)) {
					unset($cur_fields[$field_index]);
				}
			}

			$desired_fields = $this->Conn->GetCol('SELECT CONCAT(\'fld_\', FormFieldId) FROM '.TABLE_PREFIX.'FormFields ORDER BY FormFieldId');

			$sql = array();

			$fields_to_add = array_diff($desired_fields, $cur_fields);
			foreach ($fields_to_add as $field) {
				$field_expression = $field.' Text NULL';
				$sql[] = 'ADD COLUMN '.$field_expression;
			}

			$fields_to_drop = array_diff($cur_fields, $desired_fields);
			foreach ($fields_to_drop as $field) {
				$sql[] = 'DROP COLUMN '.$field;
			}

			if ($sql) {
				$query = 'ALTER TABLE '.TABLE_PREFIX.'FormSubmissions '.implode(', ', $sql);
				$this->Conn->Query($query);
			}
		}

	/*function GetPassedId($event)
	{
		return 0;
	}

	function LoadItem(&$event)
	{
		$object =& $event->getObject();
		$object->SetField('Id',0);
		$object->SetId(0);
	}
*/
	/**
	 * Enter description here...
	 *
	 * @param kEvent $event
	 */
	function OnFormSubmit(&$event)
	{
		$object =& $event->GetObject();

		$fields = explode(',',$this->Application->GetVar('fields'));
		$required_fields = explode(',', $this->Application->GetVar('required_fields'));
		$fields_params = $this->Application->GetVar('fields_params');

		foreach ($fields as $field) {
			$virt_fields[$field] = Array();
			if (in_array($field, $required_fields)) {
				$virt_fields[$field]['required'] = 1;
			}
			$params = getArrayValue($fields_params, $field);
			if ($params !== false) {
				if (getArrayValue($params, 'Type') == 'email') {
					//'formatter'=>'kFormatter', 'regexp'=>'/^(' . REGEX_EMAIL_USER . '@' . REGEX_EMAIL_DOMAIN . ')$/i', 'error_msgs' => Array('invalid_format'=>'!la_invalid_email!')
					$virt_fields[$field]['formatter']	= 'kFormatter';
					$virt_fields[$field]['regexp']	= '/^(' . REGEX_EMAIL_USER . '@' . REGEX_EMAIL_DOMAIN . ')$/i';
					$virt_fields[$field]['error_msgs']	= Array('invalid_format'=>'!la_invalid_email!');
				}
				if (getArrayValue($params, 'Type') == 'file') {
					$virt_fields[$field]['formatter']	= 'kUploadFormatter';
					$virt_fields[$field]['upload_dir']	= '/uploads/sketches/';
				}
			}
		}
		$object->SetVirtualFields($virt_fields);

		$field_values = $this->getSubmittedFields($event);


		$checkboxes = Array('MailingList', 'In-Link', 'In-Newz', 'In-Bulletin');
		$checkboxes = explode(',', $this->Application->GetVar('checkbox_fields'));
		foreach ($checkboxes as $checkbox) {
			if (isset($field_values[$checkbox])) {
				$field_values[$checkbox] = 1;
			}
			else {
				$field_values[$checkbox] = '0';
			}
		}

		$object->SetFieldsFromHash($field_values);
		if ($object->Validate()) {
			$event->redirect = $this->Application->GetVar('success_template');
			$this->Application->EmailEventAdmin($this->Application->GetVar('email_event'));
			$this->Application->EmailEventUser($this->Application->GetVar('email_event'), null,
					Array('to_email' => $field_values[$this->Application->GetVar('email_field')],
								'to_name' => $field_values[$this->Application->GetVar('name_field')]));

			if ($field_values['MailingList']) {
				$this->Application->StoreVar('SubscriberEmail', $field_values['Email']);
				$this->Application->HandleEvent($sub_event, 'u:OnSubscribeUser', Array('no_unsubscribe' => 1));
			}
		}
		else {
			$event->status = erFAIL;
		}
	}
}