<?php
/**
 * データベース管理
 */
require_once 'Zend/Controller/Action.php';

class Manage_DbController extends Zend_Controller_Action
{
    private $contents;
    
    public function preDispatch()
    {
        global $Me, $currentManage, $breadcrumb;
        
        if ($Me->isAdmin() == false) {
            $this->_redirect('/Manage/Login/');
        }
        $currentManage = 'Db';
        $breadcrumb->add('管理', BASE_URL . 'Manage/');
        $breadcrumb->add('データベース', BASE_URL . 'Manage/Db/');
    }
    
    public function indexAction()
    {
        $this->backupAction();
    }
    
    /**
     * DBバックアップ(コピー)
     */
    public function backupAction()
    {
        global $db, $config;
        
        ob_start();
        
        if (DEMO) {
            echo "<strong>DEMOでは使用できません</strong><br />\n";
        }
        else {
        
            if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                $filename = h($_POST['filename']);
                copy('private/platy.db', 'private/' . $filename . '.db');
                echo 'filename=' . $filename . 'に保存しました' . "<br />\n";
                $filename = '';
            }
            else {
                $filename = 'platy_' . date('YmdHis');
            }
            
            echo '<h2>DBバックアップ</h2>' . "\n";
            echo "保存するファイル名を入力し、「保存する」ボタンを押してください。" . "<br />\n";
            echo "[!] ファイル名の拡張子は付けないでください。拡張子'db'が自動的に付きます。" . "<br />\n";
            echo '<form method="post" action="">' . "<br />\n";
            echo 'ファイル名:';
            echo '<input type="text" name="filename" value="' . $filename . '" size="60" />' . "<br />\n";
            echo '<input type="submit" value="保存する" />' . "\n";
            echo '</form>' . "\n";
        
        }
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * DBリストア
     */
    public function restoreAction()
    {
        global $db, $config;
        
        ob_start();
        
        echo '<h2>DBリストア</h2>' . "\n";
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $filename = h($_POST['filename']);
            echo $filename . "<br />\n";
            $retval = copy(BASE_PATH . 'private/'. $filename, BASE_PATH . 'private/platy.db');
            if ($retval == false) {
                echo "failed to copy $filename ...\n";
            }
        }
        else {
        }
        echo "#注意# 選択したファイルはシステムDBを上書きします<br />\n";
        
        echo '<form method="post" action="">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>filename</th><td>';
        echo '<select name="filename" size="3">' . "\n";
        
        // 拡張子(db)でplaty.db以外を探す
        $db_path = BASE_PATH . 'private/';
        $d = dir($db_path);
        while (($entry = $d->read()) != false) {
            $path_parts = pathinfo(BASE_PATH . 'private/' . $entry);
            if (!is_dir(BASE_PATH . 'private/' . $entry) && $entry != '.' && $entry != '..' 
                && $path_parts['extension'] == 'db' && $entry != 'platy.db') {
                echo $entry . "<br />\n";
                
                echo '<option value="' . $entry . '">';
                echo $entry;
                echo '</option>' . "\n";
            }
        }
        $d->close();
        
        echo '</select>' . "\n";
        echo '</td></tr>';
        echo '<tr><th></th><td>';
        echo '<input type="submit" value="リストアする" />' . "\n";
        echo '</td></tr></table>' . "\n";
        echo '</form>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * DBアップロード
     */
    public function uploadAction()
    {
        global $db, $config;
        
        ob_start();
        
        echo '<h2>DBアップロード</h2>' . "\n";
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $filename = $_POST['filename'];
            $uploaddir = BASE_PATH . 'private/';
            $uploadfile = $uploaddir . $filename . '.db';
            
            if (filename == '') {
                
            }
            else if (is_file($uploadfile)) {
                
            }
            else {
                if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
                    echo "File is valid, and was successfully uploaded.\n";
                } else {
                    echo "Possible file upload attack!\n";
                }
            }
        }
        else {
            $filename = "platy_" . date('YmdHis');
        }
        
        echo '<form method="post" action="" enctype="multipart/form-data">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>file</th><td>';
        echo '<input type="file" name="userfile" size="60" />' . "\n";
        echo '</td></tr>';
        echo '<tr><th>filename</th><td>';
        echo '<input type="text" name="filename" value="' . $filename . '" size="60" />' . "\n";
        echo '</td></tr>';
        echo '<tr><th></th><td>';
        echo '<input type="submit" />' . "\n";
        echo '</td></tr></table>' . "\n";
        echo '</form>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * DBダウンロード
     */
    public function downloadAction()
    {
        global $db, $config;
        
        ob_start();
        
        echo '<h2>DBダウンロード</h2>' . "\n";
        
        // 拡張子(db)を探す
        $db_path = BASE_PATH . 'private/';
        $d = dir($db_path);
        while (($entry = $d->read()) != false) {
            $path_parts = pathinfo(BASE_PATH . 'private/' . $entry);
            if (!is_dir(BASE_PATH . 'private/' . $entry) && $entry != '.' && $entry != '..' 
                && $path_parts['extension'] == 'db') {
                echo '<a href="' . BASE_URL . 'Manage/DB/download2/file/' . $entry . '" target="_blank">';
                echo $entry;
                echo '</a>' . "<br />\n";
            }
        }
        $d->close();
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * DBダウンロード
     */
    public function download2Action()
    {
        $request = $this->getRequest();
        $file = $request->getParam('file');
        echo $file . "<br />\n";
        $filename = BASE_PATH . 'private/' . $file;
        $this->download_file($filename);
    }
    
    /**
     * DB削除
     */
    public function deleteAction()
    {
        global $db, $config;
        
        ob_start();
        
        echo '<h2>DB削除</h2>' . "\n";
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $filename = h($_POST['filename']);
            echo $filename . "<br />\n";
            
            $retval = unlink(BASE_PATH . 'private/'. $filename);
            if ($retval == false) {
                echo "failed to delete $filename ...\n";
            }
        }
        else {
        }
        
        echo '<form method="post" action="">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>filename</th><td>';
        echo '<select name="filename" size="3">' . "\n";
        
        // 拡張子(db)を探す
        $db_path = BASE_PATH . 'private/';
        $d = dir($db_path);
        while (($entry = $d->read()) != false) {
            $path_parts = pathinfo(BASE_PATH . 'private/' . $entry);
            if (!is_dir(BASE_PATH . 'private/' . $entry) && $entry != '.' && $entry != '..' 
                && $path_parts['extension'] == 'db') {
                echo $entry . "<br />\n";
                
                echo '<option value="' . $entry . '">';
                echo $entry;
                echo '</option>' . "\n";
            }
        }
        $d->close();
        
        echo '</select>' . "\n";
        echo '</td></tr>';
        echo '<tr><th></th><td>';
        echo '<input type="submit" value="削除する" />' . "\n";
        echo '</td></tr></table>' . "\n";
        echo '</form>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    public function buildSidebar()
    {
        ob_start();
        
        echo '<div class="widget">' . "\n";
        echo '<div class="title">メニュー</div>' . "\n";
        echo '<div class="main">' . "\n";
        
        echo '<ul>' . "\n";
        echo '<li>';
        echo '<a href="' . BASE_URL . 'Manage/DB/backup/">バックアップ</a>';
        echo '</li>' . "\n";
        echo '<li>';
        echo '<a href="' . BASE_URL . 'Manage/DB/restore/">リストア</a>';
        echo '</li>' . "\n";
        echo '<li>';
        echo '<a href="' . BASE_URL . 'Manage/DB/upload/">アップロード</a>';
        echo '</li>' . "\n";
        echo '<li>';
        echo '<a href="' . BASE_URL . 'Manage/DB/download/">ダウンロード</a>';
        echo '</li>' . "\n";
        echo '<li>';
        echo '<a href="' . BASE_URL . 'Manage/DB/delete/">削除</a>';
        echo '</li>' . "\n";

        echo '</ul>' . "\n";
        echo '</div>' . "\n";
        echo '</div>' . "<!-- /widget -->\n";
        
        $sidebar = ob_get_contents();
        ob_end_clean();
        
        return $sidebar;
    }
    
    /**
     * DBファイルのダウンロード
     * http://www.spencernetwork.org/memo/tips-5.php
     */
    private function download_file($path_file)
    {
        /* ファイルの存在確認 */
        if (!file_exists($path_file)) {
            die("Error: File(".$path_file.") does not exist");
            //return -1;
        }
        
        /* オープンできるか確認 */
        if (!($fp = fopen($path_file, "r"))) {
            die("Error: Cannot open the file(".$path_file.")");
            //return -2;
        }
        fclose($fp);
        
        /* ファイルサイズの確認 */
        if (($content_length = filesize($path_file)) == 0) {
            die("Error: File size is 0.(".$path_file.")");
            //return -3;
        }
        
        /* ダウンロード用のHTTPヘッダ送信 */
        header("Content-Disposition: inline; filename=\"".basename($path_file)."\"");
        header("Content-Length: ".$content_length);
        header("Content-Type: application/octet-stream");
        
        /* ファイルを読んで出力 */
        if (!readfile($path_file)) {
            die("Cannot read the file(".$path_file.")");
            //return -4;
        }
    }
    
    public function noRouteAction()
    {
        //$this->_redirect('/');
        echo "noRouteAction";
    }
    
    /**
     * 表示
     */
    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');
    }
}
?>