<?php
/**
 * Platy CMS
 */
require_once 'Zend/Db.php';
require_once 'Zend/Db/Table.php';
require_once 'Zend/Log.php';
require_once 'Zend/Log/Writer/Stream.php';
require_once 'Zend/Cache.php';
require_once 'Platy/Member.php';
require_once 'Platy/Manager.php';
require_once 'Platy/JSHelper.php';
require_once 'Platy/CSSHelper.php';

mb_language('Japanese');            // E-Mailエンコーディング ISO-2022-JP/Base64
mb_internal_encoding('UTF-8');      // 内部エンコーディング

$params = array ('dbname' =>  BASE_PATH . 'private/' . 'platy.db');
$db = Zend_Db::factory('PDO_SQLITE', $params);
//$db = Zend_Db::factory('pdoSqlite', $params);
Zend_Db_Table_Abstract::setDefaultAdapter($db);

// プロファイラを有効にします
$db->getProfiler()->setEnabled(true);

// パンくずリスト
require_once 'Platy/breadcrumb.php';
$breadcrumb = new Platy_Breadcrumb();

try {
    // config読込
    $sql = "SELECT name, value FROM Platy_Config";
    $rows = $db->fetchAll($sql);
    for ($i = 0; $i < count($rows); $i++) {
        $config[$rows[$i]['name']] = $rows[$i]['value'];
    }
}
catch (Exception $e) {
}

/**
 * セッションに保存するインスタンスのクラスは、セッション開始までにincludeしておく
 * TODO
 */
require_once(APP_PATH . 'models/ShopCart.php');

/* セッション開始 */
session_start();
if (!isset($_SESSION[SESS_KEY]['Me'])) {
    $_SESSION[SESS_KEY]['Me'] = new Platy_Member();
    $_SESSION[SESS_KEY]['ShopCart'] = new Shop_Cart();
}
$Me = $_SESSION[SESS_KEY]['Me'];
$MyCart = $_SESSION[SESS_KEY]['ShopCart'];

$manager =& Platy_Manager::getInstance();

// logger
$writer = new Zend_Log_Writer_Stream(BASE_PATH . 'private/platy.log');
$logger = new Zend_Log($writer);

// cache
$frontendOptions = array('lifetime' => 7200, 'automatic_serialization' => true);
$backendOptions = array('cache_dir' => BASE_PATH . 'private/cache/');
$cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);

// helper
$js_helper = new JSHelper();
$css_helper = new CSSHelper();

// Global Functions >>>>>
/**
 * htmlspacialchars()のショートカット
 */
function h($s) {
    return htmlspecialchars($s);
}

/**
 * パス名からフォルダのノードIdを得る
 * @param string $path パス名
 * @param bool $sess セッションの更新 (true:する, false:しない)
 * @param bool $bc パンくずリスト作成 (true:する,false:しない)
 * @param array $folder_param フォルダ設定 *output*
 * @return int フォルダのノードId, エラー時は負数を返す
 */
function getFolderIdFromPath($path, $sess = true, $bc = false, &$folder_param = null)
{
    global $db, $breadcrumb;
    
    $ipath = '/root' . $path;
    
    $param = array('menuSetId' => 1, 'sidebarSetId' => 1, 'view_mode' => 'summary', 'ordering_mode' => 'ordering');
    
    $str = substr($ipath, strlen($ipath)-1, 1);
    if ($str != '/') { return -1; }
    
    $nodeId = 0;
    $a = split('/', $ipath);
    if (count($a) <= 2) {
        if ($sess == true) {
            $_SESSION[SESS_KEY]['currentNode'] = '/';
            $_SESSION[SESS_KEY]['currentNodeId'] = 1;
        }
        $nodeId = 0;
        if ($bc == true) {
            $breadcrumb->add('ホーム', BASE_URL);
        }
    }
    else {
        if ($bc == true) {
            $breadcrumb->add('ホーム', BASE_URL);
        }
        $bc_link = BASE_URL;
        for ($i = 1; $i < count($a)-1; $i++) {
            $name = $a[$i];
            //echo $name . "<br />\n";
            //$sql = "SELECT n.id, b.type, b.name, b.title, n.parentId "
            //     . "FROM Platy_Content_Base b, Platy_Content_Node n "
            //     . "WHERE b.id=n.id AND b.type='Folder' AND n.parentId={$nodeId} AND b.name='{$name}' ";
            $sql = "SELECT n.id, b.type, b.name, b.title, n.parentId, f.menuSetId, f.sidebarSetId, f.view_mode, f.ordering_mode "
                 . "FROM Platy_Content_Base b, Platy_Content_Node n, Platy_Content_Folder f "
                 . "WHERE b.id=n.id AND n.id=f.id AND b.type='Folder' AND n.parentId={$nodeId} AND b.name='{$name}' ";
            //echo $sql . "<br />\n";
            $row = $db->fetchRow($sql);
            //var_dump($row);
            
            $nodeId = $row['id'];
            $title = $row['title'];
            
            if ($row['menuSetId']) { $param['menuSetId'] = $row['menuSetId']; }
            if ($row['sidebarSetId']) { $param['sidebarSetId'] = $row['sidebarSetId']; }
            if ($row['view_mode'] != '') { $param['view_mode'] = $row['view_mode']; }
            if ($row['ordering_mode'] != '') { $param['ordering_mode'] = $row['ordering_mode']; }
            
            if ($bc == true) {
                if ($row['name'] == 'root' && $row['parentId'] == 0) {
                }
                else {
                    $bc_link .= $name . '/';
                    if ($i < count($a) - 2) {
                        $breadcrumb->add($title, $bc_link);
                    }
                    else {
                        // 現在の場所は名前のみ表示し、リンクしない
                        $breadcrumb->add($title, '');
                    }
                }
            }
        }
        if ($sess == true) {
            // セッション変数の更新はManage/Nodeから行われる(Frontからは実行されない)
            $_SESSION[SESS_KEY]['currentNode'] = $path;
            $_SESSION[SESS_KEY]['currentNodeId'] = $nodeId;
        }
    }
    //var_dump($param);
    if (!is_null($folder_param)) {
        $folder_param = $param;
    }
    return $nodeId;
}

/**
 * パス名からコンテントIdを得る
 * @param string $path パス名
 * @param bool $bc パンくずリスト作成 (true:する,false:しない)
 * @param array $folder_param フォルダ設定
 * @return array(id, type, name) エラー時は負数を返す
 */
function getContentFromPath($path, $bc = false, &$folder_param = null)
{
    global $db, $breadcrumb;
    $bc_link = BASE_URL;
    //echo "getContentIdFromPath:path=" . $path . "<br />\n";
    $path = '/root' . $path; // #0.6.0
    
    $param = array('menuSetId' => 1, 'sidebarSetId' => 1, 'view_mode' => 'summary', 'ordering_mode' => 'ordering');
    
    $str = substr($path, strlen($path)-1, 1);
    if ($str == '/') { return -1; }
    
    $id = 0;
    $a = split('/', $path);
    //var_dump($a);

    
    if ($bc == true) {
        $breadcrumb->add('ホーム', $bc_link);
    }
    
    for ($i = 1; $i < count($a)-1; $i++) {
        $name = $a[$i];
        //echo $name . "<br />\n";
        //$sql = "SELECT b.id, b.type, b.name, b.title, n.parentId "
        //     . "FROM Platy_Content_Node n, Platy_Content_Base b "
        //     . "WHERE n.id=b.id AND b.type='Folder' AND n.parentId={$id} AND b.name='{$name}'";
        $sql = "SELECT n.id, b.type, b.name, b.title, n.parentId, f.menuSetId, f.sidebarSetId, f.view_mode, f.ordering_mode "
             . "FROM Platy_Content_Base b, Platy_Content_Node n, Platy_Content_Folder f "
             . "WHERE b.id=n.id AND n.id=f.id AND b.type='Folder' AND n.parentId={$id} AND b.name='{$name}' ";
        //echo $sql . "<br />\n";
        $row = $db->fetchRow($sql);
        if ($row == false) {
            return -2;
        }
        
        $id = $row['id'];
        $title = $row['title'];
        
        if ($row['menuSetId']) { $param['menuSetId'] = $row['menuSetId']; }
        if ($row['sidebarSetId']) { $param['sidebarSetId'] = $row['sidebarSetId']; }
        if ($row['view_mode'] != '') { $param['view_mode'] = $row['view_mode']; }
        if ($row['ordering_mode'] != '') { $param['ordering_mode'] = $row['ordering_mode']; }
        
        if ($bc == true) {
            if ($row['name'] == 'root' && $row['parentId'] == 0) {
            }
            else {
                $bc_link .= $name . '/';
                $breadcrumb->add($title, $bc_link);
            }
        }
    }
    
    $name = $a[$i];
    //echo "name=" . $name . "<br />\n";

    $sql = "SELECT b.id, b.name, b.type, b.title "
         . "FROM Platy_Content_Node n, Platy_Content_Base b "
         . "WHERE n.id=b.id AND n.parentId={$id} AND b.name='{$name}'";
    //echo $sql . "<br />\n";
    $row = $db->fetchRow($sql);
    //var_dump($row);
    
    if ($row == false) {
        return -1;
    }
    
    $id = $row['id'];
    $type = $row['type'];
    $name = $row['name'];
    
    if ($bc == true) {
        $title = $row['title'];
        $bc_link .= $name;
        $breadcrumb->add($title, '');
    }
    
    //var_dump($param);
    if (!is_null($folder_param)) {
        $folder_param = $param;
    }
    
    $a = array('type' => $type, 'id' => $id, 'name' => $name);
    return $a;
}

/**
 * パス名からパンくずリストを作成する
 * @param string $path パス名
 */
function createBreadcrumbFromPath($path)
{
    
}

/**
 * メンバーIdからメンバーネームを得る
 * @param int $memberId メンバーId
 * @return string メンバーネーム
 */
function getMemberName($memberId)
{
    global $db;
    
}

/**
 * メニュー作成
 * @param string $bar メニュータイプ ('header' or 'global' or 'footer')
 * @param int $setid  メニューセットId
 */
function buildMenu($bar, $setid = 1)
{
    global $db, $manage;
    
    ob_start();
    
    $sql = "SELECT type, title, module_name, module_param, link_url, dmi_name FROM Platy_Menu WHERE bar='{$bar}' AND menuSetId={$setid} ORDER BY ordering";
    $rows = $db->fetchAll($sql);

    if (count($rows) > 0) {
    
        if ($bar == 'header') {
            echo '<div id="header_nav">' . "\n";
        }
        else if ($bar == 'global') {
            echo '<div id="global_nav">' . "\n";
        }
        else if ($bar == 'footer') {
            echo '<div id="footer_nav">' . "\n";
        }
        else {
            return '';
        }
        
        echo '<ul>' . "\n";
        foreach ($rows as $row) {
            if ($row['type'] == 'module') {
                if ($manage->module == $row['module_name']) {
                    echo '<li class="selected">';
                }
                else {
                    echo '<li>';
                }
                echo '<a href="' . BASE_URL . $row['module_name'];
                if ($row['module_param'] == '') {
                    echo '/">';
                }
                else {
                    echo '/' . $row['module_param'] . '">';
                }
                echo $row['title'];
                echo '</a>';
                echo '</li>' . "\n";
            }
            else if ($row['type'] == 'link') {
                echo '<li>';
                echo '<a href="' . $row['link_url'] . '">';
                echo $row['title'];
                echo '</a>';
                echo '</li>' . "\n";
            }
            else if ($row['type'] == 'dmi') {
                echo '<li>';
                require_once(APP_PATH . 'models/DMI/' . $row['dmi_name'] . '.php');
                $DMI_classname = 'Platy_DMI_' . $row['dmi_name'];
                $obj = new $DMI_classname;
                $obj->show();
                echo '</li>' . "\n";
            }
        }
        echo '</ul>' . "\n";
        
        echo '</div>' . "\n";
    }
    
    $contents = ob_get_contents();
    ob_end_clean();
    
    return $contents;
}

/**
 * メニューにアイテムを追加する
 * @param array $item メニューアイテム
 */
function addToMenu($item)
{
    global $db;
    
    $menuSetId = 1; // デフォルトメニューセット
    
    if ($item['type'] == 'module') {
        $sql = "INSERT INTO Platy_Menu(type, menuSetId, bar, title, module_name, module_param) VALUES("
             . "'{$item['type']}', "
             . "{$menuSetId},"
             . "'{$item['bar']}', "
             . "'{$item['title']}', "
             . "'{$item['module_name']}', "
             . "'{$item['module_param']}')";
    }
    else if ($item['type'] == 'link') {
        $sql = "INSERT INTO Platy_Menu(type, menuSetId, bar, title, link_url) VALUES("
             . "'{$item['type']}', "
             . "{$menuSetId},"
             . "'{$item['bar']}', "
             . "'{$item['title']}', "
             . "'{$item['link_url']}')";
    }
    else if ($item['type'] == 'dmi') {
        $sql = "INSERT INTO Platy_Menu(type, menuSetId, bar, dmi_name) VALUES("
             . "'{$item['type']}', "
             . "{$menuSetId},"
             . "'{$item['bar']}', "
             . "'{$item['dmi_name']}')";
    }
    else {
        return false;
    }
    try {
        //echo $sql . "<br />\n";
        $db->query($sql);
    }
    catch (Exception $e) {
        return false;
    }
    return true;
}

/**
 * サイドバー作成
 * @param int $setid サイドバーセットId
 * @return string サイドバー文字列
 */
function buildSidebar($setid = 1)
{
    global $db, $config;
    
    Zend_Loader::loadClass('Zend_View');
    $view = new Zend_View();
    $view->setScriptPath(BASE_PATH . 'theme/' . $config['S_THEME']);
    
    ob_start();
    
    $sql = "SELECT id, widget, code, lr FROM Platy_Sidebar WHERE sidebarSetId={$setid} ORDER BY ordering";
    $rows = $db->fetchAll($sql);
    foreach ($rows as $row) {
        require_once(APP_PATH . 'models/Widget/' . $row['widget'] . '.php');
        $widget_class_name = 'Platy_Widget_' . $row['widget'];
        //echo $widget_class_name . "<br />\n";
        $obj = new $widget_class_name;
        $a = $obj->view($row['code']);
        if (is_array($a)) {
            $view->widget_title = $a['title'];
            $view->widget_icons = $a['icons'];
            $view->widget_main = $a['main'];
            $view->widget_footer = $a['footer'];
            echo $view->render('widget.php');
        }
        $obj = NULL;
    }
    
    $contents = ob_get_contents();
    ob_end_clean();
    return $contents;
}

/**
 * Javascriptファイルの追加
 */
$Platy_JS_files = array();

function addJS($file) {
    global $Platy_JS_files;
    $Platy_JS_files[] = $file;
}

function listJS() {
}

/**
 * CSSファイルの追加
 */
$Platy_CSS_files = array();

function addCSS($file) {
    global $Platy_CSS_files;
    $Platy_CSS_files[] = $file;
}

function MsgBox($text, $caption, $type)
{
    echo '<div class="msgbox">';
    echo '<table><tr><td>';
    echo '<img src="' . BASE_URL . 'media/system/messagebox_warning.png">' . "\n";
    echo '</td><td>';
    echo $text;
    echo '</td></tr></table>' . "\n";
    echo '</div>' . "\n";
}

/**
 * 公開期間判定
 * @param string $start 公開開始日時(YYYY-MM-DD HH:MM:SS)
 * @param string $end   公開終了日時(YYYY-MM-DD HH:MM:SS)
 * @return bool 公開期間中ならばTRUE,そうでなければFALSEを返す
 */
function checkPeriod($start, $end) {
    $start_uts = mktime(0, 0, 0, 1, 1, 1970);
    if (strlen($start) > 0) {
        $a = explode(' ', $start);
        $b = explode('-', $a[0]);
        $c = explode(':', $a[1]);
        $year = $b[0];
        $month = $b[1];
        $day = $b[2];
        $hour = $c[0];
        $min = $c[1];
        $sec = $c[2];
        $start_uts = mktime($hour, $min, $sec, $month, $day, $year);
    }
    $end_uts = mktime(0, 0, 0, 12, 31, 2037);
    if (strlen($end) > 0) {
        $a = explode(' ', $end);
        $b = explode('-', $a[0]);
        $c = explode(':', $a[1]);
        $year = $b[0];
        $month = $b[1];
        $day = $b[2];
        $hour = $c[0];
        $min = $c[1];
        $sec = $c[2];
        $end_uts = mktime($hour, $min, $sec, $month, $day, $year);
    }
    $now_uts = mktime();
    
    //echo sprintf("checkPeriod:%s - %s<br />\n", $start, $end);
    //echo sprintf("checkPeriod:%d %d - %d<br />\n", $now_uts, $start_uts, $end_uts);
    
    if ($start_uts <= $now_uts && $now_uts <= $end_uts) {
        return TRUE;
    }
    return FALSE;
}

/**
 * idからコンテント情報を得る
 * @param int $id 
 * @return array コンテント情報
 *               url, title, created, modified
 * # url を得るために、ルートからのパスを検索する
 */
function getContentFromId($id) { return getContentFromNodeId($id); }

function getContentFromNodeId($id) {
    global $db;
    $first = true;
    $pieces = array();
    $nId = $id;
   
    do {
        $sql = "SELECT id, parentId FROM Platy_Content_Node WHERE id={$nId}";
        //echo $sql;
        $row = $db->fetchRow($sql);
        
        $sql2 = "SELECT name, title, summary, created, modified FROM Platy_Content_Base WHERE id={$nId}";
        //echo $sql2;
        $row2 = $db->fetchRow($sql2);
        
        if ($first == true) {
            $title = $row2['title'];
            $summary = $row2['summary'];
            $created = $row2['created'];
            $modified = $row2['modified'];
            $first = false;
        }
        $pieces[] = $row2['name'];
        
        $nId = $row['parentId'];
        //echo $nId;
        
    } while ($nId != 0);
    
    $n = count($pieces);
    //var_dump($pieces);
    for ($i = 0; $i < $n; $i++) {
        if ($i > 0) {
            $url = $url . '/';
        }
        $url = $url . $pieces[$n -1 -$i];
    }
    //echo $url;
    
    $ret = array('url' => $url, 'title' => $title, 'summary' => $summary, 'created' => $created, 'modified' => $modified);
    //var_dump($ret);
    return $ret;
}

/**
 * idからURLを得る
 * @param int $id 
 * @return string URL
 * # url を得るために、ルートからのパスを検索する
 *   複数回(idの階層分だけ)クエリーを発行するので、それなりに遅くなりそう（多用したくない）
 */
function getURLFromId($id) { 
    global $db;
    $first = true;
    $pieces = array();
    $nId = $id;
    
    do {
        $sql = "SELECT id, parentId FROM Platy_Content_Node WHERE id={$nId}";
        $row = $db->fetchRow($sql);
        
        $sql2 = "SELECT name, title, summary, created, modified FROM Platy_Content_Base WHERE id={$nId}";
        $row2 = $db->fetchRow($sql2);
        
        $pieces[] = $row2['name'];
        
        $nId = $row['parentId'];
        
    } while ($nId != 0);
    
    $n = count($pieces);
    //var_dump($pieces);
    for ($i = 0; $i < $n; $i++) {
        if ($i > 0) {
            $url = $url . '/';
        }
        $url = $url . $pieces[$n -1 -$i];
    }
    //echo $url;
    
    // /rootをカットする #0.6.0
    $url = substr($url, 5);
    
    $ret = BASE_FULL_URL . $url;
    return $ret;
}

/**
 * escape_string のショートカット
 * # $db->quote()と同じため不要
 */
/*
function e($s)
{
    switch (DB_TYPE) {
    case 'sqlite':
        return sqlite_escape_string($s);
    case 'mysql':
        return mysql_escape_string($s);
    case 'pg':
        return pg_escape_string($s);
    default:
        return addslashes($s);
    }
}
*/

/**
 * 管理メニュー作成
 */
function buildManageMenu()
{
    global $currentManage;
    
    $menuItems = array(array('name' => 'Node',        'url' => BASE_URL . 'Manage/Node/',        'title' => 'ノード'),
                       array('name' => 'Ctype',       'url' => BASE_URL . 'Manage/Ctype/',       'title' => 'コンテンツタイプ'),
                       array('name' => 'Cext',        'url' => BASE_URL . 'Manage/Cext/',        'title' => 'コンテンツ拡張'),
                       array('name' => 'Cvar',        'url' => BASE_URL . 'Manage/Cvar/',        'title' => 'コンテンツ変数'),
                       array('name' => 'Module',      'url' => BASE_URL . 'Manage/Module/',      'title' => 'モジュール'),
                       array('name' => 'Menu',        'url' => BASE_URL . 'Manage/Menu/',        'title' => 'メニュー'),
                       array('name' => 'Widget',      'url' => BASE_URL . 'Manage/Widget/',      'title' => 'ウィジェット'),
                       array('name' => 'Sidebar',     'url' => BASE_URL . 'Manage/Sidebar/',     'title' => 'サイドバー'),
                       array('name' => 'Member',      'url' => BASE_URL . 'Manage/Member/',      'title' => 'メンバー'),
                       array('name' => 'Role',        'url' => BASE_URL . 'Manage/Role/',        'title' => 'ロール'),
                       array('name' => 'Site',        'url' => BASE_URL . 'Manage/Site/',        'title' => 'サイト情報'),
                       array('name' => 'Db',          'url' => BASE_URL . 'Manage/Db/',          'title' => 'データベース'),
                       array('name' => 'System',      'url' => BASE_URL . 'Manage/System/',      'title' => 'システム情報')
                 );
    
    echo '<ul>' . "\n";
    
    foreach ($menuItems as $item) {
        if ($currentManage == $item['name']) {
            echo '<li class="selected">';
        }
        else {
            echo '<li>';
        }
        
        echo '<a href="' . $item['url'] . '">' . $item['title'] . '</a></li>' . "\n";
    }
    
    echo '</ul>' . "\n";
}
// Global Functions <<<<<
?>