<?php
/**
 * ノード管理
 */
require_once 'Zend/Controller/Action.php';

class Manage_NodeController extends Zend_Controller_Action
{
    private $contents;
    
    public function preDispatch()
    {
        global $Me, $currentManage, $breadcrumb;
        if ($Me->isAllowed('Access_Backend') == false) {
            $this->_redirect('/Manage/Login/');
        }
        $currentManage = 'Node';
        $breadcrumb->add('管理', BASE_URL . 'Manage/');
        $breadcrumb->add('ノード管理', BASE_URL . 'Manage/Node/');
    }
    
    public function indexAction()
    {
        $this->listAction();
        //$this->_redirect('/Manage/Node/list/');
    }

    public function noRouteAction()
    {
        echo "noRouteAction";
    }
    
    private function Breadcrumb($path) {
        global $db;
        //echo $path . "<br />\n";
        
        $str = substr($path, strlen($path)-1, 1);
        //echo $str;
        //if ($str == '/') { return -1; }
        
        $bc_link = '/';
        echo '<a href="' . BASE_FULL_URL . 'Manage/Node/cd/path/' . str_replace('/', '_', $bc_link) . '">';
        echo $bc_link . ':' . 'ホーム';
        echo '</a>';
        //echo "<br />\n";
        
        $id = 0;
        $a = split('/', $path);
        //var_dump($a);

        
        for ($i = 1; $i < count($a)-1; $i++) {
            $name = $a[$i];
            
            $sql = "SELECT title FROM Platy_Content_Base WHERE name='{$name}'";
            $row = $db->fetchRow($sql);
            $title = $row['title'];
            
            $bc_link .= $name . '/';
            echo '&nbsp;';
            //for ($j = 0; $j < $i; $j++) {
                echo '->';
            //}
            echo '&nbsp;';
            echo '<a href="' . BASE_FULL_URL . 'Manage/Node/cd/path/' . str_replace('/', '_', $bc_link) . '">';
            echo $bc_link . ':' . $title;
            echo '</a>';
            //echo "<br />\n";
        }
        echo "<br />\n";
    }
    
    /**
     * 現在のNode上にあるコンテンツ一覧を表示する。
     */
    public function listAction()
    {
        global $db, $Me, $session;
        
        ob_start();
        
        echo '<h2>ノード一覧</h2>' . "\n";
        
        if (!isset($session->currentNode)) {
            $session->currentNode = '/';
            $session->currentNodeId = 1;
        }
        echo 'currentNode:' . $session->currentNode;
        echo '&nbsp;&nbsp;currentNodeId:' . $session->currentNodeId . "<br />\n";
        $this->Breadcrumb($session->currentNode);
        
//        echo '<a href="cd/path/_">goto RootPath</a>' . "&nbsp;";
        
        // 一つ上のパスへのリンク
//        $a = split('/', $session->currentNode);
//        $path = '/';
//        if (count($a) > 2) {
//            for ($i = 1; $i < count($a)-2; $i++) {
//                $path .= $a[$i]  . '/';
//            }
//            $path = str_replace('/', '_', $path);
//            echo '<a href="cd/path/' . $path . '">一つ上に戻る</a>' . "\n";
//        }
//        echo "<br />\n";
        
        // フォルダ情報を得る
        // TODO
        $sql = "SELECT id, type, name, title, modified, startDate, endDate, status, owner FROM Platy_Content_Base WHERE id=" . $_SESSION[SESS_KEY]['currentNodeId'];
        $row = $db->fetchRow($sql);
        //---
        echo '<table class="list_table">' . "\n";
        echo '<th>id</th><th>type</th><th>name</th><th>title</th><th>更新日時</th><th>ステータス</th><th>所有者</th><th>公開期間</th><th>表示順</th><th>action</th>' . "\n";
        
        echo '<tr class="even">';
        echo "\n";
        
        $id = $row['id'];
        $ordering = $row['ordering'];
        
        $name = $row['name'];
        $type = $row['type'];
        $title = $row['title'];
        $modified = $row['modified'];
        $startDate = $row['startDate'];
        $endDate = $row['endDate'];
        $status = $row['status'];
        $owner = $row['owner'];
        $owner_name = Platy_Util::getUsername($row['owner']);
        $period = checkPeriod($startDate, $endDate);
        
        echo '<td>' . $id;
        echo '</td>';
        
        echo '<td>';
        echo '<img src="' . BASE_URL . 'media/system/' . $type . '.png' . '">';
        echo $type;
        echo '</td>';
        echo '<td>';
        if ($type == 'Folder') {
            // cd のパスは、/ を _ に変換する
            $path = $session->currentNode . $name . '/';
            $path = str_replace('/', '_', $path);
            
            //echo '<a href="cd/path/' . $path . '">';
            echo $name;
            //echo '</a>';
            echo "<br />\n";
        }
        else {
            echo $name;
        }
        echo '</td>';
        echo '<td>' . $title . '</td>';
        echo '<td>' . $modified . '</td>';
        
        echo '<td>';
        //echo $status;
        switch ($status) {
        case 'public':
            echo '公開';
            break;
        case 'pending':
            echo '保留';
            break;
        case 'private':
            echo '下書き';
            break;
        }
        echo '</td>';
        echo '<td>' . $owner_name . '</td>';
        
        echo '<td>';
        if ($period == true) { echo '<img src="' . BASE_URL . 'media/system/agt_action_success.png">'; } 
        else { echo '<img src="' . BASE_URL . 'media/system/agt_action_fail.png">'; }
        echo $startDate . "<br />" . $endDate;
        echo '</td>';
        echo '<td>' . $ordering . '</td>';
        echo '<td class="">';
        
        // 閲覧ができるかをチェックする
        $allow_browse = false;
        if ($Me->isAllowed('Manage_Contents') == true) {
            $allow_browse = true;
        }
        else if ($Me->isAllowed('Approve_Contents') && ($status == 'public' || $status == 'pending')) {
            $allow_browse = true;
        }
        else if ($Me->id == $owner) {
            $allow_browse = true;
        }
        
        if ($allow_browse == true) {
            echo '<a href="browse/id/' . $id . '">';
            echo '<img src="' . BASE_URL . 'media/system/kdvi.png" alt="browse">' . '閲覧';
            echo '</a>';
        }
        else {
            echo '<img src="' . BASE_URL . 'media/system/kdvi.png" alt="browse">' . '閲覧';
        }
        
        echo '&nbsp;';
        
        // 編集ができるかをチェックする
        $allow_edit = false;
        if ($Me->isAllowed('Manage_Contents') == true) {
            $allow_edit = true;
        }
        else if ($Me->isAllowed('Approve_Contents') && ($status == 'public' || $status == 'pending')) {
            $allow_edit = true;
        }
        else if ($Me->id == $owner && $status == 'private') {
            $allow_edit = true;
        }
        if ($allow_edit == true) {
            echo '<a href="edit/id/' . $id . '">';
            echo '<img src="' . BASE_URL . 'media/system/edit.png" alt="edit">' . '編集';
            echo '</a>';
        }
        else {
            echo '<img src="' . BASE_URL . 'media/system/edit.png" alt="edit">' . '編集';
        }
        
        echo '&nbsp;';
        
        // 削除ができるかをチェックする
        $allow_delete = false;
        if ($Me->isAllowed('Manage_Contents') == true) {
            $allow_delete = true;
        }
        else if ($Me->id == $owner && $status == 'private') {
            $allow_delete = true;
        }
        if ($allow_delete == true) {
            echo '<a href="delete/id/' . $id . '">';
            echo '<img src="' . BASE_URL . 'media/system/14_layer_deletelayer.png" alt="delete">' . '削除';
            echo '</a>';
        }
        else {
            echo '<img src="' . BASE_URL . 'media/system/14_layer_deletelayer.png" alt="delete">' . '削除';
        }
        echo '</td>';
        echo '</table>'. "\n";
        echo "<br />\n";
        
        echo '<h3>' . $name . 'フォルダ内のコンテンツ一覧</h3>' . "\n";
        
        // コンテンツの登録
        if ($Me->isAllowed('Manage_Contents') || $Me->isAllowed('Create_Contents')) {
            $sql = "SELECT id, name FROM Platy_ContentType";
            $rows = $db->fetchAll($sql);
            
            echo '<form method="post" action="add/">' . "\n";
            echo '<select name="ContentType">' . "\n";
            for ($i = 0; $i < count($rows); $i++) {
                echo '<option value="' . $rows[$i]['name'] . '">' . $rows[$i]['name'] . '</option>' . "\n";
            }
            echo '</select>' . "\n";
            echo '<input type="submit" value="コンテンツを登録する" />' . "\n";
            echo '</form>' . "\n";
        }
        else {
            echo "権限がないのでコンテンツの登録はできません<br />\n";
        }
        
        // フォルダ内のコンテンツ一覧を得る
        try {
            $sql = "SELECT id, ordering FROM Platy_Content_Node WHERE parentId=" . $session->currentNodeId . " ORDER BY ordering";
        }
        catch (Exception $e) {
            $profiler = $db->getProfiler();
            $query = $profiler->getLastQueryProfile();
            echo $query->getQuery();
            echo $e->getMessage();
        }
        $rows = $db->fetchAll($sql);
        
        echo '<form method="post" action="' . BASE_URL . 'Manage/Node/clipboard">' . "\n";
        echo '<table class="list_table">' . "\n";
        echo '<th>id</th><th>type</th><th>name</th><th>title</th><th>更新日時</th><th>ステータス</th><th>所有者</th><th>公開期間</th><th>表示順</th><th>action</th>' . "\n";
        for ($i = 0; $i < count($rows); $i++) {
            $row = $rows[$i];
            if ($i % 2 == 0) { echo '<tr class="even">'; }
            else { echo '<tr class="odd">'; }
            echo "\n";
            
            echo '<td>';
            echo '<input type="checkbox" name="vid[]" value="' . $row['id'] . '" />' . "\n";
            echo $rows[$i]['id'];
            echo '</td>';
            
            $id = $row['id'];
            $ordering = $row['ordering'];
            
            $sql2 = "SELECT id, type, name, title, modified, startDate, endDate, status, owner FROM Platy_Content_Base WHERE id={$id}";
            //echo $sql2 . "<br />\n";
            try {
                $row2 = $db->fetchRow($sql2);
            }
            catch (Exception $e) {
                var_dump($row);
                echo $sql2;
                $profiler = $db->getProfiler();
                $query = $profiler->getLastQueryProfile();
                echo $query->getQuery();
                echo $e->getMessage();
            }

            $name = $row2['name'];
            $type = $row2['type'];
            $title = $row2['title'];
            $modified = $row2['modified'];
            $startDate = $row2['startDate'];
            $endDate = $row2['endDate'];
            $status = $row2['status'];
            $owner = $row2['owner'];
            $owner_name = Platy_Util::getUsername($row2['owner']);
            $period = checkPeriod($startDate, $endDate);
            
            echo '<td>';
            echo '<img src="' . BASE_URL . 'media/system/' . $type . '.png' . '">';
            echo $type;
            echo '</td>';
            echo '<td>';
            if ($type == 'Folder') {
                // cd のパスは、/ を _ に変換する
                $path = $session->currentNode . $name . '/';
                $path = str_replace('/', '_', $path);
                //$path = substr($path, 5); #0.6.0
                echo '<a href="cd/path/' . $path . '">';
                echo $name;
                echo '</a>';
                echo "<br />\n";
            }
            else {
                echo $name;
            }
            echo '</td>';
            echo '<td>' . $title . '</td>';
            echo '<td>' . $modified . '</td>';
            
            echo '<td>';
            //echo $status;
            switch ($status) {
            case 'public':
                echo '公開';
                break;
            case 'pending':
                echo '保留';
                break;
            case 'private':
                echo '下書き';
                break;
            }
            echo '</td>';
            echo '<td>' . $owner_name . '</td>';
            
            echo '<td>';
            if ($period == true) { echo '<img src="' . BASE_URL . 'media/system/agt_action_success.png">'; } 
            else { echo '<img src="' . BASE_URL . 'media/system/agt_action_fail.png">'; }
            echo $startDate . "<br />" . $endDate;
            echo '</td>';
            echo '<td>' . $ordering . '</td>';
            echo '<td class="">';
            
            // 閲覧ができるかをチェックする
            $allow_browse = false;
            if ($Me->isAllowed('Manage_Contents') == true) {
                $allow_browse = true;
            }
            else if ($Me->isAllowed('Approve_Contents') && ($status == 'public' || $status == 'pending')) {
                $allow_browse = true;
            }
            else if ($Me->id == $owner) {
                $allow_browse = true;
            }
            
            if ($allow_browse == true) {
                echo '<a href="browse/id/' . $id . '">';
                echo '<img src="' . BASE_URL . 'media/system/kdvi.png" alt="browse">' . '閲覧';
                echo '</a>';
            }
            else {
                echo '<img src="' . BASE_URL . 'media/system/kdvi.png" alt="browse">' . '閲覧';
            }
            
            echo '&nbsp;';
            
            // 編集ができるかをチェックする
            $allow_edit = false;
            if ($Me->isAllowed('Manage_Contents') == true) {
                $allow_edit = true;
            }
            else if ($Me->isAllowed('Approve_Contents') && ($status == 'public' || $status == 'pending')) {
                $allow_edit = true;
            }
            else if ($Me->id == $owner && $status == 'private') {
                $allow_edit = true;
            }
            if ($allow_edit == true) {
                echo '<a href="edit/id/' . $id . '">';
                echo '<img src="' . BASE_URL . 'media/system/edit.png" alt="edit">' . '編集';
                echo '</a>';
            }
            else {
                echo '<img src="' . BASE_URL . 'media/system/edit.png" alt="edit">' . '編集';
            }
            
            echo '&nbsp;';
            
            // 削除ができるかをチェックする
            $allow_delete = false;
            if ($Me->isAllowed('Manage_Contents') == true) {
                $allow_delete = true;
            }
            else if ($Me->id == $owner && $status == 'private') {
                $allow_delete = true;
            }
            if ($allow_delete == true) {
                echo '<a href="delete/id/' . $id . '">';
                echo '<img src="' . BASE_URL . 'media/system/14_layer_deletelayer.png" alt="delete">' . '削除';
                echo '</a>';
            }
            else {
                echo '<img src="' . BASE_URL . 'media/system/14_layer_deletelayer.png" alt="delete">' . '削除';
            }
            
            echo '&nbsp;';
            if ($type == 'Folder') {
                $path = $session->currentNode . $name . '/';
                $path = str_replace('/', '_', $path);
                //$path = substr($path, 5); #0.6.0
                echo '<a href="cd/path/' . $path . '">';
                echo '<img src="' . BASE_URL . 'media/system/action_forward.png" alt="delete">' . '移動';
                echo '</a>';
            }
            
            echo '</td>';
        }
        echo '</table>'. "\n";
        echo '<input type="submit" name="op" value="cut" />' . "\n";
        echo '<input type="submit" name="op" value="paste" />' . "\n";
        echo '</form>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * コンテンツの追加
     */
    public function addAction()
    {
        global $db, $currentContent, $manager, $Me, $session;
        
        if (($Me->isAllowed('Manage_Contents') == false) && ($Me->isAllowed('Create_Contents') == false)) {
            die();
        }
        
        ob_start();
        
        //echo 'Manage_NodeController:addAction()' . "<br />\n";
        //var_dump($_REQUEST);
        $ContentType = $_REQUEST['ContentType'];
        //var_dump($ContentType);
        require(APP_PATH . 'models/CType/' . $ContentType . '.php');
        $classname = 'Platy_CType_' . $ContentType;
        $obj = new $classname();
        
        if (isset($_POST['submit_content'])) {
            if ($obj->saveAdd($session->currentNodeId) == true) {
                $currentContent['id'] = $obj->id;
                $currentContent['type'] = $obj->type;
                $manager->raiseEvent('PostEditContent');

                $this->_redirect('/Manage/Node/');
            }
        }
        else {
            $obj->add();
        }
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * コンテンツの編集
     */
    public function editAction()
    {
        global $db, $currentContent, $manager;
        
        ob_start();
        
        $request = $this->getRequest();
        $id = $request->getParam('id');
        
        $sql = "SELECT type FROM Platy_Content_Base WHERE id={$id}";
        $row = $db->fetchRow($sql);
        //var_dump($row);
        
        $type = $row['type'];
        
        $currentContent['id'] = $id;
        $currentContent['type'] = $type;
        
        require(APP_PATH . 'models/CType/' . $type . '.php');
        $classname = 'Platy_CType_' . $type;
        $obj = new $classname($id);
        
        if (isset($_POST['submit_content'])) {
            if ($obj->saveEdit($NodeId) == true) {
                $manager->raiseEvent('PostEditContent');
                
                $this->_redirect('/Manage/Node/');
            }
        }
        else {
            $obj->edit($id);
            $sql = "SELECT ordering FROM Platy_Content_Node WHERE id={$obj->id}";
            $row = $db->fetchRow($sql);
            if ($row != false) {
                $ordering = $row['ordering'];
            }
        }
        
        echo '<form method="post" action="' . BASE_URL . 'Manage/Node/ordering/' . '">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>表示順:</th><td>';
        echo '<input type="text" name="ordering" value="' . $ordering . '" size="4" />';
        echo '<input type="hidden" name="id" value="' . $id . '" />' . "\n";
        echo '<input type="submit" value="更新する" />' . "\n";
        echo '</td></tr></table>';
        echo '</form>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * コンテンツの削除
     */
    public function deleteAction()
    {
        global $db;
        
        ob_start();
        
        $db->beginTransaction();
        
        try {
            //id/id
            $request = $this->getRequest();
            $id = $request->getParam('id');
            
            // 各コンテンツタイプの拡張データの削除
            
            $sql = "SELECT type FROM Platy_Content_Base WHERE id={$id}";
            $row = $db->fetchRow($sql);
            
            require_once(APP_PATH . 'models/CType/' . $row['type'] . '.php');
            $classname = 'Platy_CType_' . $row['type'];
            $obj = new $classname($id);
            
            if ($obj->delete() == true) {
                $sql = "DELETE FROM Platy_Content_Node WHERE id={$id}";
                echo $sql;
                $db->query($sql);
                $sql = "DELETE FROM Platy_Content_Base WHERE id={$id}";
                echo $sql;
                $db->query($sql);
            }
            
            $db->commit();
            
            $this->_redirect('/Manage/Node/');
        }
        catch (Exception $e) {
            $db->rollBack();
            echo $e->getMessage();
        }
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * 閲覧
     */
    public function browseAction()
    {
        global $db, $currentContent, $manager;
        
        ob_start();
        
        $request = $this->getRequest();
        $id = $request->getParam('id');
        
        $sql = "SELECT type FROM Platy_Content_Base WHERE id={$id}";
        $row = $db->fetchRow($sql);
        //var_dump($row);
        
        $type = $row['type'];
        
        $currentContent['id'] = $id;
        $currentContent['type'] = $type;
        
        require(APP_PATH . 'models/CType/' . $type . '.php');
        $classname = 'Platy_CType_' . $type;
        $obj = new $classname($id);
        
        $obj->browse($id);
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * カレントフォルダの変更
     */
    public function cdAction()
    {
        global $session;
        
        $request = $this->getRequest();
        $path = $request->getParam('path');
        //echo $path . "<br />\n";
        $path = str_replace('_', '/', $path);
        //echo $path . "<br />\n";
        
        // $session->currentNode, $session->currentNodeId を再設定する
        // TODO
        $retval = getFolderIdFromPath($path);
        //echo $retval . "<br />\n";
        
        //echo "currentNode:" . $session->currentNode . "<br />\n";
        //echo "currentNodeId:" . $session->currentNodeId . "<br />\n";
        
        // ->listAction()
        // TODO
        $this->_redirect('/Manage/Node/');
    }
    
    /**
     * clipboard
     */
    public function clipboardAction()
    {
        global $db, $currentNodeId, $session;
        
        $op = h($_POST['op']);
        switch ($op) {
        case 'cut':
            $id_list = $_POST['id'];
            //var_dump($vid_list);
            $session->clipboard = $id_list;
            break;
        case 'paste':
            $currentNodeId = $session->currentNodeId;
            $id_list = $session->clipboard;
            for ($i = 0; $i < count($id_list); $i++) {
                $sql = "UPDATE Platy_Content_Node SET parentId={$currentNodeId} WHERE id={$id_list[$i]}";
                $db->query($sql);
            }
            break;
        default:
            break;
        }
        $this->listAction();
        
        var_dump($session->clipboard);
        echo $currentNodeId;
    }
    
    /**
     * フォルダ内の表示順番の変更
     */
    public function orderingAction()
    {
        global $db;
        $id = intval($_POST['id']);
        $ordering = intval($_POST['ordering']);
        $sql = "UPDATE Platy_Content_Node SET ordering={$ordering} WHERE id={$id}";
        $db->query($sql);
        $this->_redirect('/Manage/Node/');
    }
    
    /**
     * Dump (デバッグ用)
     */
    public function dumpAction()
    {
        global $db;
        
        ob_start();
        
        echo '<h3>Dump Contents (for debug)</h3>' . "\n";
        $sql = "SELECT n.id, n.parentId, b.name, b.title FROM Platy_Content_Base b, Platy_Content_Node n WHERE b.id=n.id";
        $rows = $db->fetchAll($sql);
        echo "Platy_Content_Node + Base(n.id=b.id)<br />\n";
        echo '<table class="list_table">' . "\n";
        foreach ($rows as $row) {
            echo '<tr>';
            echo '<td>' . $row['id'] . '</td>';
            echo '<td>' . $row['parentId'] . '</td>';
            echo '<td>' . $row['name'] . '</td>';
            echo '<td>' . $row['title'] . '</td>';
            echo '</tr>' . "\n";
        }
        echo '</table>' . "\n";
        
        $sql = "SELECT id, type, name, title FROM Platy_Content_Base";
        $rows = $db->fetchAll($sql);
        echo "Platy_Content_Base<br />\n";
        echo '<table class="list_table">' . "\n";
        echo '<th>id</th><th>type</th><th>name</th><th>title</th>' . "\n";
        foreach ($rows as $row) {
            echo '<tr>';
            echo '<td>' . $row['id'] . '</td>';
            echo '<td>' . $row['type'] . '</td>';
            echo '<td>' . $row['name'] . '</td>';
            echo '<td>' . $row['title'] . '</td>';
            echo '</tr>' . "\n";
        }
        echo '</table>' . "\n";
        
        $sql = "SELECT id, parentId, ordering FROM Platy_Content_Node";
        $rows = $db->fetchAll($sql);
        echo "Platy_Content_Node<br />\n";
        echo '<table class="list_table">' . "\n";
        echo '<th>id</th><th>parentId</th><th>ordering</th>' . "\n";
        foreach ($rows as $row) {
            echo '<tr>';
            echo '<td>' . $row['id'] . '</td>';
            echo '<td>' . $row['parentId'] . '</td>';
            echo '<td>' . $row['ordering'] . '</td>';
            echo '</tr>' . "\n";
        }
        echo '</table>' . "<br />\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    public function buildSidebar()
    {
        ob_start();
        
        include(APP_PATH . 'Manage/models/Widget/PendingContent.php');
        $widget = new Platy_Widget_PendingContent();
        $widget->show();
        
        include(APP_PATH . 'Manage/models/Widget/ManageNodeNav.php');
        $widget = new Platy_Widget_ManageNodeNav();
        $widget->show();
        
        $sidebar = ob_get_contents();
        ob_end_clean();
        
        return $sidebar;
    }
    
    /**
     * 表示
     */
    private function view()
    {
        global $breadcrumb;
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'Manage/views');
        $view->contents = $this->contents;
        $view->breadcrumb = $breadcrumb->getContents();
        $view->sidebar = $this->buildSidebar();
        echo $view->render('page.php');
    }
}
?>