<?php
/*
 * Link Plugin for TRPG Databank
 * 
 * PHP version 5
 *
 * @copyright Copyright 2010, Cake. (http://trpgtools-onweb.sourceforge.jp/)
 * @category Controller
 * @package  plugin for 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 LinksController extends AppController {

	var $name = 'Links';

	var $helpers = array(
		'Select',
//		'Count.Count',
		'Links.LinkSelect',
	);

	// リンク先サムネイル設定
	// パラメータの詳細は「Thumbnail Web WEB ASPサービス」
	//  http://www.thumbnail-web.com/asp_setting.php
	var $thumbnail = array(
		'api_url' => 'http://free.thumbnail-web.com/p2',
		'size' => array(
			's' => '140x105',
			'm' => '200x150',
			'l' => '320x240',
		),
		'user_key' => 'guest',
		'options' => array(
			'thumbnailweb_' => array(
				'jump' => '',
				'target' => '_blank',
				'lpos' => 'right',
				'lposv' => '5',
			),
		),
	);

	var $type = array();
	var $type_settings = array();

	// pagenate設定
	// CollectionableBehavoirによりModelにて設定

	var $disableTokenActions = array();

	/* メソッド */
	function setup($options = array()) {
		if (isset($options['thumbnail'])) {
			$this->thumbnail = array_merge($this->thumbnail, (array)$options['thumbnail']);
		}
	}

	function beforeFilter() {
		parent::beforeFilter();

		// Cache
		$this->cacheAction = array(
			'index' => Configure::read('Cache.expire'),
			'listview' => Configure::read('Cache.expire'),
		);

		// 認証なしアクセス可
		$this->AuthPlus->allow('index');
		$this->AuthPlus->allow('listview');
		$this->AuthPlus->allow('visit');

		if (!$this->isAdmin) {
			// 仮：ユーザ側停止
			$this->redirect(array('plugin' => null, 'controller' => 'users', 'action'=>'index'));

			$this->set_members_type();
		}
	}

	function beforeRender()
	{
		parent::beforeRender();

		$this->set_type4view();

		$this->set('thumbnail', $this->thumbnail);
	}

	/* アクションメソッド */
	function index() {
		$this->_index(false);
	}

	function listview() {
		$this->_listview();
	}

	function add() {
		if (!empty($this->data)) {
			$this->_add();
		}
	}

	function edit($id = null) {
		$this->_edit($id);
	}

	function delete($id = null) {
		$this->_delete($id);
	}

	function visit($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for link', true));
			$this->redirect(array('action'=>'listview'));
		}

		$link = $this->_getLink4id($id);

		$url = $link['Link']['url'];

		// redirect
		$this->redirect($url);
		exit;
	}

	function admin_index() {
		$this->_index();
	}

	function admin_listview() {
		$this->_listview();
	}

	function admin_add() {
		if (!empty($this->data)) {
			$this->_add();
		}
	}

	function admin_edit($id = null) {
		$this->_edit($id);
	}

	function admin_delete($id = null) {
		$this->_delete($id);
	}

	function _index() {
		$this->Link->beforeFind('');
		/* WhatsNew */
		// all
		$this->set('all', $this->get_link4options(array('limit9')));

		// By Type
		$this->set('links', array(
			'portal' => $this->get_link4options(array('portal', 'limit5')),
			'online' => $this->get_link4options(array('online', 'limit5')),
			'offline' => $this->get_link4options(array('offline', 'limit5')),
			'tool' => $this->get_link4options(array('tool', 'limit5')),
			'creator' => $this->get_link4options(array('creator', 'limit5')),
			'shop' => $this->get_link4options(array('shop', 'limit5')),
		));

		// ring
		// thans
		$this->set('ring', $this->get_link4options(array('ring', 'unlimited')));
		$this->set('thanks', $this->get_link4options(array('thanks', 'unlimited')));
	}

	function _listview() {
		$this->paginate = $this->Link->options();
		$links = $this->paginate();

		$links = $this->restore_html_link($links, true, false);

		$this->set('links', $links);

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

	function _add() {
		// デモモードチェック
		$this->_check_demo();

		if ($this->isAdmin) {
			$fieldList = $this->Link->fields['admin_add'];
		} else {
			$fieldList = $this->Link->fields['add'];
		}

		$this->data['Link']['user_id'] = $this->user_id;

		// Attachment用
		if (empty($this->data['Attachment'][0]['file']['tmp_name'])) {
			unset($this->data['Attachment']);
		} else {
			$this->data['Attachment'][0]['user_id'] = $this->user_id;
		}
		$this->Link->create();
		if ($this->Link->saveAll($this->data, array('fieldList' => array_merge($fieldList, $this->Link->fields['image']), 'validate' => 'first'))) {
			$this->Session->setFlash(__('The link has been saved', true));
			$this->redirect(array('action' => 'listview'));
		} else {
			$this->Session->setFlash(__('The link could not be saved. Please, try again.', true));
		}

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

	function _edit($id = null) {
		// デモモードチェック
		$this->_check_demo();

		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Id', true));
			$this->redirect(array('action' => 'listview'));
		}
		$link = $this->_getLink4id($id);

		// 権限チェック
		if (!$this->isAdmin) {
			if ($link['Link']['user_id'] != $this->user_id) {
				$this->Session->setFlash(__('No Permission', true));
				$this->redirect(array('action' => 'listview'));
			}
		}

		if (!empty($this->data)) {
			if ($this->isAdmin) {
				$fieldList = $this->Link->fields['admin_edit'];
			} else {
				$fieldList = $this->Link->fields['edit'];
			}

			// URL編集が無い場合
			if ($this->Link->mb_urlEncode($this->data) == $link['Link']['url']) {
				unset($this->Link->validate['url']['isUnique']);
			// URL編集した場合はcreatedも更新
			} else {
				$this->data['Link']['created'] = date('Y-m-d H:i:s');
				$fieldList[] = 'created';
			}

			$this->data['Link']['id'] = $id;
			if ($this->Link->saveAll($this->data, array('fieldList' => array_merge($fieldList, $this->Link->fields['image']), 'validate' => 'first'))) {
				$this->Session->setFlash(__('The link has been saved', true));
				$this->redirect(array('action' => 'listview'));
			} else {
				$this->Session->setFlash(__('The link could not be saved. Please, try again.', true));

				$this->data = $link;
				$this->data['Link']['id'] = $id;

				if (isset($this->data['Attachment'][1])) {
					$delete = $this->data['Attachment'][1]['delete'];
				}
				$this->data['Attachment'] = $link['Attachment'];
			}
		} else {
			$this->data = $this->_restore_html_link($link, false, true);
		}

		$this->set('title_for_layout', " - ". __('Edit Link', true). " - ". $link['Link']['title']. "(". $link['Link']['url']. ")");
	}

	function _delete($id = null) {
		// デモモードチェック
		$this->_check_demo();

		if (!$id) {
			$this->Session->setFlash(__('Invalid id for link', true));
			$this->redirect(array('action'=>'listview'));
		}
		$link = $this->_getLink4id($id);

		// 権限チェック
		if (!$this->isAdmin) {
			if ($link['Link']['user_id'] != $this->user_id) {
				$this->Session->setFlash(__('No Permission', true));
				$this->redirect(array('action' => 'listview'));
			}
		}

		if (isset($this->data['Link']['confirm']) && !empty($this->data['Link']['confirm'])) {
			if ($this->Link->delete($id)) {
				if ($link['Link']['title'] == 'No Title') {
					$link['Link']['title'] = sprintf('Link for %s', $link['Link']['url']);
				}
				$this->Session->setFlash(sprintf(__('%s was deleted.', true), $link['Link']['title']));
				$this->redirect(array('action'=>'listview'));
			}
			$this->Session->setFlash(sprintf(__('%s was deleted.', true), $this->data['Link']['url']));
			$this->redirect(array('action' => 'listview'));
		}

		$this->set('link', $this->_restore_html_link($link, true, false));

		$confirm_message = __('Are you sure you want to delete it?', true);

		$this->Session->setFlash($confirm_message);
		$this->set('title_for_layout', " - ". $confirm_message. " - ". $link['Link']['title']. "(". $link['Link']['url']. ")");
	}

	/* get link By Id */
	function _getLink4id($id = null, $fields = '') {
		if (!$id) {
			$this->Session->setFlash(__('No Id', true));
			$this->redirect(array('action' => 'listview'));
		}

		$link = $this->Link->find('first', array(
			'conditions' => array(
				'Link.id' => $id,
			),
			'fields' => $fields,
			'contain' => array(
			 	'Attachment',
			 	'User',
			),
			'recursive' => 1,
		));

		if (empty($link)) {
			$this->Session->setFlash(__('Invalid Id', true));
			$this->redirect(array('action' => 'listview'));
		}

		// restore
		$link = $this->_restore_html_link($link);

		return $link;
	}

	/* type設定をセット */
	function set_type4view()
	{
		$this->type = $this->get_type_i18n();

		$this->set('type', $this->type);
	}
	function get_type()
	{
		if (isset($this->Link)) {
			return $this->Link->type;
		} else {
			return array();
		}
	}
	function get_type_i18n(){
		$type = $this->get_type();
		$this->set('model_type', $type);

		if (!empty($type)) {
			$this->set_type_i18n();

			$types = array();
			foreach ($type as $k => $v) {
				$types[$k]['name'] = $v;
				if (isset($this->type_settings[$v])) {
					$types[$k]['title'] = $this->type_settings[$v]['title'];
					$types[$k]['description'] = $this->type_settings[$v]['description'];
				} else {
					$types[$k]['title'] = '';
					$types[$k]['description'] = '';
				}
			}
			$type = $types;
		}
		return $type;
	}
	function set_type_i18n() {
		$this->type_settings = array(
			'member' => array(
				'title' => __('General', true),
				'description' => '',
			),
			'portal' => array(
				'title' => __('Portal/Search', true),
				'description' => __('Portal site or the search site for TRPG.', true),
			),
			'online' => array(
				'title' => __('Online Circle', true),
				'description' => __('Online Circle for TRPG.', true),
			),
			'offline' => array(
				'title' => __('Offline Circle', true),
				'description' => __('Offline Circle/Convention for TRPG.', true),
			),
			'tool' => array(
				'title' => __('TRPG Tools', true),
				'description' => __('Websites including the useful TRPG tools.', true),
			),
			'creator' => array(
				'title' => __('Creator/Publisher', true),
				'description' => __('Websites of TRPG creators/Publishers.', true),
			),
			'shop' => array(
				'title' => __('Shop/Playing Space', true),
				'description' => __('Shop/Playing Space of TRPG.', true),
			),
			'ring' => array(
				'title' => __('WebRing', true),
				'description' => __('Joined Webrings', true),
			),
			'thanks' => array(
				'title' => __('Thanks links', true),
				'description' => __('Thanks sites. Some site have NO relation to TRPG.',  true),
			),
		);
	}

	/* Restore */
	function restore_html_link($data, $nl2br = false, $emptyNotitle = false) {
		if (empty($data) || !is_array($data)) {
			return array();
		}

		foreach ($data as $k => $v) {
			$data[$k] = $this->_restore_html_link($v, $nl2br, $emptyNotitle);
		}

		return $data;
	}

	function _restore_html_link($data, $nl2br = false, $emptyNotitle = false) {
		if (!isset($data['Link']) || empty($data['Link'])) {
			return array();
		}

		$data['Link']['url'] = rawurldecode($data['Link']['url']);

		if (!isset($data['Link']['title']) || empty($data['Link']['title']) && !$emptyNotitle) {
			$data['Link']['title'] = __('No Title', true);
		}

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

		if (isset($data['Link']['ring'])  && !empty($data['Link']['ring'])) {
			$data['Link']['ring'] = $this->{$this->modelClass}->restore_html($data['Link']['ring'], false, false, false);
		}

		return $data;
	}

	/* 一般ユーザに許可されたtypeのみ */
	function set_members_type() {
		$types = $this->get_type();
		foreach ($types as $k => $type) {
			if ($k >= 100) {
				unset($this->Link->type[$k]);
			}
		}
	}

	/* optionsを指定してLink取得 */
	function get_link4options($options = array()) {
		$links = $this->Link->find('all', array('options' => $options));

		return $this->restore_html_link($links, true, false);
	}

}

