<?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/
 */

/**
 * 独自App Contoroller
 */

App::import('Vendor', 'pear_ini');  

class AppController extends Controller
{
	var $user = array('User' => array(
		'id' => 0,
		'group_id' => 0,
	));
	var $user_id = 0;
	var $isAdministrator = false;
	var $isAdmin = false;

	var $site_configs = array();

	var $components = array(
		'Session',
		'AuthPlus',
		'Cakeplus.HtmlEscape',
		'Token',
		'Crypt',
		'DebugKit.Toolbar',
//		'Benchmark'
	);

	var $helpers = array(
		'Html',
		'Form',
		'Js' => array(
		),
		'Text',
		'Time',
		'Settings',
		'Session',
		'Media.Media',
		'Media.Upfile',
		'Cache',
		'PaginatorEx',
		'Token'
	);

	/* Characters抽出条件 */
	var $conditions = array(
		'Character.public_flag' => 1,
		'Character.deleted' => 0
	);
	var $fields = array(
		'Character.id',
		'Character.system_id',
		'Character.user_id',
		'Character.name',
		'Character.main_picture',
		'Character.sort_order',
		'Character.status',
		'Character.public_flag',
		'Character.modified',
	);
	var $contain = array();
	var $recursive = -1;
	var $order = array(
		'Character.modified' => 'DESC',
	);
	var $paginate = array(
		'Character' => array(
			'limit' => 20,
			'conditions' => array(
				'Character.public_flag' => 1,
				'Character.deleted' => 0
			),
			'recursive' => -1,
			'order' => array(
				'Character.modified' => 'DESC',
			)
		),
	);

	var $showlist_cols = array(
	);

	var $cacheAction = array();

	// POSTのTokenチェックをしないアクション
	var $disableTokenActions = array();

	var $model_public_flags = array(
	);

	var $model_status = array(
	);

	var $model_status2 = array(
	);

	function beforeFilter()
	{

		// Session->setFlashのメッセージがある場合、キャッシュしない
		$message = $this->Session->read('Message.flash');
		if (!empty($message['message']) && Configure::read('Cache.check')) {
			Configure::write('Cache.check', false);
		}

		if (isset($this->Benchmark) && is_object($this->Benchmark)) {
			$this->Benchmark->report($this->params['controller']. '/'. $this->action . ':' .' beforeFilterStart');
		}

		parent::beforeFilter();

		$this->user['User']['name'] = __('Guest', true);

		// ブラウザキャッシュ破棄
		$this->disableCache();

		if (isset($this->params['prefix'])) {
			if ($this->params['prefix'] == Configure::read('Routing.base_prefixes')) {
				$this->isAdmin = true;
				$this->layout = 'admin_'.$this->layout;
			}
		}
		$this->set('admin', $this->isAdmin);

		// サイト設定
		$this->site_configs = CorePlus::set_db_settings();
		$this->set('site_configs', $this->site_configs);

		if ($this->AuthPlus) {
//			// ACL関連
//			$this->AuthPlus->actionPath = 'controllers/';
//			$this->AuthPlus->authorize = 'crud';
			$this->AuthPlus->authorize = 'orig';
			// 認証済みユーザ情報のセット
			$this->user_id = $this->AuthPlus->user('id');
			$user = $this->getUser($this->user_id);
			if (!empty($user)) {
				$this->user = $user;
			}

			if (in_array($this->AuthPlus->user('group_id'), array(1,2,3))) {
				$this->isAdministrator = true;
			}

			// 対CRSF:Tokenチェック
			$this->Token->checkToken();

			// 認証アクション設定
			$this->AuthPlus->loginAction = '/users/login';
			$this->AuthPlus->loginRedirect = Configure::read('Routing.basePath');
			$this->AuthPlus->logoutRedirect = Configure::read('Routing.basePath');
			if ($this->isAdmin) {
				$this->AuthPlus->loginRedirect = '/admin/users/index';
			}
		}
		$this->set('user', $this->user);
		$this->set('isAdministrator', $this->isAdministrator);
	}

	function beforeRender()
	{
		if (isset($this->Benchmark) && is_object($this->Benchmark)) {
			$this->Benchmark->report($this->params['controller']. '/'. $this->action . ':' . ' beforeRenderStart');
		}

		parent::beforeRender();
	}

	function afterFilter()
	{
		if (isset($this->Benchmark) && is_object($this->Benchmark)) {
			$this->Benchmark->report($this->params['controller']. '/'. $this->action . ':' . ' afterFilterStart');
		}
		parent::afterFilter();
	}

	/* 共通関数 */
	/* public_flag設定をview用にセット */
	function set_public_flag4view()
	{
		$this->model_public_flags = $this->get_public_flag();

		$this->set('public_flags', $this->model_public_flags);
	}
	function get_public_flag()
	{
		return $this->{$this->modelClass}->public_flag;
	}
	function check_public_flag($data, $key = null)
	{
		return CorePlus::check_public_flag($data, $key);
	}
	function check_public_flag2($data, $key = null)
	{
		return CorePlus::check_public_flag2($data, $key);
	}

	/* status設定をview用にセット */
	function set_status4view()
	{
		$this->model_status = $this->get_status();

		$this->set('status', $this->model_status);

		$this->model_status2 = array_merge($this->model_status, array('all' => 'all'));

		$this->set('status2', $this->model_status2);
	}
	function get_status()
	{
		if (isset($this->Character)) {
			return $this->Character->status;
		} elseif (isset($this->CharacterProfileArchive)) {
			return $this->CharacterProfileArchive->Character->status;
		} else {
			return array();
		}
	}

	/* isOwner */
	function isOwner($data, $user_id)
	{
		return CorePlus::isOwner($data, $user_id);
	}

	/* ユーザ情報取得 */
	function getUser($id, $isAdmin=false, $isDelete=false) {
		if (!$id) {
			return array();
		}

		if (!isset($this->User)) {
			$this->User = CorePlus::set_model('User');
		}

		$conditions = array(
			'User.id' => $id,
		);
		if ($isAdmin === true) {
			$conditions['User.group_id'] = array(
				Configure::read('Group.admin'),
				Configure::read('Group.subadmin'),
				Configure::read('Group.watcher'),
				Configure::read('Group'),
				Configure::read('Group.locked'),
				Configure::read('Group.pre'),
			);
		} else {
			$conditions['User.group_id'] = array(
				Configure::read('Group.admin'),
				Configure::read('Group.subadmin'),
				Configure::read('Group.watcher'),
				Configure::read('Group.member'),
				Configure::read('Group.locked'),
			);
		}

		$fields = array(
			'User.id',
			'User.group_id',
			'User.name',
			'User.pcmail',
			'User.url',
			'User.notes',
			'User.modified',
		);
		if ($isAdmin === true) {
			$fields = array_merge($fields, array(
				'User.username',
				'User.useragent',
				'User.host',
				'User.created',
			));
		}

		$contain = array(
			 'Attachment',
		);
		if ($this->name == 'Users') {
			$contain = array_merge($contain, array(
				'CharacterSheet' => array(
					'System',
				),
			));
		}

		if ($id == $this->user_id || $isAdmin === true) {
			unset($this->User->hasMany['CharacterSheet']['conditions']['CharacterSheet.public_flag']);
		} else {
			$this->User->hasMany['CharacterSheet']['conditions']['CharacterSheet.public_flag'] = 1;
		}

		if ($isAdmin === true || $isDelete === true) {
			$contain = array_merge($contain, array(
				'Character',
			));

			unset($this->User->hasMany['Character']['conditions']['Character.public_flag']);
			unset($this->User->hasMany['Character']['limit']);
		}

		if (empty($contain)) {
			$recursive = -1;
		} else {
			$recursive = Set::countDim($contain, true);
		}

		$user = $this->User->find('first', array(
			'conditions' => $conditions,
			'fields' => $fields,
			'recursive' => $recursive,
			'contain' => $contain,
		));

		return $user;
	}

	/* 指定Systemを取得 */
	function _getThisSystem($id, $isAdmin = false)
	{
		static $this_system;
		static $prev_id;
		static $prev_isAdmin;

		if (!empty($this_system) 
			&& (!empty($prev_id) && $id == $prev_id)
			&& ($isAdmin == $prev_isAdmin)) {
			return $this_system;
		}

		$prev_id = $id;
		$prev_isAdmin = $isAdmin;
		$system_conditions['System.id'] = $id;
		if ($isAdmin === false) {
			$system_conditions['System.public_flag'] = 1;
		}

		$this_system = $this->{$this->modelClass}->System->find('first', array(
			'conditions' => $system_conditions,
			'recursive' => -1,
		));

		if (!isset($this_system['System'])) {
			$this->Session->setFlash(__('Invalid System.', true));
			$this->redirect(array('action' => 'index'));
		}

		return $this_system;
	}

	/* デモモードチェック */
	function _check_demo()
	{
		if (Configure::read('Mode.Demo')) {
			if ($_SESSION['Auth']['User']['username'] == 'guest') {
				$this->Session->setFlash(__('Unavailable for GUEST.', true));

				if ($this->site_configs['User.newUserRegist']['value']) {
					$this->redirect(array('controller' => 'users', 'action'=>'add'));
				// 新規登録停止の場合
				} else {
					$this->redirect(array('action'=>'index'));
				}
			}
		}
	}

	/* システム情報取得 */
	function _restore_html_system($data, $nl2br = false) {
		if (isset($data['System']['name'])  && !empty($data['System']['name'])) {
			$data['System']['name'] = $this->{$this->modelClass}->restore_html($data['System']['name'], false, false, false);
		}
		if (isset($data['System']['copyright'])  && !empty($data['System']['copyright'])) {
			$data['System']['copyright'] = $this->{$this->modelClass}->restore_html($data['System']['copyright'], false, false, false);
		}
		if (isset($data['System']['url'])  && !empty($data['System']['url'])) {
			$data['System']['url'] = $this->{$this->modelClass}->restore_html($data['System']['url'], false, false, false);
		}
		if (isset($data['System']['detail'])  && !empty($data['System']['detail'])) {
			$data['System']['detail'] = $this->{$this->modelClass}->restore_html($data['System']['detail'], false, false, false);
			if ($nl2br) {
				$data['System']['detail'] = str_replace('<br />', "\n", $data['System']['detail']);
			}
		}
		if (isset($data['System']['ad'])  && !empty($data['System']['ad'])) {
			$data['System']['ad'] = $this->{$this->modelClass}->restore_html($data['System']['ad'], false, false, false);
		}

		if (isset($data['Profile']) && !empty($data['Profile'])) {
			$data = $this->_restore_html_profile($data);
		}

		return $data;
	}

	function _get_systems($public_flag = 1, $conditions = array(), $fields = array())
	{
		if (!isset($this->System)) {
			$this->System = CorePlus::set_model('System');
		}

		if (empty($public_flag)) {
			if (isset($conditions['System.public_flag'])) {
				unset($conditions['System.public_flag']);
			}
		} else {
			$conditions = array_merge(
				$conditions,
				array(
					'System.public_flag' => $public_flag,
				)
			);
		}


		$fields = array_merge(
			array(
				'System.id',
				'System.name',
				'System.sort_order',
			),
			$fields
		);

		$systems = $this->System->find('all', array(
			'conditions' => $conditions,
			'fields' => $fields,
			'recursive' => -1,
		));

		if (!empty($systems)) {
			$systems = $this->_restore_html_get_systems($systems, $public_flag);
		}

		return $systems;
	}

	/* キャラクター一覧取得 */
	/* 条件セット */
	function _set_conditions_characters4user_id($user_id = null, $conditions = array(), $fields = array(), $contain = array(), $order = array())
	{
		if (!empty($this->showlist_cols)) {
			$this->contain = array_merge($this->contain, array('CharactersHasProfile'));
			if (isset($this->showlist_cols['Profile']) && !empty($this->showlist_cols['Profile'])) {
				$this->Character->hasMany['CharactersHasProfile']['conditions']['CharactersHasProfile.profile_id'] = $this->showlist_cols['Profile'];
			}
		}

		if (!empty($user_id)) {
			$conditions = array_merge((array)$conditions, 
				array(
					'Character.user_id' => $user_id,
				)
			);

		}

		$conditions = array_merge($this->conditions, (array)$conditions);
		if ((isset($conditions['isAdmin']) && !empty($conditions['isAdmin']))
			|| (!empty($user_id) && ($user_id == $this->user_id))
			|| (isset($conditions['public_force']) && !empty($conditions['public_force']))) {
			if (isset($this->Character->hasMany['CharactersHasProfile']['conditions']['CharactersHasProfile.public_flag'])) {
				unset($this->Character->hasMany['CharactersHasProfile']['conditions']['CharactersHasProfile.public_flag']);
			}
			unset($conditions['Character.public_flag']);
			unset($conditions['CharactersHasProfile.public_flag']);
		} else {
			if (isset($conditions['profile_search'])) {
				$this->Character->hasMany['CharactersHasProfile']['conditions']['CharactersHasProfile.public_flag'] = 1;
			}
			$conditions['Character.public_flag'] = 1;
/*			if (!isset($conditions['CharactersHasProfile.public_flag']) || empty($conditions['CharactersHasProfile.public_flag'])) {
				$conditions['CharactersHasProfile.public_flag'] = 1;
			}*/
		}
		unset($conditions['isAdmin']);
		unset($conditions['public_force']);

		$fields = array_merge($this->fields,
			(array)$fields
		);

		$contain = array_merge($this->contain, (array)$contain);
		$contain = array_unique($contain);
		if (empty($contain)) {
			$recursive = -1;
		} else {
			$recursive = Set::countDim($contain);
		}

		$order = array_merge($this->order, (array)$order);

		return array($conditions, $fields, $contain, $recursive, $order);
	}

	function _get_characters_list4user_id($user_id = null, $conditions = array(), $limit = 5, $fields = array(), $contain = array(), $order = array())
	{
		list($conditions, $fields, $contain, $recursive, $order) = $this->_set_conditions_characters4user_id($user_id, $conditions, $fields, $contain, $order);

		if ($this->modelClass != 'Character') {
			$this->Character = CorePlus::set_model('Character');
		}

		return $this->Character->find('all', array(
			'conditions' => $conditions,
			'limit' => $limit,
			'fields' => $fields,
			'recursive' => $recursive,
			'contain' => $contain,
			'order' => $order,
		));
	}

	function _get_characters_page4user_id($user_id = null, $conditions = array(), $limit = 20, $fields = array(), $contain = array(), $order = array(), $page = 1)
	{
		list($conditions, $fields, $contain, $recursive, $order) = $this->_set_conditions_characters4user_id($user_id, $conditions, $fields, $contain, $order);

		if (!isset($this->Character)) {
			$this->Character = CorePlus::set_model('Character');
		}

		// Systemの取得項目
		if ($key = array_search('System.copyright', $this->Character->belongsTo['System']['fields'])) {
			unset($this->Character->belongsTo['System']['fields'][$key]);
		}

		$this->paginate['Character'] = array(
			'limit' => $limit,
			'conditions' => $conditions,
			'fields' => $fields,
			'contain' => $contain,
			'recursive' => $recursive,
			'order' => $order,
			'page' => $page
		);

		return $this->paginate('Character');
	}


	/* キャラクター情報取得 */
	function _get_character4character_id($character_id, $user_id = null, $public_flag = null, $is_deleted = 0)
	{
		if (!isset($this->Character)) {
			$this->Character = CorePlus::set_model('Character');
		}

		$conditions = array(
			'Character.id' => $character_id,
			'Character.deleted' => $is_deleted,
		);
		if ($user_id) {
			$conditions['Character.user_id'] = $user_id;
		}

		unset($this->Character->hasMany['CharacterPicture']['conditions']['CharacterPicture.public_flag']);
		if ($public_flag) {
			$conditions['Character.public_flag'] = $public_flag;
			$this->Character->hasMany['CharacterPicture']['conditions']['CharacterPicture.public_flag'] = $public_flag;
		}

		$character = $this->Character->find('first', array(
			'conditions' => $conditions,
			'contain' => array(
				'CharacterPicture' => array(
					'Attachment',
				),
			),
			'recursive' => 2,
		));
		if (empty($character)) {
			$this->Session->setFlash(__('Invalid Character.', true));
			$this->redirect(array('controller' => 'characters', 'action'=>'index'));
		}
		return $character;
	}

	function check_character_picture_max($character_pictures_num)
	{
		if (!$max_num = intval($this->site_configs['Character.maxPictures']['value'])) {
			return true;
		}

		if ($max_num <= $character_pictures_num) {
			return false;
		}

		return true;
	}

	/* restore_html */
	function _restore_html_user($data, $nl2br = false) {
		$data['name'] = $this->{$this->modelClass}->restore_html($data['name'], false, false, false);

		if (isset($data['notes']) && !empty($data['notes'])) {
			$data['notes'] = $this->{$this->modelClass}->restore_html($data['notes'], false, false, false);
			if ($nl2br) {
				$data['notes'] = str_replace('<br />', "\n", $data['notes']);
			}
		}

		// アドレス復号化
		$data = $this->decrypt_mail($data);

		return $data;
	}
	function _restore_html_news($data, $nl2br = false) {
		$data['title'] = $this->{$this->modelClass}->restore_html($data['title'], false, false, false);

		if (isset($data['value']) && !empty($data['value'])) {
			$data['value'] = $this->{$this->modelClass}->restore_html($data['value'], false, false, false);
			if ($nl2br) {
				$data['value'] = str_replace('<br />', "\n", $data['value']);
			}
		}

		return $data;
	}

	// アドレス復号化
	function decrypt_mail($data)
	{
		if (isset($data['pcmail']) && !empty($data['pcmail'])) {
			$data['pcmail'] = $this->Crypt->decrypt($data['pcmail']);
		}
		return $data;
	}

	/* Profile系 htmlRestore */
	function _restore_html_profile($data) {
		if (isset($data['Profile']['name'])  && !empty($data['Profile']['name'])) {
			$data['Profile']['name'] = $this->{$this->modelClass}->restore_html($data['Profile']['name'], false, false, false);
		}

		if (isset($data['Profile'][0]['ProfileSelect'])) {
			foreach ($data['Profile'] as $k => $v) {
				$data['Profile'][$k] = $this->__restore_html_profile($v);
			}
			$data['Profile'] = $this->_restore_html_profiles($data['Profile']);

		} elseif(isset($data['Profile']['ProfileSelect'])) {
			$data['Profile'] = $this->__restore_html_profile($data['Profile']);
		}

		return $data;
	}
	function __restore_html_profile($data) {
		if (isset($data['ProfileSelect']) && !empty($data['ProfileSelect'])) {
			$data['ProfileSelect'] = $this->_restore_html_profile_select($data['ProfileSelect']);
		}
		if (isset($data['ProfileTable']) && !empty($data['ProfileTable'])) {
			$data['ProfileTable'] = $this->_restore_html_profile_table($data['ProfileTable']);
			if (isset($data['ProfileTable'][0]['ProfileTableStatic']) && !empty($data['ProfileTable'][0]['ProfileTableStatic'])) {
				$data['ProfileTable'][0]['ProfileTableStatic'] = $this->_restore_html_profile_table_static($data['ProfileTable'][0]['ProfileTableStatic']);
			}
		}

		return $data;
	}
	function _restore_html_profiles($data) {
		$sort_order = array();
		foreach ($data as $k => $v) {
			if (isset($v['value'])  && !empty($v['value'])) {
				$data[$k]['value'] = $this->{$this->modelClass}->restore_html($v['value'], false, false, false);
			}

			if (isset($v['sort_order'])  && !empty($v['sort_order'])) {
				$sort_order[$k] = $v['sort_order'];
			} else {
				$sort_order[$k] = 0;
			}
		}

		$data = $this->sort4sort_order($data, $sort_order);

		return $data;
	}
	function _restore_html_get_systems($data, $public_flag = array()) {
		$sort_order = array();
		foreach ($data as $k => $v) {
			$restored[$this->{$this->modelClass}->restore_html($v['System']['name'])] = $v['System']['id'];
			// SingleSystem
			if (isset($this->site_configs['System.singleSystem']['value']) && $this->site_configs['System.singleSystem']['value'] && !empty($public_flag)) {
				return $restored;
			}

			if (isset($v['System']['sort_order'])  && !empty($v['System']['sort_order'])) {
				$sort_order[$v['System']['id']] = $v['System']['sort_order'];
			} else {
				$sort_order[$v['System']['id']] = 0;
			}
		}

		$restored = $this->sort4sort_order($restored, $sort_order);

		return array_flip($restored);
	}
	function _restore_html_profile_select($data) {
		$sort_order = array();
		foreach ($data as $k => $v) {
			if (isset($v['value'])  && !empty($v['value'])) {
				$data[$k]['value'] = $this->{$this->modelClass}->restore_html($v['value'], false, false, false);
			}

			if (isset($v['sort_order'])  && !empty($v['sort_order'])) {
				$sort_order[$k] = $v['sort_order'];
			} else {
				$sort_order[$k] = 0;
			}
		}

		$data = $this->sort4sort_order($data, $sort_order);

		return $data;
	}
	function _restore_html_profile_table($data) {
		foreach ($data as $k => $v) {
			if (isset($v['value'])  && !empty($v['value'])) {
				$data[$k]['value'] = $this->{$this->modelClass}->restore_html($v['value'], false, false, false);
			}

			if (isset($v['sort_order'])  && !empty($v['sort_order'])) {
				$sort_order[$k] = $v['sort_order'];
			} else {
				$sort_order[$k] = 0;
			}
		}

		$data = $this->sort4sort_order($data, $sort_order);

		return $data;
	}
	function _restore_html_profile_table_static($data) {
		if (empty($data) || !is_array($data)) {
			return $data;
		}

		foreach ($data as $k => $v) {
			if (isset($v['title'])  && !empty($v['title'])) {
				$data[$k]['title'] = $this->{$this->modelClass}->restore_html($v['title'], false, false, false);
			}

			if (isset($v['sort_order'])  && !empty($v['sort_order'])) {
				$sort_order[$k] = $v['sort_order'];
			} else {
				$sort_order[$k] = 0;
			}
		}

		$data = $this->sort4sort_order($data, $sort_order);

		return $data;
	}

	function sort4sort_order($data, $sort_order)
	{
		if (empty($data) || empty($sort_order)) {
			return $data;
		}
		array_multisort($sort_order, SORT_ASC, $data);

		return $data;
	}

	function _checkCharaSheeOwner($characterSheet)
	{
		if (!isset($characterSheet['CharacterSheet']) || empty($characterSheet['CharacterSheet']) || !isset($characterSheet['CharacterSheet']['user_id']) || empty($characterSheet['CharacterSheet']['user_id'])) {
			return false;
		}

		if ($characterSheet['CharacterSheet']['user_id'] == $this->user_id) {
			return true;
		}

		return false;
	}

	function checkEditOtherSystem($system_id = null)
	{
		if ($this->isOtherSystem($system_id)) {
			$this->Session->setFlash(__('Other System cannot have ANY PROFILE SETTINGS.', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'view', $system_id));
		}
	}
	function isOtherSystem($system_id = null)
	{
		if (empty($system_id)) {
			return false;
		}

		if (empty($this->site_configs['System.otherSetting']['value']) || $this->site_configs['System.otherSetting']['value'] != $system_id) {
			return false;
		}

		return true;
	}


	/* POSTのCharactersHasProfileを処理 */
	function _set_new_characters_has_profile($characters_has_profiles, $profile_id = null, $now_data = array(), $allow_blank = false)
	{
		$prev_profile_id = null;
		$profileTable_tmp = array();
		$i = 0;
		$public = null;
		foreach ($characters_has_profiles as $k => $v) {
			if (!empty($character_id)) {
				$characters_has_profiles[$k]['character_id'] = $character_id;
			}
			// 配列valueの処理
			if (is_array($v['value'])) {
				$characters_has_profiles[$k]['value'] = $v['value'][0];
			}

			// サニタイズ
			$characters_has_profiles[$k]['value'] = str_replace("\\", '', $characters_has_profiles[$k]['value']);

			// textarea改行処理
			if (isset($v['is_textarea']) && $v['is_textarea'] == 1) {
//				$characters_has_profiles[$k]['value'] = str_replace(array("\n\r", '\n', "\r"), '<br />', $characters_has_profiles[$k]['value']);
			}

			// 空の値処理, public_flag
			// table: 一時保管して全項目空の場合行削除
			if (CorePlus::is_valid($v, 'profile_table_id')) {
				if (isset($profileTable_tmp[$v['profile_id']][$i][$v['profile_table_id']])) {
					$i++;
					$public = null;
				}

				// 行単位public_flag
				if ($public == null && isset($characters_has_profiles[$k]['public_flag'])) {
					$public = $v['public_flag'];
					// Static設定タイトルは公開
					if ($v['profile_table_static_id']) {
						$characters_has_profiles[$k]['public_flag'] = 1;
					}
				} else {
					$characters_has_profiles[$k]['public_flag'] = $public;
				}

				$profileTable_tmp[$v['profile_id']][$i][$v['profile_table_id']] = array($characters_has_profiles[$k], $k);
			// $allow_blank = falseならそれ以外は削除
			} elseif (empty($v['value']) && empty($allow_blank)) {
				unset($characters_has_profiles[$k]);
			}
		}

		// table: 空行削除、不正profile_table_idデータ削除
		if (!empty($profileTable_tmp)) {
			if (!isset($this->Character->ProfileTable)) {
				$this->Character->ProfileTable = CorePlus::set_model('ProfileTable');
			}
			foreach($profileTable_tmp as $profile_id => $v) {
				$profile_table_columns = $this->Character->ProfileTable->find('list', array(
					'conditions' => array('ProfileTable.profile_id' => $profile_id),
					'fields' => array('ProfileTable.id'),
					'order' => array('ProfileTable.sort_order' => 'asc'),
					'recursive' => -1,
				));

				foreach ($v as $i => $profile_tables) {
					// 不正POSTの削除
					$diff_keys = array_diff_key($profile_tables, $profile_table_columns);
					if (!empty($diff_keys)) {
						foreach($diff_keys as $dvalue) {
							unset($characters_has_profiles[$dvalue[1]]);
						}
					}

					// 空行削除
					$delete_flg = true;
					foreach($profile_table_columns as $k2 => $columns) {
						if (CorePlus::is_valid($profile_tables, $columns.'.0.value')) {
							$delete_flg = false;
							break;
						}
					}
					if ($delete_flg === true) {
						foreach ($profile_tables as $delk) {
							unset($characters_has_profiles[$delk[1]]);
						}
					}
				}
			}
		}

		// 指定データのみ変更
		if (!is_null($profile_id) && !empty($now_data)) {
			$tmp = array();
			$i = 0;
			foreach($now_data as $k => $v) {
				if ($v['id'] == $profile_id) {
					$v['CharactersHasProfile'] = $characters_has_profiles;
				}

				foreach ($v['CharactersHasProfile'] as $k2 => $v2) {
					$tmp[$i] = $v2;
					if (isset($tmp[$i]['id'])) {
						unset($tmp[$i]['id']);
					}
					if (isset($tmp[$i]['character_id'])) {
						unset($tmp[$i]['character_id']);
					}

					$i++;
				}
			}

			$characters_has_profiles = $tmp;
		}

		return $characters_has_profiles;
	}

	// 最新のお知らせ
	function get_news($limit = 5) {
		$this->News = CorePlus::set_model('News');

		$news = $this->News->find('all', array(
			'conditions' => array(
				'News.public_flag' => 1,
				'News.end_date > ' => date('Y-m-d 00:00:00', time()),
			),
			'fields' => '',
			'recursive' => -1,
			'order' => array(
				'News.date' => 'desc'
			),
			'limit' => $limit,
		));

		foreach($news as $k => $v) {
			$news[$k]['News'] = $this->_restore_html_news($v['News']);
		}

		return $news;
	}

}

/*
 * データ処理用
 */

/*
 * 文字コード変換 SJISWin->UTF-8
 */
function convertEncodeSjis2Utf8(&$str, $key)
{
	$str = mb_convert_encoding($str, 'UTF-8', 'SJIS-Win');
}

