<?php
/*
 * PHP version 5
 *
 * @copyright Copyright 2010, Cake. (http://trpgtools-onweb.sourceforge.jp/)
 * @category Controller
 * @package  TRPG Data Bank
 * @version  beta
 * @author   Cake <cake_67@users.sourceforge.jp>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://trpgtools-onweb.sourceforge.jp/
 */

class SendMailsController extends AppController {
	var $name = 'SendMails';

	var $components = array(
		'Mail',
		'Crypt',
	);

	var $helpers = array(
		'formhidden',
		'xformjp',
	);

	var $disableTokenActions = array();

	// listView用のpagenate設定
	var $paginate = array(
		'conditions' => array(
		),
		'fields' => '',
		'recursive' => 1,
		'contain' => array(
			'User',
			'FromUser',
		),
		'limit' => 20,
		'order' => array(
			'SendMail.modified' => 'desc'
		),
	);


	function beforeFilter() {

		parent::beforeFilter();

		// 認証なしアクセス可
		$this->AuthPlus->allow('contact');
		$this->AuthPlus->allow('contact_confirm');
		$this->AuthPlus->allow('contact_finish');

		if (!empty($this->user_id)) {
			$this->disableTokenActions = array(
				'contact',
			);
		}

		if (isset($this->user['User']['pcmail']) && !empty($this->user['User']['pcmail'])) {
			$this->user['User'] = $this->decrypt_mail($this->user['User']);
		
			$this->set('user', $this->user);
		}
	}

	function contact() {
		if (!$this->_checkContactAvailable()) {
			$this->Session->setFlash(__('The contact is not available now.', true));
			$this->redirect(array('controller' =>'users', 'action' => 'index'));
		}

		$this->set('title_for_layout', " - ". __('Contact', true));
	}

	function contact_confirm() {
		if (!$this->_checkContactAvailable()) {
			$this->Session->setFlash(__('The contact is not available now.', true));
			$this->redirect(array('controller' =>'users', 'action' => 'index'));
		}

		$xformHelperConfirmFlag = true;

		if (!empty($this->data)) {
			$this->SendMail->beforeSave();
			$this->SendMail->set($this->data);
			if ($this->SendMail->validates()) {
				$this->set('title_for_layout', " - ". __('Contact Confirm', true));
			} else {
				$xformHelperConfirmFlag = false;
				$this->render('contact');
				$this->set('title_for_layout', " - ". __('Contact Mail', true));
			}
		} else {
			$this->Session->setFlash(__('No Data.', true));
			$this->redirect(array('action' => 'contact'));
		}

		$this->params['xformHelperConfirmFlag'] = $xformHelperConfirmFlag;
	}

	function contact_finish() {
		if (!$this->_checkContactAvailable()) {
			$this->Session->setFlash(__('The contact is not available now.', true));
			$this->redirect(array('controller' =>'users', 'action' => 'index'));
		}

		if (!empty($this->data)) {
			$postdata = $this->data;

			$this->data['SendMail']['user_id'] = 1;

			if (!empty($this->user_id)) {
				$this->data['SendMail']['from_user_id'] = $this->user_id;
			}

			$this->data['SendMail']['useragent'] = $_SERVER["HTTP_USER_AGENT"];
			$this->data['SendMail']['host'] = gethostbyaddr($_SERVER["REMOTE_ADDR"]);

			$this->SendMail->set($this->data);
			if ($this->SendMail->validates()) {
			
				$from = $this->data['SendMail']['from'];
				$this->data['SendMail']['from'] = $this->Crypt->crypt($this->data['SendMail']['from']);
				$this->data['SendMail']['subject'] = sprintf(__('[%s %s] ', true), $this->site_configs['Site.siteName']['value'], __('Contact', true)). $this->data['SendMail']['subject'];

				$this->SendMail->create();
				if ($this->SendMail->save($this->data, array('fieldList' => $this->SendMail->fields['add'], 'validate' => false))) {
					$subject = htmlspecialchars($this->data['SendMail']['subject']);
					$body = htmlspecialchars($this->data['SendMail']['body']);


					$this->Mail->send_mail(
						$this->site_configs['Site.adminAddress']['value'],
						$subject, 
						$body, 
						'default', 
						array(
							'from' => $from,
						)
					);

					$this->Session->setFlash(__('The sending email has been done.', true));
				} else {
					$this->data = $postdata;
				}
			} else {
				$this->Session->setFlash(__('The sending email failed. Please, try again.', true));
				$this->render('contact');
				$this->set('title_for_layout', " - ". __('Contact Mail', true));
			}
		} else {
			$this->Session->setFlash(__('No Data.', true));
			$this->redirect(array('action' => 'contact'));
		}
	}


	function admin_index() {
		$this->SendMail->recursive = 0;

		$send_mails = $this->paginate();
		foreach ($send_mails as $k => $v) {
			$send_mails[$k] = $this->_restore_html_sendmail($v);
		}

		$this->set('sendMails', $send_mails);
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for send mail', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->SendMail->delete($id)) {
			$this->Session->setFlash(__('Send mail deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Send mail was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}


		function _checkContactAvailable()
		{
			if (empty($this->site_configs['Site.useContact']['value'])) {
				return false;
			}

			if (empty($this->site_configs['Site.adminAddress']['value'])) {
				return false;
			}

			return true;
		}

		function _restore_html_sendmail($data, $nl2br = false) {
			if (isset($data['SendMail']['from']) && !empty($data['SendMail']['from'])) {
				$data['SendMail']['from'] = $this->Crypt->decrypt($data['SendMail']['from']);
			}

			if (isset($data['User']['pcmail']) && !empty($data['User']['pcmail'])) {
				$data['User']['pcmail'] = $this->Crypt->decrypt($data['User']['pcmail']);
			}
			if (isset($data['FromUser']['pcmail']) && !empty($data['FromUser']['pcmail'])) {
				$data['FromUser']['pcmail'] = $this->Crypt->decrypt($data['FromUser']['pcmail']);
			}

			$data['SendMail']['body'] = $this->{$this->modelClass}->restore_html($data['SendMail']['body'], false, false, false);
			if ($nl2br) {
				$data['SendMail']['body'] = str_replace('<br />', "\n", $data['SendMail']['body']);
			}

			return $data;
		}
}
