<?php
//==============================================================================
// Flexible Form v151.1
// 
// Author: Clear Thinking, LLC
// E-mail: johnathan@getclearthinking.com
// Website: http://www.getclearthinking.com
//==============================================================================

class ControllerInformationForm extends Controller {
	private $error = array();
	
	public function index() {
		$v14x = (!defined('VERSION') || VERSION < 1.5);
		$v150 = (strpos(VERSION, '1.5.0') === 0);
		$v151 = (strpos(VERSION, '1.5.1') === 0);
		
		$this->language->load('information/form');
		
		$form_data = ($v151) ? $this->config->get('form_data') : unserialize($this->config->get('form_data'));
		
		if (isset($this->request->get['form']) && isset($form_data[$this->request->get['form']])) {
			
			$form = $form_data[$this->request->get['form']];
			
			if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate($form)) {
				$mail = new Mail();
				$mail->protocol = $this->config->get('config_mail_protocol');
				$mail->parameter = $this->config->get('config_mail_parameter');
				$mail->hostname = $this->config->get('config_smtp_host');
				$mail->username = $this->config->get('config_smtp_username');
				$mail->password = $this->config->get('config_smtp_password');
				$mail->port = $this->config->get('config_smtp_port');
				$mail->timeout = $this->config->get('config_smtp_timeout');
				$mail->setFrom($this->config->get('config_email'));
				$mail->setSender($this->config->get('config_name'));
				$mail->setSubject(sprintf($this->language->get('email_subject'), $form['title']));
				
				$body = '';
				
				$fields = $form['fields'];
				
				$sort_order = array();
				foreach ($fields as $key => $value) {
					$sort_order[$key] = $value['sort_order'];
					$column[$key] = $value['column'];
				}
				array_multisort($column, SORT_ASC, $sort_order, SORT_ASC, $fields);
				
				foreach ($fields as $field) {
					$key = preg_replace('/[^\w]/', '', $field['name']);
					
					$body .= $field['name'] . $this->language->get('text_after_title') . "\n";
						
					if ($field['type'] == 'file') {
						
						$file_error = FALSE;
						if (isset($this->request->files[$key]['name']) && $this->request->files[$key]['name']) {
							if ((strlen(utf8_decode($this->request->files[$key]['name'])) < 3) || (strlen(utf8_decode($this->request->files[$key]['name'])) > 128)) {
								$file_error = TRUE;
								$body .= $this->language->get('error_file_name') . "\n";
							}
							
							if ($this->request->files[$key]['size']/1024 > $form['filesize_limit']) {
								$file_error = TRUE;
								$body .= $this->language->get('error_file_size') . "\n";
							}
							
							$allowed = array();
							$filetypes = explode(',', $form['allowed_ext']);
							foreach ($filetypes as $filetype) {
								$allowed[] = trim($filetype);
							}
							
							$ext = strtolower(substr(strrchr($this->request->files[$key]['name'], '.'), 1));
							if (!in_array($ext, $allowed)) {
								$file_error = TRUE;
								$body .= sprintf($this->language->get('error_file_ext'), $ext) . "\n";
							}
							
							if ($this->request->files[$key]['error'] != UPLOAD_ERR_OK) {
								$file_error = TRUE;
								$body .= $this->language->get('error_file_upload') . "\n";
							}
						} else {
							$file_error = TRUE;
							$body .= $this->language->get('text_no_file') . "\n";
						}
						
						if (!$file_error && is_uploaded_file($this->request->files[$key]['tmp_name']) && file_exists($this->request->files[$key]['tmp_name'])) {
							$mail->addAttachment($this->request->files[$key]['tmp_name'], $this->request->files[$key]['name']);
							$body .= $this->request->files[$key]['name'] . "\n";
						}
						
					} else {
						
						if (!isset($this->request->post[$key]) || !$this->request->post[$key]) {
							$body .= $this->language->get('text_no_answer') . "\n";
						} elseif (is_array($this->request->post[$key])) {
							foreach ($this->request->post[$key] as $value) {
								$body .= strip_tags(html_entity_decode($value, ENT_QUOTES, 'UTF-8')) . "\n";
							}
						} else {
							$body .= strip_tags(html_entity_decode($this->request->post[$key], ENT_QUOTES, 'UTF-8')) . "\n";
						}
						
					}
					
					$body .= "\n";
				}
				
				$mail->setText($body);
				
				foreach (explode(',', $form['email']) as $email) {
					$mail->setTo(trim($email));
					$mail->send();
				}
				
				$this->redirect($this->makeURL('information/form/success'));
			}
			
			if ($v14x) {
				$this->document->title = $form['title'];
				$this->document->breadcrumbs = array();
				$this->document->breadcrumbs[] = array(
					'text'		=> $this->language->get('text_home'),
					'href'		=> HTTP_SERVER . 'index.php?route=common/home',
					'separator'	=> FALSE
				);
				$this->document->breadcrumbs[] = array(
					'text'		=> $form['title'],
					'href'		=> HTTP_SERVER . 'index.php?route=information/contact',
					'separator'	=> $this->language->get('text_separator')
				);
			} else {
				$this->document->setTitle($form['title']);
				$this->data['breadcrumbs'] = array();
				$this->data['breadcrumbs'][] = array(
					'text'		=> $this->language->get('text_home'),
					'href'		=> $this->url->link('common/home'),
					'separator'	=> FALSE
				);
				$this->data['breadcrumbs'][] = array(
					'text'		=> $form['title'],
					'href'		=> $this->url->link('information/contact'),
					'separator'	=> $this->language->get('text_separator')
				);
			}
			
			$this->data['heading_title'] = $form['title'];
			
			$this->data['error_required'] = (isset($this->error['required'])) ? $this->error['required'] : '';
			$this->data['error_captcha'] = (isset($this->error['captcha'])) ? $this->error['captcha'] : '';
			
			$this->data['description'] = html_entity_decode($form['description'], ENT_QUOTES, 'UTF-8');
			$this->data['text_after_title'] = $this->language->get('text_after_title');
			$this->data['text_allowed_ext'] = sprintf($this->language->get('text_allowed_ext'), $form['allowed_ext']);
			
			$this->data['column1'] = array();
			$this->data['column2'] = array();
			
			foreach ($form['fields'] as $field) {
				$key = preg_replace('/[^\w]/', '', $field['name']);
				
				if (isset($this->request->post[$key])) {
					$this->data[$key] = $this->request->post[$key];
				} else {
					if ($field['type'] == 'checkbox' || $field['type'] == 'radio' || $field['type'] == 'select') {
						$this->data[$key] = explode(';', $field['value']);
					} else {
						$this->data[$key] = $field['value'];
					}
				}
				
				if ($field['column'] == 1) {
					$this->data['column1'][] = $field;
				} else {
					$this->data['column2'][] = $field;
				}
			}
			
			$sort_order = array();
			foreach ($this->data['column1'] as $key => $value) {
				$sort_order[$key] = $value['sort_order'];
			}
			array_multisort($sort_order, SORT_ASC, $this->data['column1']);
			
			$sort_order = array();
			foreach ($this->data['column2'] as $key => $value) {
				$sort_order[$key] = $value['sort_order'];
			}
			array_multisort($sort_order, SORT_ASC, $this->data['column2']);
			
			$this->data['include_captcha'] = $form['captcha'];
			$this->data['text_enter_code'] = $this->language->get('text_enter_code');
			
			$this->data['button_submit'] = $this->language->get('button_submit');
			
			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/information/form.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/information/form.tpl';
			} else {
				$this->template = 'default/template/information/form.tpl';
			}
			
		} else {
			
			if ($v14x) {
				$this->document->title = $this->language->get('error_not_found');
				$this->document->breadcrumbs = array();
				$this->document->breadcrumbs[] = array(
					'text'		=> $this->language->get('text_home'),
					'href'		=> HTTP_SERVER . 'index.php?route=common/home',
					'separator'	=> FALSE
				);
				$this->document->breadcrumbs[] = array(
					'text'		=> $this->language->get('error_not_found'),
					'href'		=> HTTP_SERVER . 'index.php?route=information/form',
					'separator'	=> $this->language->get('text_separator')
				);
			} else {
				$this->document->setTitle($this->language->get('error_not_found'));
				$this->data['breadcrumbs'] = array();
				$this->data['breadcrumbs'][] = array(
					'text'		=> $this->language->get('text_home'),
					'href'		=> $this->url->link('common/home'),
					'separator'	=> FALSE
				);
				$this->data['breadcrumbs'][] = array(
					'text'		=> $this->language->get('error_not_found'),
					'href'		=> $this->url->link('information/form'),
					'separator'	=> $this->language->get('text_separator')
				);
			}
			
			$this->data['heading_title'] = $this->language->get('error_not_found');
			$this->data['text_error'] = $this->language->get('error_not_found');
			$this->data['button_continue'] = $this->language->get('button_continue');
			
			$this->data['continue'] = $this->makeURL('common/home');
			
			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/error/not_found.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/error/not_found.tpl';
			} else {
				$this->template = 'default/template/error/not_found.tpl';
			}
		}
		
		if ($v14x) {
			$this->children = array(
				'common/column_right',
				'common/footer',
				'common/column_left',
				'common/header'
			);
			$this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
		} else {
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);
			$this->response->setOutput($this->render());
		}
	}
	
	public function success() {
		$v14x = (!defined('VERSION') || VERSION < 1.5);
		$v150 = (strpos(VERSION, '1.5.0') === 0);
		$v151 = (strpos(VERSION, '1.5.1') === 0);
		
		$this->language->load('information/form');
		
		if ($v14x) {
			$this->document->title = $this->language->get('heading_title');
			$this->document->breadcrumbs = array();
			$this->document->breadcrumbs[] = array(
				'href'		=> HTTP_SERVER . 'index.php?route=common/home',
				'text'		=> $this->language->get('text_home'),
				'separator'	=> FALSE
			);
			$this->document->breadcrumbs[] = array(
				'href'		=> HTTP_SERVER . 'index.php?route=information/contact',
				'text'		=> $this->language->get('heading_title'),
				'separator'	=> $this->language->get('text_separator')
			);
		} else {
			$this->document->setTitle($this->language->get('heading_title'));
			$this->data['breadcrumbs'] = array();
			$this->data['breadcrumbs'][] = array(
				'text'		=> $this->language->get('text_home'),
				'href'		=> $this->url->link('common/home'),
				'separator'	=> FALSE
			);
			$this->data['breadcrumbs'][] = array(
				'text'		=> $this->language->get('heading_title'),
				'href'		=> $this->url->link('information/contact'),
				'separator'	=> $this->language->get('text_separator')
			);
		}
		
		$this->data['heading_title'] = $this->language->get('heading_title');
		$this->data['text_message'] = $this->language->get('text_message');
		$this->data['button_continue'] = $this->language->get('button_continue');
		
		$this->data['continue'] = $this->makeURL('common/home');
		
		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/success.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/common/success.tpl';
		} else {
			$this->template = 'default/template/common/success.tpl';
		}
		
		if ($v14x) {
			$this->children = array(
				'common/column_right',
				'common/footer',
				'common/column_left',
				'common/header'
			);
			$this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
		} else {
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);
			$this->response->setOutput($this->render());
		}
	}
	
	public function captcha() {
		$this->load->library('captcha');
		
		$captcha = new Captcha();
		
		$this->session->data['captcha'] = $captcha->getCode();
		
		$captcha->showImage();
	}
	
	private function makeURL($route, $args = '', $connection = 'NONSSL') {
		if (!defined('VERSION') || VERSION < 1.5) {
			$url = ($connection == 'NONSSL') ? HTTP_SERVER : HTTPS_SERVER;
			$url .= 'index.php?route=' . $route;
			if ($args) {
				$url .= '&' . ltrim($args, '&');
			}
			return $url;
		} else {
			return $this->url->link($route, $args, $connection);
		}
	}
	
	private function validate($form = array()) {
		if (isset($form['fields'])) {
			foreach ($form['fields'] as $field) {
				$key = preg_replace('/[^\w]/', '', $field['name']);
				if ($field['required'] && !((isset($this->request->post[$key]) && $this->request->post[$key]) || (isset($this->request->files[$key]['name']) && $this->request->files[$key]['name']))) {
					$this->error['required'] = $this->language->get('error_required');
					break;
				}
			}
		}
		
		if ($form['captcha']) {
			if (!isset($this->session->data['captcha']) || ($this->session->data['captcha'] != $this->request->post['captcha'])) {
				$this->error['captcha'] = $this->language->get('error_captcha');
			}
		}
		
		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
}
?>