<?php

/**
 * ECSHOP 管理中心模版管理程序
 * ============================================================================
 * 版权所有 (C) 2005-2007 北京亿商互动科技发展有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com
 * ----------------------------------------------------------------------------
 * 这是一个免费开源的软件；这意味着您可以在不用于商业目的的前提下对程序代码
 * 进行修改、使用和再发布。
 * ============================================================================
 * @author:     Weber Liu <weberliu@hotmail.com>
 * @version:    v2.1
 * ---------------------------------------------
 * $Author: paulgao $
 * $Date: 2007-05-21 16:06:07 +0800 (星期一, 21 五月 2007) $
 * $Id: template.php 8665 2007-05-21 08:06:07Z paulgao $
*/

define('IN_ECS', true);

require('includes/init.php');
require_once('includes/lib_template.php');

/*------------------------------------------------------ */
//-- 模版列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
    /* 获得当前的模版的信息 */
    $curr_template = $_CFG['template'];

    /* 获得可用的模版 */
    $available_templates = array();
    $template_dir        = @opendir(ROOT_PATH . 'themes/');
    while ($file = readdir($template_dir))
    {
        if ($file != '.' && $file != '..' && is_dir(ROOT_PATH. 'themes/' . $file) && $file != '.svn')
        {
            $available_templates[] = get_template_info($file);
        }
    }
    @closedir($template_dir);

    /* 清除不需要的模板设置 */
    $available_code = array();
    $sql = "DELETE FROM ".$ecs->table('template')." WHERE 1 ";
    foreach ($available_templates AS $tmp)
    {
        $sql .= " AND theme <> '".$tmp['code']."' ";
        $available_code[] = $tmp['code'];
    }
    $tmp_bak_dir = @opendir(ROOT_PATH .'templates/backup/library/');
    while ($file = readdir($tmp_bak_dir))
    {
        if ($file != '.' && $file != '..' && $file != '.svn' && is_file(ROOT_PATH .'templates/backup/library/' . $file) == true)
        {
            $code = substr($file, 0, strpos($file, '-'));
            if (!in_array($code, $available_code))
            {
                @unlink(ROOT_PATH . 'templates/backup/library/' . $file);
            }
        }
    }

    $db->query($sql);

    assign_query_info();

    $smarty->assign('ur_here',             $_LANG['template_manage']);
    $smarty->assign('curr_template',       get_template_info($curr_template));
    $smarty->assign('available_templates', $available_templates);
    $smarty->display('templates_list.htm');
}

/*------------------------------------------------------ */
//-- 设置模板的内容
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'setup')
{
    admin_priv('template_manage');

    $template_theme = $_CFG['template'];
    $curr_template  = empty($_REQUEST['template_file']) ? 'index' : $_REQUEST['template_file'];

    $temp_options   = array();
    $temp_regions   = get_template_region($template_theme, $curr_template.'.dwt', false);
    $temp_libs      = get_template_region($template_theme, $curr_template.'.dwt', true);

    /* 获取数据库中数据，并跟模板中数据核对,并设置动态内容 */
    /* 动态内容 */
    $cate_goods   = array();
    $brand_goods  = array();
    $cat_articles = array();
    $ad_positions = array();

    $sql = "SELECT region, library, sort_order, id, number, type FROM ".$ecs->table('template') ." ".
           "WHERE theme='$template_theme' AND filename='$curr_template' AND type > 0 ".
           "ORDER BY region, sort_order ASC ";

    $rc = $db->query($sql);
    $db_dyna_libs = array();
    while ($row= $db->FetchRow($rc))
    {
        $db_dyna_libs[$row['region']][$row['library']][] = array('id' => $row['id'], 'number' => $row['number'], 'type' => $row['type']);
    }

    foreach ($temp_libs AS $val)
    {
        /* 对动态内容赋值 */
        if ($val['lib'] == 'cat_goods')
        {
            /* 分类下的商品 */
            if (isset($db_dyna_libs[$val['region']][$val['library']]) && ($row = array_shift($db_dyna_libs[$val['region']][$val['library']])))
            {
                $cate_goods[] = array('region' => $val['region'], 'sort_order' => $val['sort_order'], 'number' => $row['number'], 'cats'=>cat_list(0, $row['id']));
            }
            else
            {
                $cate_goods[] = array('region' => $val['region'], 'sort_order' => $val['sort_order'], 'number'=>0, 'cats'=>cat_list(0));
            }
        }

        elseif ($val['lib'] == 'brand_goods')
        {
            /* 品牌下的商品 */
            if (isset($db_dyna_libs[$val['region']][$val['library']]) && ($row = array_shift($db_dyna_libs[$val['region']][$val['library']])))
            {
                $brand_goods[] = array('region' => $val['region'], 'sort_order' => $val['sort_order'], 'number' => $row['number'], 'brand' => $row['id']);
            }
            else
            {
                $brand_goods[] = array('region' => $val['region'], 'sort_order' => $val['sort_order'], 'number'=>0, 'brand'=>0);
            }
        }

        /* 文章列表 */
        elseif ($val['lib'] == 'cat_articles')
        {
            if (isset($db_dyna_libs[$val['region']][$val['library']]) && ($row = array_shift($db_dyna_libs[$val['region']][$val['library']])))
            {
                $cat_articles[] = array('region' => $val['region'], 'sort_order' => $val['sort_order'], 'number' => $row['number'], 'cat' => $row['id']);
            }
            else
            {
                $cat_articles[] = array('region' => $val['region'], 'sort_order' => $val['sort_order'], 'number'=>0, 'cat'=>0);
            }
        }

        /* 广告位 */
        elseif ($val['lib'] == 'ad_position')
        {
            if (isset($db_dyna_libs[$val['region']][$val['library']]) && ($row = array_shift($db_dyna_libs[$val['region']][$val['library']])))
            {
                 $ad_positions[] = array('region' => $val['region'], 'sort_order' => $val['sort_order'], 'number' => $row['number'], 'ad_pos' => $row['id']);
            }
            else
            {
                 $ad_positions[] = array('region' => $val['region'], 'sort_order' => $val['sort_order'], 'number'=>0, 'ad_pos'=>0);
            }
        }
    }

    /* 固定内容 */
    foreach ($page_libs[$curr_template] AS $val)
    {
        $lib = basename(strtolower(substr($val, 0, strpos($val, '.'))));
        if (!in_array($lib, $GLOBALS['dyna_libs']))
        {
            /* 先排除动态内容 */
            $temp_options[$lib]            = get_setted($val, $temp_libs);
            $temp_options[$lib]['desc']    = $_LANG['template_libs'][$lib];
            $temp_options[$lib]['library'] = $val;
        }
    }

    assign_query_info();
    $smarty->assign('ur_here',            $_LANG['03_template_setup']);
    $smarty->assign('curr_template_file', $curr_template);
    $smarty->assign('temp_options',       $temp_options);
    $smarty->assign('temp_regions',       $temp_regions);
    $smarty->assign('cate_goods',         $cate_goods);
    $smarty->assign('brand_goods',        $brand_goods);
    $smarty->assign('cat_articles',       $cat_articles);
    $smarty->assign('ad_positions',       $ad_positions);
    $smarty->assign('arr_cates',          cat_list(0, 0, true));
    $smarty->assign('arr_brands',         get_brand_list());
    $smarty->assign('arr_article_cats',   article_cat_list(0, false));
    $smarty->assign('arr_ad_positions',   get_position_list());
    $smarty->display('template_setup.htm');
}

/*------------------------------------------------------ */
//-- 提交模板内容设置
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'setting')
{
    admin_priv('template_manage');

    $curr_template = $_CFG['template'];
    $db->query("DELETE FROM " .$ecs->table('template'). " WHERE filename = '$_POST[template_file]' AND theme = '$curr_template'");

    /* 先处理固定内容 */
    foreach ($_POST['regions'] AS $key => $val)
    {
        if (!in_array($key, $GLOBALS['dyna_libs']) AND isset($_POST['display'][$key]) AND $_POST['display'][$key] == 1)
        {
            $sql = "INSERT INTO " .$ecs->table('template').
                        "(theme, filename, region, library, sort_order)".
                    " VALUES ".
                        "('$curr_template', '$_POST[template_file]', '$val', '".$_POST['map'][$key]."', '" .$_POST['sort_order'][$key]. "')";
            $db->query($sql);
        }
    }

    /* 分类的商品 */
    if (isset($_POST['regions']['cat_goods']))
    {
        foreach ($_POST['regions']['cat_goods'] AS $key => $val)
        {
            if ($_POST['categories']['cat_goods'][$key] != '' && intval($_POST['categories']['cat_goods'][$key]) > 0)
            {
                $sql = "INSERT INTO " .$ecs->table('template'). " (".
                            "theme, filename, region, library, sort_order, type, id, number".
                        ") VALUES (".
                            "'$curr_template', ".
                            "'$_POST[template_file]', '" .$val. "', '/library/cat_goods.lbi', ".
                            "'" .$_POST['sort_order']['cat_goods'][$key]. "', 1, '" .$_POST['categories']['cat_goods'][$key].
                            "', '" .$_POST['number']['cat_goods'][$key]. "'".
                        ")";
                $db->query($sql);
            }
        }
    }

    /* 品牌的商品 */
    if (isset($_POST['regions']['brand_goods']))
    {
        foreach ($_POST['regions']['brand_goods'] AS $key => $val)
        {
            if ($_POST['brands']['brand_goods'][$key] != '' && intval($_POST['brands']['brand_goods'][$key]) > 0)
            {
                $sql = "INSERT INTO " .$ecs->table('template'). " (".
                            "theme, filename, region, library, sort_order, type, id, number".
                        ") VALUES (".
                            "'$curr_template', ".
                            "'$_POST[template_file]', '" .$val. "', '/library/brand_goods.lbi', ".
                            "'" .$_POST['sort_order']['brand_goods'][$key]. "', 2, '" .$_POST['brands']['brand_goods'][$key].
                            "', '" .$_POST['number']['brand_goods'][$key]. "'".
                        ")";
                $db->query($sql);
            }
        }
    }

    /* 文章列表 */
    if (isset($_POST['regions']['cat_articles']))
    {
        foreach ($_POST['regions']['cat_articles'] AS $key => $val)
        {
            if ($_POST['article_cat']['cat_articles'][$key] != '' && intval($_POST['article_cat']['cat_articles'][$key]) > 0)
            {
                $sql = "INSERT INTO " .$ecs->table('template'). " (".
                            "theme, filename, region, library, sort_order, type, id, number".
                        ") VALUES (".
                            "'$curr_template', ".
                            "'$_POST[template_file]', '" .$val. "', '/library/cat_articles.lbi', ".
                            "'" .$_POST['sort_order']['cat_articles'][$key]. "', 3, '" .$_POST['article_cat']['cat_articles'][$key].
                            "', '" .$_POST['number']['cat_articles'][$key]. "'".
                        ")";
                $db->query($sql);
            }
        }
    }

    /* 广告位 */
    if (isset($_POST['regions']['ad_position']))
    {
        foreach ($_POST['regions']['ad_position'] AS $key => $val)
        {
            if ($_POST['ad_position'][$key] != '' && intval($_POST['ad_position'][$key]) > 0)
            {
                $sql = "INSERT INTO " .$ecs->table('template'). " (".
                            "theme, filename, region, library, sort_order, type, id, number".
                        ") VALUES (".
                            "'$curr_template', ".
                            "'$_POST[template_file]', '" .$val. "', '/library/ad_position.lbi', ".
                            "'" .$_POST['sort_order']['ad_position'][$key]. "', 4, '" .$_POST['ad_position'][$key].
                            "', '" .$_POST['number']['ad_position'][$key]. "'".
                        ")";
                $db->query($sql);
            }
        }
    }

    /* 对提交内容进行处理 */
    $post_regions = array();
    foreach ($_POST['regions'] AS $key => $val)
    {
        switch ($key)
        {
            case 'cat_goods':
                foreach ($val AS $k => $v)
                {
                    if (intval($_POST['categories']['cat_goods'][$k]) > 0)
                    {
                        $post_regions[] = array('region'     => $v,
                                                'type'       => 1,
                                                'number'     => $_POST['number']['cat_goods'][$k],
                                                'library'    => '/library/' .$key. '.lbi',
                                                'sort_order' => $_POST['sort_order']['cat_goods'][$k],
                                                'id'         => $_POST['categories']['cat_goods'][$k]);
                    }
                }
                break;
            case 'brand_goods':
                foreach ($val AS $k => $v)
                {
                    if (intval($_POST['brands']['brand_goods'][$k]) > 0)
                    {
                        $post_regions[] = array('region'     => $v,
                                                'type'       => 2,
                                                'number'     => $_POST['number']['brand_goods'][$k],
                                                'library'    => '/library/' .$key. '.lbi',
                                                'sort_order' => $_POST['sort_order']['brand_goods'][$k],
                                                'id'         => $_POST['brands']['brand_goods'][$k]);
                    }
                }
                break;
            case 'cat_articles':
                foreach ($val AS $k => $v)
                {
                    if (intval($_POST['article_cat']['cat_articles'][$k]) > 0)
                    {
                        $post_regions[] = array('region'     => $v,
                                                'type'       => 3,
                                                'number'     => $_POST['number']['cat_articles'][$k],
                                                'library'    => '/library/' .$key. '.lbi',
                                                'sort_order' => $_POST['sort_order']['cat_articles'][$k],
                                                'id'         => $_POST['article_cat']['cat_articles'][$k]);
                    }
                }
                break;
            case 'ad_position':
                foreach ($val AS $k => $v)
                {
                    if (intval($_POST['ad_position'][$k]) > 0)
                    {
                        $post_regions[] = array('region'     => $v,
                                                'type'       => 4,
                                                'number'     => $_POST['number']['ad_position'][$k],
                                                'library'    => '/library/' .$key. '.lbi',
                                                'sort_order' => $_POST['sort_order']['ad_position'][$k],
                                                'id'         => $_POST['ad_position'][$k]);
                    }
                }
                break;
            default:
                if (!empty($_POST['display'][$key]))
                {
                    $post_regions[] = array('region'     => $val,
                                            'type'       => 0,
                                            'number'     => 0,
                                            'library'    => $_POST['map'][$key],
                                            'sort_order' => $_POST['sort_order'][$key],
                                            'id'         => 0);
                }

        }
    }

    /* 排序 */
    usort($post_regions, "array_sort");

    /* 修改模板文件 */
    $template_file    = '../themes/' . $curr_template . '/' . $_POST['template_file'] . '.dwt';
    $template_content = file_get_contents($template_file);
    $template_content = str_replace("\xEF\xBB\xBF", '', $template_content);
    $org_regions      = get_template_region($curr_template, $_POST['template_file'].'.dwt', false);

    $region_content   = '';
    $pattern          = '/(<!--\\s*TemplateBeginEditable\\sname="%s"\\s*-->)(.*?)(<!--\\s*TemplateEndEditable\\s*-->)/s';
    $replacement      = "\\1\n%s\\3";
    $lib_template     = "<!-- #BeginLibraryItem \"%s\" -->\n%s\n <!-- #EndLibraryItem -->\n";

    foreach ($org_regions AS $region)
    {
        $region_content = ''; // 获取当前区域内容
        foreach ($post_regions AS $lib)
        {
            if ($lib['region'] == $region)
            {
                $lib_content     = file_get_contents('../themes/' . $curr_template . $lib['library']);
                $lib_content     = preg_replace('/<meta\\shttp-equiv=["|\']Content-Type["|\']\\scontent=["|\']text\/html;\\scharset=(.*?)["|\']>/i', '', $lib_content);
                $lib_content     = str_replace("\xEF\xBB\xBF", '', $lib_content);
                $region_content .= sprintf($lib_template, $lib['library'], $lib_content);
            }
        }

        /* 替换原来区域内容 */
        $template_content = preg_replace(sprintf($pattern, $region), sprintf($replacement , $region_content), $template_content);
    }

    if (file_put_contents($template_file, $template_content))
    {
        clear_tpl_files(false, '.dwt.php'); // 清除对应的编译文件
        $lnk[] = array('text' => $_LANG['go_back'], 'href'=>'template.php?act=setup&template_file=' .$_POST['template_file']);
        sys_msg($_LANG['setup_success'], 0, $lnk);
    }
    else
    {
        sys_msg(sprintf($_LANG['modify_dwt_failed'], 'themes/' . $curr_template. '/' . $_POST['template_file'] . '.dwt'), 1, null, false);
    }
}

/*------------------------------------------------------ */
//-- 管理库项目
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'library')
{
    admin_priv('template_manage');

    /* 包含插件语言项 */
    $sql = "SELECT code FROM ".$ecs->table('plugins');
    $rs = $db->query($sql);
    while ($row = $db->FetchRow($rs))
    {
        /* 取得语言项 */
        if (file_exists('../plugins/'.$row['code'].'/languages/common_'.$_CFG['lang'].'.php'))
        {
            include_once('../plugins/'.$row['code'].'/languages/common_'.$_CFG['lang'].'.php');
        }
    };
    $curr_template = $_CFG['template'];
    $arr_library   = array();
    $library_path  = '../themes/' . $curr_template . '/library';
    $library_dir   = @opendir($library_path);
    $curr_library  = '';

    while ($file = @readdir($library_dir))
    {
        if (substr($file, -3) == "lbi")
        {
            $filename               = substr($file, 0, -4);
            $arr_library[$filename] = $file. ' - ' . @$_LANG['template_libs'][$filename];

            if ($curr_library == '')
            {
                $curr_library = $filename;
            }
        }
    }

    ksort($arr_library);

    @closedir($library_dir);

    $lib = load_library($curr_template, $curr_library);

    assign_query_info();
    $smarty->assign('ur_here',      $_LANG['04_template_library']);
    $smarty->assign('curr_library', $curr_library);
    $smarty->assign('libraries',    $arr_library);
    $smarty->assign('library_html', $lib['html']);
    $smarty->display('template_library.htm');
}

/*------------------------------------------------------ */
//-- 安装模版
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'install')
{
    check_authz_json('template_manage');

    $tpl_name = trim($_GET['tpl_name']);

    $sql = "UPDATE " .$GLOBALS['ecs']->table('shop_config'). " SET value = '$tpl_name' WHERE code = 'template'";
    if ($db->query($sql, 'SILENT'))
    {
        clear_all_files(); //清除模板编译文件

        $error_msg = '';
        if (move_plugin_library($tpl_name, $error_msg))
        {
            make_json_error($error_msg);
        }
        else
        {
            make_json_result(get_template_info($tpl_name), $_LANG['install_template_success']);
        }
    }
    else
    {
        make_json_error($db->error());
    }
}

/*------------------------------------------------------ */
//-- 备份模版
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'backup')
{
    include_once('includes/cls_phpzip.php');

    $tpl = trim($_REQUEST['tpl_name']);

    $filename = '../templates/backup/' . $tpl . '_' . date('Ymd') . '.zip';

    $zip = new PHPZip;
    $done = $zip->zip('../themes/' . $tpl . '/', $filename);

    if ($done)
    {
        make_json_result($filename);
    }
    else
    {
        make_json_error($_LANG['backup_failed']);
    }
}

/*------------------------------------------------------ */
//-- 载入指定库项目的内容
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'load_library')
{
    $library = load_library($_CFG['template'], trim($_GET['lib']));
    $message = ($library['mark'] & 7) ? '' : $_LANG['library_not_written'];

    make_json_result($library['html'], $message);
}

/*------------------------------------------------------ */
//-- 更新库项目内容
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'update_library')
{
    check_authz_json('template_manage');

    $html = stripslashes($_POST['html']);
    $lib_file = '../themes/' . $_CFG['template'] . '/library/' . $_POST['lib'] . '.lbi';
    $lib_file = str_replace("0xa", '', $lib_file); // 过滤 0xa 非法字符

    $org_html = str_replace("\xEF\xBB\xBF", '', file_get_contents($lib_file));

    if (@file_exists($lib_file) === true && @file_put_contents($lib_file, $html))
    {
        @file_put_contents('../templates/backup/library/' . $_CFG['template'] . '-' . $_POST['lib'] . '.lbi', $org_html);

        make_json_result('', $_LANG['update_lib_success']);
    }
    else
    {
        make_json_error(sprintf($_LANG['update_lib_failed'], 'themes/' . $_CFG['template'] . '/library'));
    }
}

/*------------------------------------------------------ */
//-- 还原库项目
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'restore_library')
{
    $lib_name   = trim($_GET['lib']);
    $lib_file   = '../themes/' . $_CFG['template'] . '/library/' . $lib_name . '.lbi';
    $lib_file   = str_replace("0xa", '', $lib_file); // 过滤 0xa 非法字符
    $lib_backup = '../templates/backup/library/' . $_CFG['template'] . '-' . $lib_name . '.lbi';
    $lib_backup = str_replace("0xa", '', $lib_backup); // 过滤 0xa 非法字符

    if (file_exists($lib_backup) && filemtime($lib_backup) >= filemtime($lib_file))
    {
        make_json_result(str_replace("\xEF\xBB\xBF", '',file_get_contents($lib_backup)));
    }
    else
    {
        make_json_result(str_replace("\xEF\xBB\xBF", '',file_get_contents($lib_file)));
    }
}

function array_sort($a, $b)
{
    $cmp = strcmp($a['region'], $b['region']);

    if ($cmp == 0)
    {
        return ($a['sort_order'] < $b['sort_order']) ? -1 : 1;
    }
    else
    {
        return ($cmp > 0) ? -1 : 1;
    }
}

/**
 * 载入库项目内容
 *
 * @access  public
 * @param   string  $curr_template  模版名称
 * @param   string  $lib_name       库项目名称
 * @return  array
 */
function load_library($curr_template, $lib_name)
{
    $lib_name = str_replace("0xa", '', $lib_name); // 过滤 0xa 非法字符

    $lib_file    = '../themes/' . $curr_template . '/library/' . $lib_name . '.lbi';
    $arr['mark'] = file_mode_info($lib_file);
    $arr['html'] = str_replace("\xEF\xBB\xBF", '', file_get_contents($lib_file));

    return $arr;
}

?>