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

define('IN_ECS', true);

require('includes/init.php');

/*------------------------------------------------------ */
//-- 框架
/*------------------------------------------------------ */
if ($_REQUEST['act'] == '')
{
    $smarty->display('index.htm');
}

/*------------------------------------------------------ */
//-- 顶部框架的内容
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'top')
{
    // 获得管理员设置的菜单
    $lst = array();
    $nav = $db->GetOne('SELECT nav_list FROM ' . $ecs->table('admin_user') . " WHERE user_id = '" . $_SESSION['admin_id'] . "'");

    if (!empty($nav))
    {
        $arr = explode(',', $nav);

        foreach ($arr AS $val)
        {
            $tmp = explode('|', $val);
            $lst[$tmp[1]] = $tmp[0];
        }
    }

    // 获得管理员ID
    $smarty->assign('nav_list', $lst);
    $smarty->display('top.htm');
}

/*------------------------------------------------------ */
//-- 计算器
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'calculator')
{
    $smarty->display('calculator.htm');
}

/*------------------------------------------------------ */
//-- 左边的框架
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'menu')
{
    include_once('includes/inc_menu.php');

    /* 包含插件菜单语言项 */
    $sql = 'SELECT code FROM ' . $ecs->table('plugins');
    $rs = $db->query($sql);
    while ($row = $db->FetchRow($rs))
    {
        /* 取得语言项 */
        if (file_exists(ROOT_PATH . 'plugins/'.$row['code'].'/languages/common_'.$_CFG['lang'].'.php'))
        {
            include_once(ROOT_PATH . 'plugins/'.$row['code'].'/languages/common_'.$_CFG['lang'].'.php');
        }

        /* 插件的菜单项 */
        if (file_exists(ROOT_PATH . 'plugins/'.$row['code'].'/languages/inc_menu.php'))
        {
            include_once(ROOT_PATH . 'plugins/'.$row['code'].'/languages/inc_menu.php');
        }
    }

    foreach ($modules AS $key => $value)
    {
        ksort($modules[$key]);
    }
    ksort($modules);

    foreach ($modules AS $key => $val)
    {
        $menus[$key]['label'] = $_LANG[$key];
        if (is_array($val))
        {
            foreach ($val AS $k => $v)
            {
                $menus[$key]['children'][$k]['label']  = $_LANG[$k];
                $menus[$key]['children'][$k]['action'] = $v;
            }
        }
        else
        {
            $menus[$key]['action'] = $val;
        }
    }

    $smarty->assign('menus',     $menus);
    $smarty->assign('no_help',   $_LANG['no_help']);
    $smarty->assign('help_lang', $_CFG['lang']);
    $smarty->display('menu.htm');
}

/*------------------------------------------------------ */
//-- 清除缓存
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'clear_cache')
{
    clear_all_files();

    sys_msg($_LANG['caches_cleared']);
}

/*------------------------------------------------------ */
//-- 主窗口，起始页
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'main')
{
    $gd = gd_version();

    /* 检查文件目录属性 */
    $warning = array();

    if ($_CFG['shop_closed'])
    {
        $warning[] = $_LANG['shop_closed_tips'];
    }

    if (file_exists('../install'))
    {
        $warning[] = $_LANG['remove_install'];
    }

    if (file_exists('../upgrade'))
    {
        $warning[] = $_LANG['remove_upgrade'];
    }

    $open_basedir = ini_get('open_basedir');
    if (!empty($open_basedir))
    {
        /* 如果 open_basedir 不为空，则检查是否包含了 upload_tmp_dir  */
        $open_basedir = str_replace(array("\\", "\\\\"), array("/", "/"), $open_basedir);
        $upload_tmp_dir = ini_get('upload_tmp_dir');

        if (empty($upload_tmp_dir))
        {
            if (stristr(PHP_OS, 'win'))
            {
                $upload_tmp_dir = getenv('TEMP') ? getenv('TEMP') : getenv('TMP');
                $upload_tmp_dir = str_replace(array("\\", "\\\\"), array("/", "/"), $upload_tmp_dir);
            }
            else
            {
                $upload_tmp_dir = getenv('TMPDIR') === false ? '/tmp' : getenv('TMPDIR');
            }
        }

        if (!stristr($open_basedir, $upload_tmp_dir))
        {
            $warning[] = sprintf($_LANG['temp_dir_cannt_read'], $upload_tmp_dir);
        }
    }

    $result = file_mode_info('../cert');
    if ($result < 2)
    {
        $warning[] = sprintf($_LANG['not_writable'], 'cert', $_LANG['cert_cannt_write']);
    }

    $result = file_mode_info('../data');
    if ($result < 2)
    {
        $warning[] = sprintf($_LANG['not_writable'], 'data', $_LANG['data_cannt_write']);
    }
    else
    {
        $result = file_mode_info('../data/afficheimg');
        if ($result < 2)
        {
            $warning[] = sprintf($_LANG['not_writable'], 'data/afficheimg', $_LANG['afficheimg_cannt_write']);
        }

        $result = file_mode_info('../data/brandlogo');
        if ($result < 2)
        {
            $warning[] = sprintf($_LANG['not_writable'], 'data/brandlogo', $_LANG['brandlogo_cannt_write']);
        }

        $result = file_mode_info('../data/cardimg');
        if ($result < 2)
        {
            $warning[] = sprintf($_LANG['not_writable'], 'data/cardimg', $_LANG['cardimg_cannt_write']);
        }

        $result = file_mode_info('../data/feedbackimg');
        if ($result < 2)
        {
            $warning[] = sprintf($_LANG['not_writable'], 'data/feedbackimg', $_LANG['feedbackimg_cannt_write']);
        }

        $result = file_mode_info('../data/packimg');
        if ($result < 2)
        {
            $warning[] = sprintf($_LANG['not_writable'], 'data/packimg', $_LANG['packimg_cannt_write']);
        }
    }

    $result = file_mode_info('../images');
    if ($result < 2)
    {
        $warning[] = sprintf($_LANG['not_writable'], 'images', $_LANG['images_cannt_write']);
    }
    else
    {
        $result = file_mode_info('../images/upload');
        if ($result < 2)
        {
            $warning[] = sprintf($_LANG['not_writable'], 'images/upload', $_LANG['imagesupload_cannt_write']);
        }
    }

    $result = file_mode_info('../templates');
    if ($result < 2)
    {
        $warning[] = sprintf($_LANG['not_writable'], 'images', $_LANG['tpl_cannt_write']);
    }

    $result = file_mode_info('../templates/backup');
    if ($result < 2)
    {
        $warning[] = sprintf($_LANG['not_writable'], 'images', $_LANG['tpl_backup_cannt_write']);
    }

    if (!is_writeable('../data/order_print.html'))
    {
        $warning[] = $_LANG['order_print_canntwrite'];
    }
    clearstatcache();

    $smarty->assign('warning_arr', $warning);

    /* 管理员留言信息 */
    $sql = 'SELECT message_id, sender_id, receiver_id, send_date, readed, deleted, title, message, user_name ' .
           'FROM ' . $ecs->table('admin_message') . ' AS a, ' . $ecs->table('admin_user') . ' AS b ' .
           "WHERE a.sender_id = b.user_id AND a.receiver_id = '$_SESSION[admin_id]' AND a.readed = 0 AND deleted = 0 ORDER BY a.send_date DESC";
    $admin_msg = $db->GetAll($sql);

    $smarty->assign('admin_msg', $admin_msg);

    /* 取得支持货到付款和不支持货到付款的支付方式 */
    $ids = get_pay_ids();

    /* 已完成的订单 */
    $order['finished']     = $db->GetOne('SELECT COUNT(*) FROM ' . $ecs->table('order_info').
                                        " WHERE order_status = '" . OS_CONFIRMED . "'" .
                                        " AND (pay_status = '" . PS_PAYED . "' OR pay_status = '" . PS_PAYING . "')" .
                                        " AND (shipping_status = '" . SS_SHIPPED . "' OR shipping_status = '" . SS_RECEIVED . "')");
    $status['finished']    = CS_FINISHED;

    /* 待发货的订单： */
    $order['await_ship']   = $db->GetOne('SELECT COUNT(*)'.
                                        ' FROM ' .$ecs->table('order_info') .
                                        " WHERE order_status = '" . OS_CONFIRMED . "'" .
                                        " AND shipping_status = '" . SS_UNSHIPPED . "'" .
                                        ' AND ((pay_id ' . db_create_in($ids['is_not_cod']) . " AND pay_status <> '" . PS_UNPAYED . "') OR pay_id " . db_create_in($ids['is_cod']) . ')');
    $status['await_ship']  = CS_AWAIT_SHIP;

    /* 待付款的订单： */
    $order['await_pay']    = $db->GetOne('SELECT COUNT(*)'.
                                        ' FROM ' .$ecs->table('order_info') .
                                        " WHERE order_status = '" . OS_CONFIRMED . "'" .
                                        " AND pay_status = '" . PS_UNPAYED . "'" .
                                        ' AND ((pay_id ' . db_create_in($ids['is_cod']) . " AND shipping_status <> '" . SS_UNSHIPPED . "') OR pay_id " . db_create_in($ids['is_not_cod']) . ')');
    $status['await_pay']   = CS_AWAIT_PAY;

    /* “未确认”的订单 */
    $order['unconfirmed']  = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('order_info').
                                        " WHERE order_status = '" . OS_UNCONFIRMED . "'");
    $status['unconfirmed'] = OS_UNCONFIRMED;

    $smarty->assign('order', $order);
    $smarty->assign('status', $status);

    /* 商品信息 */
    $goods['total']   = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
                                    ' WHERE is_delete = 0 AND (is_gift = 0 OR is_alone_sale = 1)');
    $goods['new']     = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
                                    ' WHERE is_delete = 0 AND is_new = 1');
    $goods['best']    = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
                                    ' WHERE is_delete = 0 AND is_best = 1');
    $goods['hot']     = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
                                    ' WHERE is_delete = 0 AND is_hot = 1');

    $time             = date('Y-m-d');
    $goods['promote'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
                                    ' WHERE is_delete = 0 AND promote_price>0' .
                                    " AND promote_start <= '$time' AND promote_end >= '$time'");

    /* 缺货商品 */
    if ($_CFG['use_storage'])
    {
        $sql = 'SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND goods_number <= warn_number';
        $goods['warn'] = $db->GetOne($sql);
    }
    else
    {
        $goods['warn'] = 0;
    }
    $smarty->assign('goods', $goods);

    /* 访问统计信息 */
    $sql         = 'SELECT COUNT(*) FROM ' .$ecs->table('stats').
                   ' WHERE access_time > ' . strtotime(date('Y-m-d'));
    $today_visit = $db->GetOne($sql);
    $smarty->assign('today_visit', $today_visit);

    $online_users = $sess->get_users_count();
    $smarty->assign('online_users', $online_users);

    /* 最近反馈 */
    $smarty->assign('feedback_number', $db->GetOne('SELECT COUNT(*) FROM ' . $ecs->table('feedback') .
                                                    ' WHERE reply = 0'));

    /* 未审核评论 */
    $smarty->assign('comment_number', $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('comment') .
                                                            ' WHERE status = 0'));

    $mysql_ver = $db->version();   // 获得 MySQL 版本

    /* 系统信息 */
    $sys_info['os']            = PHP_OS;
    $sys_info['web_server']    = $_SERVER['SERVER_SOFTWARE'];
    $sys_info['php_ver']       = PHP_VERSION;
    $sys_info['mysql_ver']     = $mysql_ver;
    $sys_info['zlib']          = function_exists('gzclose') ? $_LANG['yes']:$_LANG['no'];
    $sys_info['safe_mode']     = (boolean) ini_get('safe_mode') ?  $_LANG['yes']:$_LANG['no'];
    $sys_info['safe_mode_gid'] = (boolean) ini_get('safe_mode_gid') ? $_LANG['yes'] : $_LANG['no'];
    $sys_info['timezone']      = function_exists("date_default_timezone_get") ? date_default_timezone_get() : $_LANG['no_timezone'];
    $sys_info['socket']        = function_exists('fsockopen') ? $_LANG['yes'] : $_LANG['no'];

    if ($gd == 0)
    {
        $sys_info['gd'] = 'N/A';
    }
    else
    {
        if ($gd == 1)
        {
            $sys_info['gd'] = 'GD1';
        }
        else
        {
            $sys_info['gd'] = 'GD2';
        }

        $sys_info['gd'] .= ' (';

        /* 检查系统支持的图片类型 */
        if ($gd && (imagetypes() & IMG_JPG) > 0)
        {
            $sys_info['gd'] .= ' JPEG';
        }

        if ($gd && (imagetypes() & IMG_GIF) > 0)
        {
            $sys_info['gd'] .= ' GIF';
        }

        if ($gd && (imagetypes() & IMG_PNG) > 0)
        {
            $sys_info['gd'] .= ' PNG';
        }

        $sys_info['gd'] .= ')';
    }

    /* IP库版本 */
    include_once(ROOT_PATH . 'includes/ip/cls_ip.php');
    $ip_search  = new ip_search(ROOT_PATH);
    $ip_version = $ip_search->getlocation('255.255.255.000');
    $sys_info['ip_version'] = $ip_version['area'];

    /* 允许上传的最大文件大小 */
    $sys_info['max_filesize'] = ini_get('upload_max_filesize');

    $smarty->assign('sys_info', $sys_info);

    /* 缺货登记 */
    $smarty->assign('booking_goods', $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('booking_goods') . ' WHERE is_dispose = 0'));

    /* 退款申请 */
    $smarty->assign('new_repay', $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('user_account') . ' WHERE process_type = ' . SURPLUS_RETURN . ' AND is_paid = 0 '));

    /* 如果管理员的最后登陆时间大于24小时则检查最新版本 */
    if (time() - strtotime($_SESSION['last_check']) > (3600 * 12))
    {
        $smarty->assign('need_check_version', 1);
    }

    assign_query_info();

    $smarty->assign('ecs_version',  VERSION);
    $smarty->assign('ecs_release',  RELEASE);
    $smarty->assign('ecs_lang',     $_CFG['lang']);
    $smarty->assign('install_date', date($_CFG['date_format'], $_CFG['install_date']));
    $smarty->display('start.htm');
}

/*------------------------------------------------------ */
//-- 关于 ECSHOP
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'about_us')
{
    assign_query_info();
    $smarty->display('about_us.htm');
}

/*------------------------------------------------------ */
//-- 拖动的帧
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'drag')
{
    $smarty->display('drag.htm');;
}

/*------------------------------------------------------ */
//-- 检查订单
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'check_order')
{
    if (empty($_SESSION['last_check']))
    {
        $_SESSION['last_check'] = date('Y-m-d H:i:s');

        make_json_result('', '', array());
    }

    /* 新订单 */
    $sql = 'SELECT COUNT(*) FROM ' . $ecs->table('order_info').
            " WHERE order_time >= '$_SESSION[last_check]'";
    $arr['new_orders'] = $db->getOne($sql);

    /* 新付款的订单 */
    $sql = 'SELECT COUNT(*) FROM '.$ecs->table('order_info').
            ' WHERE pay_time >= ' . strtotime($_SESSION['last_check']);
    $arr['new_paid'] = $db->getOne($sql);

    $_SESSION['last_check'] = date('Y-m-d H:i:s');

    if (!(is_numeric($arr['new_orders']) && is_numeric($arr['new_paid'])))
    {
        make_json_error($db->error());
    }
    else
    {
        make_json_result('', '', $arr);
    }
}

?>