<?php

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

if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}

/*
 * 模块的基本信息
*/

define('VIRTUAL_CARD_CODE', 'virtual_card');
define('VIRTUAL_CARD_VER',  1.0);

global $_LANG;
include_once(ROOT_PATH .'plugins/'. VIRTUAL_CARD_CODE .'/languages/common_'. $GLOBALS['_CFG']['lang']. '.php');

if (isset($set_modules) && $set_modules == TRUE)
{
    $i = (isset($modules)) ? count($modules) : 0;

    /* 插件的代码必须和目录名保持一致 */
    $modules[$i]['code']    = VIRTUAL_CARD_CODE;

    /* 插件的版本 */
    $modules[$i]['version'] = VIRTUAL_CARD_VER;

    /* 插件的描述 */
    $modules[$i]['desc']    = 'virtual_card_desc';

    /* 插件的作者 */
    $modules[$i]['author']  = "ECSHOP TEAM";

    /* 插件作者的官方网站 */
    $modules[$i]['website'] = "http://www.ecshop.com";

    return;
}

/*------------------------------------------------------ */
//-- 插件类
/*------------------------------------------------------ */
class virtual_card
{
    /**
     * 错误信息
     *
     * @var integer     $error
     */
    var $error      = '';

    /**
     * 插件代码
     *
     * @var string      $_code
     */
    var $code       = VIRTUAL_CARD_CODE;

    /**
     * 插件版本
     *
     * @var float       $version
     */
    var $version    = VIRTUAL_CARD_VER;

    /**
     * 是否需要为模板赋值
     *
     * @var integer     $assign
     */
    var $assign     = 0;

    /**
     * 调用的library
     *
     * @var string      $library
     */
    var $library    = '';

    /**
     * 构造函数
     *
     * @access  public
     * @return  void
     */
    function virtual_card()
    {
    }

    function __construct()
    {
        $this->virtual_card();
    }

    /**
     * 安装插件。将文件复制到相应的目录，同时创建数据表
     *
     * @access  public
     * @return  boolean
     */
    function install()
    {
        $this->error = '';

        if (file_mode_info(ROOT_PATH .'admin') < 6)
        {
            $this->error = sprintf($GLOBALS['_LANG']['dir_readonly'], 'admin');

            return false;
        }

        /* 创建数据表 */
        $sql1 = "CREATE TABLE ".$GLOBALS['ecs']->table('virtual_card')." (".
                "`card_id` mediumint(8) NOT NULL auto_increment,".
                "`goods_id` mediumint(8) unsigned NOT NULL default '0',".
                "`card_sn` varchar(60) NOT NULL default '',".
                "`card_password` varchar(60) NOT NULL default '',".
                "`add_date` int(11) NOT NULL default '0',".
                "`end_date` int(11) NOT NULL default '0',".
                "`is_saled` tinyint(1) NOT NULL default '0',".
                "`order_sn` varchar(20) NOT NULL default '',".
                "`crc32` int(11) NOT NULL default '0'," .
                "PRIMARY KEY  (`card_id`),".
                "KEY `goods_id` (`goods_id`),".
                "KEY `car_sn` (`card_sn`),".
                "KEY `is_saled` (`is_saled`)".
                ") TYPE=MyISAM ;";

        $sql2 = "INSERT INTO ".$GLOBALS['ecs']->table('mail_templates')." (`template_code`, `is_html`, `template_subject`, `template_content`, `last_modify`) ".
                "VALUES ('virtual_card', 0, '虚拟卡片', ".
                "'亲爱的{\$order.consignee}。你好！\n\n您的订单{\$order.order_sn}中{\$virtual_card.goods_name} 商品的详细信息如下:\n卡号为:         {\$virtual_card.card_sn}\n卡片密码:       {\$virtual_card.card_password}\n卡片截至日期:    {\$virtual_card.end_date}\n\n\n再次感谢您对我们的支持。欢迎您的再次光临。 \n\n{\$shop_name}\n{\$send_date}', '".time()."') ";

        /* 如果mysql版本大于4.1必须指定字符集 */
        if ($GLOBALS['db']->version() > '4.1')
        {
            $sql1 = str_replace("TYPE=MyISAM", 'ENGINE=MyISAM DEFAULT CHARSET=utf8', $sql1);
        }

        $GLOBALS['db']->query("DROP TABLE IF EXISTS ".$GLOBALS['ecs']->table('virtual_card'));
        $GLOBALS['db']->query($sql1);
        $GLOBALS['db']->query($sql2);

        if ($GLOBALS['db']->errno() > 0)
        {
            if (DEBUG_MODE)
            {
                die($GLOBALS['db']->errorMsg());
            }
            else
            {
                $this->error = $GLOBALS['_LANG']['create_table_failed'];

                return false;
            }
        }

        /* 将文件复制到相应的目录 */
        if (@!copy(ROOT_PATH. '/plugins/virtual_card/admin/virtual_card.php', ROOT_PATH .'admin/virtual_card.php'))
        {
            $this->error = sprintf($GLOBALS['_LANG']['file_readonly'], 'admin');

            return false;
        }

        return true;
    }

    /**
     * 卸载插件，删除所有文件，同时删除数据表
     *
     * @access  public
     * @return  boolean
     */
    function uninstall()
    {
        /* 删除表及相关记录 */
        $GLOBALS['db']->query("DROP TABLE IF EXISTS ".$GLOBALS['ecs']->table('virtual_card'));

        $sql = 'DELETE FROM '.$GLOBALS['ecs']->table('mail_templates').
               " WHERE template_code = 'virtual_card'";
        $GLOBALS['db']->query($sql);

        /* 删除文件 */
        @unlink('virtual_card.php');

        /* 检查是否虚拟卡商品 */
        $sql = 'SELECT COUNT(*) FROM ' .$GLOBALS['ecs']->table('goods').
               " WHERE is_real = 0 AND extension_code = 'virtual_card'";
        $num = $GLOBALS['db']->getOne($sql);
        if ($num > 0)
        {
            $links[] = array('text' => $GLOBALS['_LANG']['remove_goods'], 'href'=>'?act=remove&confirm=1&code=virtual_card');
            $links[] = array('text' => $GLOBALS['_LANG']['remove_cancel'], 'href'=>'javascript:history.go(-1)');

            sys_msg(sprintf($GLOBALS['_LANG']['virtual_goods_not_null'], $num), 2, $links, false);
        }

        return true;
    }

    /**
     * 插件升级
     *
     * @access  public
     * @param   float   $old_version
     * @return  boolean
     */
    function upgrade($old_version = 1.0)
    {
        if (file_mode_info(ROOT_PATH .'admin') < 6)
        {
            $this->error = sprintf($_LANG['dir_readonly'], 'admin');

            return false;
        }

        @chmod(ROOT_PATH. 'admin/virtual_card.php', 0777);

        /* 将文件复制到相应的目录 */
        if (@!copy(ROOT_PATH. 'plugins/virtual_card/admin/virtual_card.php', ROOT_PATH. 'admin/virtual_card.php'))
        {
            $this->error = sprintf($GLOBALS['_LANG']['file_readonly'], ROOT_PATH. 'admin/virtual_card.php');

            return false;
        }

        return true;
    }

    /**
     * 分配变量
     *
     * @access  public
     * @param   object  $smarty
     * @return  void
     */
    function assign_val(&$smarty)
    {
        $smarty->assign($this->code, '');
    }

    /**
     * 虚拟商品发货。
     *
     * @access  public
     * @param   integer     $goods_id       商品编号
     * @param   array       $order          订单信息
     * @param   string      $msg            出错信息
     * @return  void
     */
    function shipping($goods, $order_sn, &$msg)
    {
        /* 包含加密解密函数所在文件 */
        include_once(ROOT_PATH . 'includes/lib_code.php');

        /* 检查有没有缺货 */
        $sql = "SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('virtual_card')." WHERE goods_id = '$goods[goods_id]' AND is_saled = 0 ";
        $num = $GLOBALS['db']->GetOne($sql);

        if ($num < $goods['num'])
        {
            $msg .= sprintf($GLOBALS['_LANG']['virtual_card_oos'], $goods['goods_name']);

            return false;
        }


        /* 更新商品数量,先减了库存，发送邮件时间可能太长 */
        $num = $num - $goods['num'];
        $sql = "UPDATE ".$GLOBALS['ecs']->table('goods'). " SET goods_number = '$num' WHERE goods_id = '$goods[goods_id]'";
        $GLOBALS['db']->query($sql);

        /* 取得订单信息 */
        $sql = "SELECT order_id, order_sn, consignee, email FROM ".$GLOBALS['ecs']->table('order_info'). " WHERE order_sn = '$order_sn'";
        $order = $GLOBALS['db']->GetRow($sql);
        if (empty($order))
        {
            $msg .= $GLOBALS['db']->error();

            return false;
        }

        for ($i = 0; $i < $goods['num']; $i++)
        {
            /* 获取卡号信息 */
            $sql = "SELECT card_id, card_sn, card_password, end_date, crc32 FROM ".$GLOBALS['ecs']->table('virtual_card')." WHERE goods_id = '$goods[goods_id]' AND is_saled = 0";
            $virtual_card = $GLOBALS['db']->GetRow($sql);
            if (!$virtual_card)
            {
                $msg .= sprintf($GLOBALS['_LANG']['get_virtual_card_error'],$goods['goods_name']);

                return false;
            }
            $virtual_card['end_date'] = date($GLOBALS['_CFG']['date_format'], $virtual_card['end_date']);
            $virtual_card['goods_name'] = $goods['goods_name'];

            /* 卡号和密码解密 */
            if ($virtual_card['crc32'] == 0 || $virtual_card['crc32'] == crc32(AUTH_KEY))
            {
                $virtual_card['card_sn'] = decrypt($virtual_card['card_sn']);
                $virtual_card['card_password'] = decrypt($virtual_card['card_password']);
            }
            elseif ($virtual_card['crc32'] == crc32(OLD_AUTH_KEY))
            {
                $virtual_card['card_sn'] = decrypt($virtual_card['card_sn'], OLD_AUTH_KEY);
                $virtual_card['card_password'] = decrypt($virtual_card['card_password'], OLD_AUTH_KEY);
            }
            else
            {
                $msg .= 'error key';

                return false;
            }

           /* 先标记卡片有错误，然后发送邮件，邮件是否发送成功可以忽略 */
            $sql = "UPDATE ".$GLOBALS['ecs']->table('virtual_card')." SET ".
                   "is_saled = 1 ,".
                   "order_sn = '".$order['order_sn']."' ".
                   "WHERE card_id = '".$virtual_card['card_id']."'";
            if (!$GLOBALS['db']->query($sql, 'SILENT'))
            {
                $msg .= $GLOBALS['db']->error();

                return false;
            }

            /* 更新订单中发货数量 */
            $sql = "UPDATE ".$GLOBALS['ecs']->table('order_goods'). " SET ".
                   "send_number = send_number + 1 ".
                   "WHERE order_id = '$order[order_id]' AND goods_id = '$goods[goods_id]' ";
            if (!$GLOBALS['db']->query($sql, 'SILENT'))
            {
                $msg .= $GLOBALS['db']->error();

                return false;
            }

            /* 发送邮件 */
            $GLOBALS['smarty']->assign('virtual_card',                   $virtual_card);
            $GLOBALS['smarty']->assign('order',                          $order);

            $GLOBALS['smarty']->assign('send_time', date('Y-m-d H:i:s'));
            $GLOBALS['smarty']->assign('shop_name', $GLOBALS['_CFG']['shop_name']);
            $GLOBALS['smarty']->assign('send_date', date('Y-m-d'));
            $GLOBALS['smarty']->assign('sent_date', date('Y-m-d'));

            $content = $GLOBALS['smarty']->fetch("db:virtual_card");
            $tpl = get_mail_template('virtual_card');
            if (!send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']))
            {
                $msg .= sprintf($GLOBALS['_LANG']['virtual_card_send_card_fail'], $goods['goods_name']);
                //return false; //邮件发送失败不算错误
            }
        }

        return true;
    }

    /**
     * 虚拟商品在订单中显示结果
     *
     * @access  public
     * @param
     *
     * @return void
     */
    function result($order_sn, $goods)
    {
        /* 包含加密解密函数所在文件 */
        include_once(ROOT_PATH . 'includes/lib_code.php');

        /* 获取已经发送的卡片数据 */
        $sql = "SELECT card_sn, card_password, end_date, crc32 FROM ".$GLOBALS['ecs']->table('virtual_card')." WHERE goods_id= '$goods[goods_id]' AND order_sn = '$order_sn' ";
        $res= $GLOBALS['db']->query($sql);

        $str = '';
        while ($row = $GLOBALS['db']->FetchRow($res))
        {
            /* 卡号和密码解密 */
            if ($row['crc32'] == 0 || $row['crc32'] == crc32(AUTH_KEY))
            {
                $row['card_sn'] = decrypt($row['card_sn']);
                $row['card_password'] = decrypt($row['card_password']);
            }
            elseif ($row['crc32'] == crc32(OLD_AUTH_KEY))
            {
                $row['card_sn'] = decrypt($row['card_sn'], OLD_AUTH_KEY);
                $row['card_password'] = decrypt($row['card_password'], OLD_AUTH_KEY);
            }
            else
            {
                $row['card_sn'] = '***';
                $row['card_password'] = '***';
            }

            $str .= '<tr><td>'.$goods['goods_name'].'</td><td colspan="3"><strong>'.$GLOBALS['_LANG']['card_sn'].':</strong>'.$row['card_sn'];
            $str .= empty($row['card_password'])?'':'&nbsp;&nbsp;&nbsp;&nbsp;<strong>'.$GLOBALS['_LANG']['card_password'].':</strong>'.$row['card_password'];
            $str .= empty($row['end_date'])?'':'&nbsp;&nbsp;&nbsp;&nbsp;<strong>'.$GLOBALS['_LANG']['end_date'].':</strong>'.date($GLOBALS['_CFG']['date_format'], $row['end_date']);
            $str .='</td></tr>'."\n";
        }

        return $str;
    }
}

?>