<?php

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

define('IN_ECS', true);

require('includes/init.php');

/*------------------------------------------------------ */
//-- 会员数据整合插件列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
    $modules = read_modules('../includes/modules/integrates');

    for ($i = 0; $i < count($modules); $i++)
    {
         $modules[$i]['installed'] = ($modules[$i]['code'] == $_CFG['integrate_code']) ? 1 : 0;
    }

    $smarty->assign('ur_here', $_LANG['06_list_integrate']);
    $smarty->assign('modules', $modules);

    assign_query_info();
    $smarty->display('integrates_list.htm');
}

/*------------------------------------------------------ */
//-- 安装会员数据整合插件
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'install')
{
    admin_priv('integrate_users', '');

    if ($_GET['code'] == 'ecshop')
    {
        $sql = "UPDATE " .$ecs->table('shop_config'). " SET value = 'ecshop' WHERE code = 'integrate_code'";
        $db->query($sql);

        /* 清除shopconfig表的sql的缓存 */
        clear_cache_files();

        $links[0]['text'] = $_LANG['go_back'];
        $links[0]['href'] = 'integrate.php?act=list';
        sys_msg($_LANG['update_success'], 0, $links);
    }
    else
    {
        include_once(ROOT_PATH."includes/modules/integrates/".$_GET['code'].".php");

        $class_vars = get_class_vars($_GET['code']);
        $cfg['db_host']       = empty($class_vars['db_host']) ? '' : $class_vars['db_host'];
        $cfg['prefix']        = empty($class_vars['prefix']) ? '' : $class_vars['prefix'];
        $cfg['cookie_prefix'] = empty($class_vars['cookie_prefix']) ? '' : $class_vars['cookie_prefix'];
        $cfg['integrate_url'] = "http://";

        /* 判断 */

        assign_query_info();

        $smarty->assign('cfg',      $cfg);
        $smarty->assign('set_list', get_charset_list());
        $smarty->assign('ur_here',  $_LANG['integrate_setup']);
        $smarty->assign('code',     $_GET['code']);
        $smarty->display('integrates_setup.htm');
    }
}

/*------------------------------------------------------ */
//-- 设置会员数据整合插件
/*------------------------------------------------------ */

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

    if ($_GET['code'] == 'ecshop')
    {
        sys_msg($_LANG['need_not_setup']);
    }
    else
    {
        $cfg = unserialize($_CFG['integrate_config']);
        assign_query_info();
        $smarty->assign('set_list', get_charset_list());
        $smarty->assign('ur_here',  $_LANG['integrate_setup']);
        $smarty->assign('code',     $_GET['code']);
        $smarty->assign('cfg',      $cfg);
        $smarty->display('integrates_setup.htm');
    }
}

/*------------------------------------------------------ */
//-- 更新会员数据整合插件的设置
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'update')
{
    $_POST['code'] = trim($_POST['code']);

    /* 当前所整合的会员插件 */
    $integrate_code = $db->getOne("SELECT value FROM " .$ecs->table('shop_config').
                                  " WHERE code = 'integrate_code'");

    /* 如果要更换其它的会员插件, 清空商城原有的会员相关数据 */
    if ($_POST['code'] <> $integrate_code)
    {
        /* 清除商城的会员相关数据, 以保证整合后会员数据的正确性 */
        $db->query("TRUNCATE TABLE ".$ecs->table('users'));
        $db->query("TRUNCATE TABLE ".$ecs->table('user_account'));
        $db->query("TRUNCATE TABLE ".$ecs->table('user_address'));
        $db->query("TRUNCATE TABLE ".$ecs->table('user_bonus'));
        $db->query("TRUNCATE TABLE ".$ecs->table('order_info'));
        $db->query("TRUNCATE TABLE ".$ecs->table('order_goods'));
        $db->query("TRUNCATE TABLE ".$ecs->table('order_action'));
        $db->query("TRUNCATE TABLE ".$ecs->table('cart'));
        $db->query("TRUNCATE TABLE ".$ecs->table('tag'));
        $db->query("TRUNCATE TABLE ".$ecs->table('booking_goods'));
        $db->query("TRUNCATE TABLE ".$ecs->table('collect_goods'));
        $db->query("TRUNCATE TABLE ".$ecs->table('feedback'));
        $db->query("TRUNCATE TABLE ".$ecs->table('snatch_log'));
    }

    /* 插入code到shop_config表 */
    $sql = "SELECT COUNT(*) FROM " .$ecs->table('shop_config'). " WHERE code = 'integrate_code'";

    if ($db->GetOne($sql) == 0)
    {
        $sql = "INSERT INTO " .$ecs->table('shop_config'). " (code, value) ".
                "VALUES ('integrate_code', '$_POST[code]')";
    }
    else
    {
        $sql = "UPDATE " .$ecs->table('shop_config'). " SET value = '$_POST[code]' WHERE code = 'integrate_code'";
    }
    $db->query($sql);

    /* 插入设置信息 */
    $arr['db_host']       = trim($_POST['db_host']);
    $arr['db_name']       = trim($_POST['db_name']);
    $arr['db_user']       = trim($_POST['db_user']);
    $arr['db_pass']       = $_POST['db_pass'];
    $arr['db_chartset']   = $_POST['db_chartset'];
    $arr['prefix']        = trim($_POST['prefix']);
    $arr['integrate_url'] = trim($_POST['integrate_url']);
    if (!empty($_POST['cookie_prefix']))
    {
        $arr['cookie_prefix']   = trim($_POST['cookie_prefix']);
    }
    /* 初始化提示信息 */
    $message = '';

    /* 当前的域名 */
    if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))
    {
        $cur_domain = $_SERVER['HTTP_X_FORWARDED_HOST'];
    }
    elseif (isset($_SERVER['HTTP_HOST']))
    {
        $cur_domain = $_SERVER['HTTP_HOST'];
    }
    else
    {
        if (isset($_SERVER['SERVER_NAME']))
        {
            $cur_domain = $_SERVER['SERVER_NAME'];
        }
        elseif (isset($_SERVER['SERVER_ADDR']))
        {
            $cur_domain = $_SERVER['SERVER_ADDR'];
        }
    }

    /* 整合对象的域名 */
    $int_domain = str_replace(array('http://', 'https://'), array('', ''), $_POST['integrate_url']);
    if (strrpos($int_domain, '/'))
    {
        $int_domain = substr($int_domain, 0, strrpos($int_domain, '/'));
    }

    if ($cur_domain != $int_domain)
    {
        $same_domain    = true;
        $domain         = '';

        /* 域名不一样，检查是否在同一域下 */
        $cur_domain_arr = explode(".", $cur_domain);
        $int_domain_arr = explode(".", $int_domain);

        if (count($cur_domain_arr) != count($int_domain_arr) || $cur_domain_arr[0] == '' || $int_domain_arr[0] == '')
        {
            /* 域名结构不相同 */
            $same_domain = false;
        }
        else
        {
            /* 域名结构一致，检查除第一节以外的其他部分是否相同 */
            $count = count($cur_domain_arr);

            for ($i = 1; $i < $count; $i++)
            {
                if ($cur_domain_arr[$i] != $int_domain_arr[$i])
                {
                    $domain         = '';
                    $same_domain    = false;
                    break;
                }
                else
                {
                    $domain .= ".$cur_domain_arr[$i]";
                }
            }
        }

        if ($same_domain == false)
        {
            /* 不在同一域，设置提示信息 */
            $message = $_LANG['different_domain'];
            $arr['cookie_domain']   = '';
            $arr['cookie_path']     = '/';
        }
        else
        {
            $arr['cookie_domain']   = $domain;
            $arr['cookie_path']     = '/';
        }
    }
    else
    {
        $arr['cookie_domain']   = '';
        $arr['cookie_path']     = '/';
    }

    /* 序列化设置信息，并保存到数据库 */
    $cfg = serialize($arr);
    $sql = "SELECT COUNT(*) FROM " .$ecs->table('shop_config'). " WHERE code='integrate_config'";

    if ($db->GetOne($sql) == 0)
    {
        $sql = "INSERT INTO " .$ecs->table('shop_config'). " (code, value) ".
                "VALUES ('integrate_config', '$cfg')";
    }
    else
    {
        $sql = "UPDATE " .$ecs->table('shop_config'). " SET value='$cfg' ".
                "WHERE code='integrate_config'";
    }
    $db->query($sql);

    /* 清除shopconfig表的sql的缓存 */
    clear_cache_files();

    /* 提示信息 */
    $links[0]['text'] = $_LANG['go_back'];
    $links[0]['href'] = 'integrate.php?act=list';
    sys_msg((empty($message) ? $_LANG['update_success'] : $message), 0, $links);
}

/*------------------------------------------------------ */
//-- 同步会员数据
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'sync')
{
    admin_priv('sync_users', '');

    /* 检查当前的整合对象是不是ecshop */
    if ($_CFG['integrate_code'] == 'ecshop')
    {
        sys_msg($_LANG['neednot_sync'], 1);
    }

    $sync_start     = (isset($_GET['sync_start']) && $_GET['sync_start'] > 0) ? $_GET['sync_start'] : 0;
    $sync_num       = (isset($_GET['sync_num']) && $_GET['sync_num'] > 0) ? $_GET['sync_num'] : 5000;
    $sync_target    = (isset($_GET['sync_target']) && $_GET['sync_target'] != '') ? $_GET['sync_target'] : 0;

    assign_query_info();
    $smarty->assign('ur_here',      $_LANG['05_synchronous']);
    $smarty->assign('sync_start',   $sync_start);
    $smarty->assign('sync_num',     $sync_num);
    $smarty->assign('sync_target',  $sync_target);

    $smarty->display('integrate_sync.htm');
}

/*------------------------------------------------------ */
//-- 同步会员数据
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'exec_sync')
{
    admin_priv('sync_users', '');

    $integrate =& init_users();

    $count = $integrate->sync($_POST['target'], $_POST['start'], $_POST['num']);

    $link[] = array('text' => $_LANG['continue_sync'],
                    'href'=>'integrate.php?act=sync&sync_start=' .($_POST['start'] + $_POST['num']).
                            '&sync_num=' .$_POST['num'].'&sync_target='.$_POST['target']);
    $link[] = array('text' => $_LANG['go_userslist'],
                    'href'=>'users.php?act=list');

    /* 获得用户记录总数 */
    $user_count = 0;
    if ($_POST['target'] == 0)
    {
        /* 同步到第三方系统 */
        $user_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('users'));
    }
    else
    {
        /* 同步到 ecshop */
        $user_count = $integrate->get_user_count();
    }

    sys_msg(sprintf($_LANG['sync_success'], $user_count, $_POST['start'], $_POST['num'], $count), 0, $link);
}

?>