<?php
/* SVN FILE: $Id: plugin.php 588 2008-06-21 16:48:32Z bb_yujiro $ */
/**
 * 構築タイプの選択
 *
 * PHP versions 5
 *
 *      hitSuji : Social Network Service <http://rakuto.net/rktSNS/>
 *      Copyright (c) 2007 Yujiro Takahashi
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @package         hitSuji
 * @version         $Revision: 588 $
 * @modifiedby      $LastChangedBy: bb_yujiro $
 * @lastmodified    $Date: 2008-06-22 01:48:32 +0900 (日, 22 6 2008) $
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */
 
/**
 * Controllerクラス
 *
 * @category        hitSuji developer
 * @package         hitSuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision: 588 $
 * @modifiedby      $LastChangedBy: bb_yujiro $
 * @lastmodified    $Date: 2008-06-22 01:48:32 +0900 (日, 22 6 2008) $
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */
class Controller extends RKT_Controller
{
    /**
     * アカウント情報
     * @var array
     */
    protected $account = array('status'=> STATUS_GUEST);

    /**
     * ベンダー
     * @var string
     */
    protected $vendor = null;
    /**
     * 選択済みパッケージ
     * @var string
     */
    protected $package = null;
    /**
     * キー
     * @var string
     */
    protected $key = null;
    /**
     * なまえ
     * @var string
     */
    protected $name = null;
    /**
     * チャンネル
     * @var string
     */
    protected $channel = null;
    /**
     * サマリー
     * @var string
     */
    protected $summary = null;
    /**
     * 説明
     * @var string
     */
    protected $description = null;
    /**
     * 日付
     * @var string
     */
    protected $date = null;
    /**
     * リンク
     * @var string
     */
    protected $link = null;
    /**
     * アイコン
     * @var string
     */
    protected $icon = null;
    /**
     * 作者
     * @var string
     */
    protected $author = null;
    /**
     * バージョン
     * @var string
     */
    protected $version = null;
    /**
     * ライセンス
     * @var string
     */
    protected $license = null;
    /**
     * ライセンスURI
     * @var string
     */
    protected $license_uri = null;

    /**
     * パッケージリスト
     * @var array
     */
    private $_packages = array();

    /**
     * 変数の初期化
     *
     * @abstract
     * @access protected
     * @return void
     */
    protected function initValue()
    {
        $this->objvew->setBaseFile('common/frame/xml.tpl');
    }

    /**
     * 実行処理
     *
     * @access public
     * @return void
     **/
    protected function action()
    {
        $complete = false;
        if ($this->objrqt->getValidate() && !empty($_POST['manip'])){
            $this->_manipPlugin();
            $complete = true;
        }
        $this->objvew->assign('complete', $complete);

        if (empty($_POST['manip'])){
            $this->_readPackages();
        } else {
            $this->objvew->assign('alert', $this->objrqt->getAlerts());
        }
    }

    /**
     * 入力条件の設定
     *
     * @access protected
     * @return string   絞込み句
     **/
    protected function setCondition()
    {
        $this->conditions = array (
            'vendor'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> true,
                'input'=>    RKT_Model::INPUT_CHATCH,
            ),
            'package'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> false
            ),
            'key'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> true,
                'input'=>    RKT_Model::INPUT_CHATCH,
            ),
            'name'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> true,
                'input'=>    RKT_Model::INPUT_CHATCH,
            ),
            'channel'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> true,
                'input'=>    RKT_Model::INPUT_CHATCH,
            ),
            'summary'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> true,
                'input'=>    RKT_Model::INPUT_CHATCH,
            ),
            'description'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> true,
                'effect'=>   array('RKT_Request', 'htmlBody'),
                'input'=>    RKT_Model::INPUT_CHATCH,
            ),
            'date'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> true,
                'input'=>    RKT_Model::INPUT_CHATCH,
            ),
            'link'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> false
            ),
            'icon'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> false
            ),
            'author'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> true,
                'effect'=>   array('RKT_Request', 'htmlBody'),
                'input'=>    RKT_Model::INPUT_CHATCH,
            ),
            'version'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> false
            ),
            'license'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> false
            ),
            'license_uri'=> array(
                'type'=>     'string',
                'option'=>   array(),
                'required'=> false
            ),
        );
    }

    /**
     * テンプレート解析結果の取得
     *
     * @access privat
     * @param string $template
     * @return string
     */
    private function _getParsed($template)
    {
        ob_start();
        include VIEW_DIR.'admin'.DS.'developer'.DS.$template;
        $buffer = ob_get_contents();
        ob_end_clean();

        return $buffer;
    }

    /**
     * 連続削除処理
     *
     * @access private
     * @param string $path
     * @param integer $mode
     * @return boolean
     */
    private function _mkdirP($path, $mode=0755)
    {
        $dir    = dirname($path);
        $result = true;
        if (!file_exists($dir)){
            $result = mkdir($dir, $mode, true);
        }
        return $result;
    }

    /**
     * パッケージ読み込み
     *
     * @access private
     * @return void
     */
    private function _readPackages()
    {
        $default = array();
        foreach ($this->conditions as $key=>$row){
            $default[$key] = '';
        }
        if (empty($this->vendor)){
            $this->objvew->assign('default', $default);
            return ;
        }
        $filename = PLUGIN_DIR.$this->vendor.DS.'packages.php';
        if (!file_exists($filename)){
            $this->objvew->assign('default', $default);
            return ;
        }
        include $filename;

        $packages = array();
        foreach ($GLOBALS['INFO_PLUGIN'] as $row){
            $packages[$row['key']] = $row['name'];
        }
        $this->objvew->assign('packages', $packages);

        /* パッケージ指定 */
        if (empty($this->package)){
            $this->objvew->assign('default', $default);
            return ;
        }
        if (empty($GLOBALS['INFO_PLUGIN'][$this->package])){
            $this->objvew->assign('default', $default);
            return ;
        }
        foreach ($GLOBALS['INFO_PLUGIN'][$this->package] as $key=>$value){
            $default[$key] = $value;
        }
        $this->objvew->assign('default', $default);
    }

    /************************************************************/
    /**
     * Modelの作成実行
     *
     * @access private
     * @return void
     */
    private function _manipPlugin()
    {
        $package  = substr($this->key, strpos($this->key, '_') + 1);
        $filename = PLUGIN_DIR.$this->vendor.DS.$package.DS.'plugin.php';
        if (!file_exists($filename)){
            $buff = file_get_contents(VIEW_DIR.'admin'.DS.'developer'.DS.'_rkt_plugin.tpl');
            $buff = str_replace('{$plugin_key}', $this->key, $buff);
            
            $this->_mkdirP($filename);
            file_put_contents($filename, $buff);
        }

        $filename = PLUGIN_DIR.$this->vendor.DS.'packages.php';
        /* 既存パッケージ定義の読み込み */
        if (file_exists($filename)){
            include $filename;
            foreach ($GLOBALS['INFO_PLUGIN'] as $row){
                $this->_packages[$row['key']] = $row;
            }
        }
        
        $this->_packages[$this->key] = array(
            'key'=>         $this->key,
            'plugin'=>      str_replace('_', '/', $this->key).'/plugin.php',
            'name'=>        addslashes($this->name),
            'channel'=>     $this->channel,
            'summary'=>     addslashes($this->summary),
            'description'=> addslashes($this->description),
            'date'=>        $this->date,
            'link'=>        $this->link,
            'icon'=>        $this->icon,
            'author'=>      addslashes($this->author),
            'version'=>     addslashes($this->version),
            'license'=>     addslashes($this->license),
            'license_uri'=> $this->license_uri,
        );


        if (file_exists($filename)){
            $this->_updatePlugin($filename);
        } else {
            $this->_createPlugin($filename);
        }
    }

    /**
     * 新規ManipModelの作成
     *
     * @access private
     * @param string $filename
     * @return boolean
     */
    private function _createPlugin($filename)
    {
        $buff  = "<?php\r\n";
        $buff .= $this->_getParsed('_headerPlugin.tpl');
        $buff .= $this->_getParsed('_plugin.tpl');
        $buff .= "/* <<<<<end */\r\n";
        $buff .= "?>\r\n";

        /* ファイルの中身を取得 */
        return file_put_contents($filename, $buff);
    }

    /**
     * ManipModelの更新
     *
     * @access private
     * @param string $filename
     * @return boolean
     */
    private function _updatePlugin($filename)
    {
        $anchor = array(
            'start>>>>>',
            '<<<<<end',
            '<<<<<*>>>>>'
        );

        /* ファイルの中身を取得 */
        $handle = fopen($filename, 'r');
        if (!is_resource($handle)) {
            return false;
        }

        $buff = array('', '', '');
        $pos = 0;
        while (!feof($handle)) {
            $line  = fgets($handle, 4096);
            $match = strpos($line, $anchor[$pos]);
            if ($match !== false){
                $pos++;
            }            
            $buff[$pos] .= $line;
        }
        fclose($handle);
        $buff[1] = $this->_getParsed('_plugin.tpl');

        /* ファイルの中身を取得 */
        return file_put_contents($filename, $buff[0].$buff[1].$buff[2]);
    }
} // class Controller