<?php
/**
 * SystemManager Controller
 *
 * @author Noriko Arai <arai@nii.ac.jp>
 * @author Shohei Nakajima <nakajimashouhei@gmail.com>
 * @link http://www.netcommons.org NetCommons Project
 * @license http://www.netcommons.org/license.txt NetCommons License
 * @copyright Copyright 2014, NetCommons Project
 */

App::uses('SystemManagerAppController', 'SystemManager.Controller');

/**
 * システム管理【セキュリティ設定】
 *
 * @author Shohei Nakajima <nakajimashouhei@gmail.com>
 * @package NetCommons\SystemManager\Controller
 */
class SecuritySettingsController extends SystemManagerAppController {

/**
 * use model
 *
 * @var array
 */
	public $uses = array(
		'SiteManager.SiteSetting',
		'UserRoles.UserRole',
	);

/**
 * edit
 *
 * @return void
 */
	public function edit() {
		//会員権限リストを取得する
		$userRoles = $this->UserRole->find('list', array(
			'recursive' => -1,
			'fields' => array('key', 'name'),
			'conditions' => array(
				'language_id' => Current::read('Language.id')
			),
			'order' => array('id' => 'asc')
		));
		$this->set('userRoles', $userRoles);

		//リクエストセット
		if ($this->request->is('post')) {
			$data = $this->request->data['SiteSetting'];
			$value = $data['Security.deny_ip_move']['0']['value'];
			if (is_array($value)) {
				$data['Security.deny_ip_move']['0']['value'] = implode('|', $value);
			}

			//登録処理
			$this->request->data['SiteSetting'] = $data;
			$this->SiteSetting->userRoles = $userRoles;
			$this->SiteManager->saveData();

		} else {
			$this->request->data['SiteSetting'] = $this->SiteSetting->getSiteSettingForEdit(
				array('SiteSetting.key' => array(
					// * アップロードファイルの許可拡張子
					'Upload.allow_extension',
					// * IP変動を禁止する会員権限
					'Security.deny_ip_move',
					// * IPアドレスでアクセス拒否する
					'Security.enable_bad_ips',
					// * アクセス拒否IPアドレス
					'Security.bad_ips',
					// * 管理画面のアクセスをIPアドレスで制御する
					'Security.enable_allow_system_plugin_ips',
					// * 管理画面アクセス許可IPアドレス
					'Security.allow_system_plugin_ips',
				)
			));

			$ips = $this->request->data['SiteSetting']['Security.allow_system_plugin_ips']['0']['value'];
			if (! $this->SiteSetting->hasCurrentIp($ips)) {
				$ips = Hash::get($_SERVER, 'REMOTE_ADDR');
				$this->request->data['SiteSetting']['Security.allow_system_plugin_ips']['0']['value'] = $ips;
			}
		}
	}
}
