<?php

/**
 * ECSHOP 会员数据处理类(DVBBS for PHP)
 * ============================================================================
 * 版权所有 (C) 2005-2007 北京亿商互动科技发展有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com
 * ----------------------------------------------------------------------------
 * 这是一个免费开源的软件；这意味着您可以在不用于商业目的的前提下对程序代码
 * 进行修改、使用和再发布。
 * ============================================================================
 * @author:     changyu hao <haochangyu@hotmail.com>
 * @version:    v2.1
 * ---------------------------------------------
 * $Author: paulgao $
 * $Date: 2007-05-22 15:26:36 +0800 (星期二, 22 五月 2007) $
 * $Id: dvbbs.php 8700 2007-05-22 07:26:36Z paulgao $
 */

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

/* 模块的基本信息 */
if (isset($set_modules) && $set_modules == TRUE)
{
    $i = (isset($modules)) ? count($modules) : 0;

    /* 会员数据整合插件的代码必须和文件名保持一致 */
    $modules[$i]['code']    = 'dvbbs';

    /* 插件名称 */
    $modules[$i]['name']    = 'DVBBS for PHP';

    /* 插件版本 */
    $modules[$i]['version'] = '1.0.x';

    /* 插件作者 */
    $modules[$i]['author']  = 'ECSHOP R&D TEAM';

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

    return;
}

class dvbbs
{
    /*------------------------------------------------------ */
    //-- PUBLIC ATTRIBUTEs
    /*------------------------------------------------------ */

    /* 整合对象使用的数据库主机 */
    var $db_host        = 'localhost';

    /* 整合对象使用的数据库名 */
    var $db_name        = 'dvbbs';

    /* 整合对象使用的数据库用户名 */
    var $db_user        = 'root';

    /* 整合对象使用的数据库密码 */
    var $db_pass        = '';

    /* 整合对象数据库使用字符集 */
    var $db_charset     = 'UTF8';

    /* 字符集转换对象 */
    var $iconv          = '';

    /* 整合对象数据表前缀 */
    var $prefix         = 'dv_';

    /* COOKIE前缀 */
    var $cookie_prefix  = 'dvbbs_';

    /* 整合对象使用的cookie的domain */
    var $cookie_domain  = '';

    /* 整合对象使用的cookie的path */
    var $cookie_path    = '/';

    /* 会员ID的字段名 */
    var $field_id   = 'userid';

    /* 会员名称的字段名 */
    var $field_name = 'username';

    /* 会员密码的字段名 */
    var $field_pass = 'userpassword';

    /* 会员mail的字段名 */
    var $field_email    = 'useremail';

    /* 会员post的字段名 */
    var $field_userpost = 'userpost';

    /* 会员类别的字段名 */
    var $field_userclass = 'userclass';

    /* 会员lock的字段名 */
    var $field_lockuser = 'lockuser';

    /* 会员是否隐身的字段名 */
    var $field_userhidden = 'userhidden';

    /* 会员所属组的字段名 */
    var $field_usergroupid = 'usergroupid';

    /* 会员加入时间的字段名 */
    var $field_reg_date = 'joindate';

    /* 会员头像字段名 */
    var $field_titlepic = 'titlepic';

    /* 会员确认密码字段名 */
    var $field_truepassword = 'truepassword';

    /* 会员最后登陆时间字段名 */
    var $field_lastlogin = 'lastlogin';

    /* 会员用户描述字段名 */
    var $field_usertitle = 'usertitle';

    /* 会员性别字段名 */
    var $field_usersex = 'usersex';

    /* 会员生日字段名 */
    var $field_bday = 'userbirthday';

    var $error = 0;

    /*------------------------------------------------------ */
    //-- PRIVATE ATTRIBUTEs
    /*------------------------------------------------------ */

    var $db;

    /*------------------------------------------------------ */
    //-- PUBLIC METHODs
    /*------------------------------------------------------ */

    /**
     * 会员数据整合插件类的构造函数
     *
     * @access      public
     * @param       string  $db_host    数据库主机
     * @param       string  $db_name    数据库名
     * @param       string  $db_user    数据库用户名
     * @param       string  $db_pass    数据库密码
     * @return      void
     */
    function dvbbs($db_host = 'localhost', $db_name = '', $db_user = 'root', $db_pass = '', $prefix = '',  $cookie_domain = '', $cookie_path = '/', $db_charset = 'UTF8')
    {
        $this->db_host = $db_host;
        $this->db_name = $db_name;
        $this->db_user = $db_user;
        $this->db_pass = $db_pass;
        $this->prefix = $prefix;
        $this->db_charset = $db_charset;

        /* 获得cookie的域名和路径 */
        $this->cookie_domain = $cookie_domain;
        $this->cookie_path   = $cookie_path;

        /* 开始连接数据库 */
        $this->db = new cls_mysql($db_host, $db_user, $db_pass, $db_name);
        $this->db->set_mysql_charset($this->db_charset);

        /* 如果整合对象编码不为UTF-8 则初始化转码对象 */
        if ($db_charset != 'UTF8')
        {
            include_once(ROOT_PATH.'includes/iconv/cls_iconv.php');
            $this->iconv = new Chinese(ROOT_PATH);
        }
    }

    /*获取字段名称的函数*/
    function table($str)
    {
        return '`' . $this->db_name . '`.`' . $this->prefix . $str . '`';
    }

    /**
     * 将整合论字符集转换成UTF-8编码
     * 可以转换数组
     *
     * @access  public
     * @param   mix     $arr
     * @return  mix
     */
    function convert($data)
    {
        if (!empty($this->iconv) && $this->db_charset != 'UTF8')
        {
            if (is_array($data))
            {
                foreach ($data as $key => $value)
                {
                    if (is_array($value))
                    {
                        $data[$key] = $this->convert($value);
                    }
                    else
                    {
                        $data[$key] = $this->iconv->convert($this->db_charset,'UTF8',$value);
                    }
                }
            }
            else
            {
                $data = $this->iconv->convert($this->db_charset,'UTF8',$data);
            }
        }

        return $data;
    }

    /**
     * 将UTF-8字符转换整合对象字符集
     * 可以转换数组
     *
     * @access  public
     * @param   mix     $arr
     * @return  mix
     */
    function convert_to($data)
    {
        if (!empty($this->iconv) && $this->db_charset != 'UTF8')
        {
            if (is_array($data))
            {
                foreach ($data as $key => $value)
                {
                    if (is_array($value))
                    {
                        $data[$key] = $this->convert_to($value);
                    }
                    else
                    {
                        $data[$key] = $this->iconv->convert('UTF8',$this->db_charset,$value);
                    }
                }
            }
            else
            {
                $data = $this->iconv->convert('UTF8',$this->db_charset,$data);
            }
        }

        return $data;
    }

    /**
     * 根据用户名、密码验证用户身份的函数
     *
     * @param       string      username    用户名
     * @param       string      password    登录密码
     *
     * @return bool
     */
    function login($username, $password)
    {
        /* 字符集转换 */
        $uname = $this->convert_to($username);

        $sql = "SELECT " . $this->field_id . ", " . $this->field_name . ", ". $this->field_pass . ", " . $this->field_userpost . ", " . $this->field_userclass . ", " . $this->field_lockuser . ", " . $this->field_userhidden . ", " . $this->field_reg_date . ", " . $this->field_usergroupid . ", " . $this->field_titlepic . ", " . $this->field_truepassword . ", " . $this->field_lastlogin . ", " . $this->field_usertitle . ", " . $this->field_userpost . ", " . $this->field_email . " FROM " . $this->table('user') . " WHERE " . $this->field_name . " = '$uname'"." AND " . $this->field_pass . " = '" .$this->compile_password($password)."'";
        $row = $this->db->getRow($sql);

        if ($row)
        {
            if (empty($this->field_lockuser))
            {
                return false;
            }
            else
            {
                /* 登录成功 */
                $this->set_cookie($row[$this->field_id], $row[$this->field_truepassword], $row[$this->field_name], $row[$this->field_userhidden]);
                $this->set_user_session($row[$this->field_id], $username, $row[$this->field_email]);
                $this->user_sync($row[$this->field_id], $username);

                return true;
            }
         }
         else
         {
            return false;
         }
    }

    /**
     * 根据cookie来验证用户身份的函数
     *
     * @access      public
     * @return      void
     */
    function get_cookie()
    {
        $dvbbs_userid   = $this->cookie_prefix . 'userid';
        $dvbbs_username = $this->cookie_prefix . 'username';
        $dvbbs_password = $this->cookie_prefix . 'password';

        if (empty($_COOKIE[$dvbbs_userid]) && empty($_COOKIE[$dvbbs_username]))
        {
            return false;
        }

        $sql = "SELECT " . $this->field_id . ", " . $this->field_name . ", " . $this->field_email . ", " .$this->field_truepassword. ", userhidden".
               " FROM " . $this->table('user') .
               " WHERE " . $this->field_id . " = '" . $_COOKIE[$dvbbs_userid] . "'".
               " AND " . $this->field_truepassword . " = '" . $_COOKIE[$dvbbs_password] . "'";
        $row = $this->db->GetRow($sql);

        if ($row)
        {
            /* 登陆成功 */
            //$this->set_cookie($row[$this->field_id], $row[$this->field_truepassword], $row[$this->field_name], $row['userhidden']);
            $username = $this->convert($row[$this->field_name]);
            $this->set_user_session($row[$this->field_id], $username, $row[$this->field_email]);
            $this->user_sync($row[$this->field_id], $username);

            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 用户退出
     *
     * @access      public
     * @return      void
     */
    function logout()
    {
         $dvbbs_userid   = $this->cookie_prefix . 'userid';
         $dvbbs_username = $this->cookie_prefix . 'username';
         $dvbbs_password = $this->cookie_prefix . 'password';
         $dvbbs_userhidden = $this->cookie_prefix . 'userhidden';
         $dvbbs_onlinecachetime = $this->cookie_prefix . 'onlinecachetime';

        /* 删除论坛表相关数据 */
        if ($_COOKIE[$dvbbs_userid] > 0)
        {
            $this->db->query("DELETE FROM " . $this->table('online'). " WHERE id='$_COOKIE[$dvbbs_userid]'");
            $this->db->query("UPDATE " . $this->table('user'). " SET userhidden=1 WHERE userid = '$_COOKIE[$dvbbs_userid]'");
        }

        $time = time() - 3600 * 24 * 30;
        setcookie($dvbbs_password, '', $time, $this->cookie_path, $this->cookie_domain);
        setcookie($dvbbs_userid, '', $time, $this->cookie_path, $this->cookie_domain);
        setcookie($dvbbs_username, '', $time, $this->cookie_path, $this->cookie_domain);
        setcookie($dvbbs_userhidden, '', $time, $this->cookie_path, $this->cookie_domain);
        setcookie($dvbbs_onlinecachetime, '', $time, $this->cookie_path, $this->cookie_domain);

        /* 清除session */
        $GLOBALS['sess']->destroy_session();
    }

    /**
     * 设置cookie
     *
     * @access      private
     * @param       int         user_id         用户编号
     * @param       string      user_password   登录密码
     * @param       string      salt            加密串
     * @return      void
     */
    function set_cookie($user_id, $user_password, $user_name, $user_hidden)
    {
         $dvbbs_userid   = $this->cookie_prefix . 'userid';
         $dvbbs_username = $this->cookie_prefix . 'username';
         $dvbbs_password = $this->cookie_prefix . 'password';
         $dvbbs_userhidden = $this->cookie_prefix . 'userhidden';

        $time = time() + 3600 * 24 * 30;
        setcookie($dvbbs_userid, $user_id, $time, $this->cookie_path, $this->cookie_domain);
        setcookie($dvbbs_password, $user_password, $time, $this->cookie_path, $this->cookie_domain);
        setcookie($dvbbs_username, $user_name, $time, $this->cookie_path, $this->cookie_domain);
        setcookie($dvbbs_userhidden, $user_hidden, $time, $this->cookie_path, $this->cookie_domain);
    }

    /**
     * 添加新用户的函数
     *
     * @access      public
     * @param       string      username    用户名
     * @param       string      password    登录密码
     * @param       string      email       邮件地址
     * @return      int         返回最新的ID
     */
    function add_user($username, $password, $email)
    {
        $username = $this->convert_to($username);

        /* 检查用户名是否已经存在 */
        $sql = 'SELECT COUNT(*) FROM ' . $this->table('user') .' WHERE ' .$this->field_name. " = '$username'";

        if ($this->db->GetOne($sql) > 0)
        {
            $this->error = ERR_USERNAME_EXISTS;

            return false;
        }

        /* 检查邮件地址是否重复 */
        $sql = 'SELECT COUNT(*) FROM ' . $this->table('user') .' WHERE ' . $this->field_email . " = '$email'";

        if ($this->db->GetOne($sql) > 0)
        {
            $this->error = ERR_EMAIL_EXISTS;

            return false;
        }

        /* 编译密码 */
        $password = $this->compile_password($password);

        /*生成验证码*/
        $truepassword = $this->Createpass(16);

        /* 插入数据库 */
        $sql = 'INSERT INTO ' . $this->table('user') . '(' .$this->field_name . ', ' . $this->field_pass . ', '.$this->field_truepassword . ', '. $this->field_email . ',' . $this->field_reg_date . ' ) VALUES ( ' . "'$username', '$password', ' $truepassword ', '$email', " . time() . ')';

        $res = $this->db->query($sql);
         if ($res)
         {
             $new_id = $this->db->Insert_ID();

             return $new_id;
         }
         else
         {
             $this->error = ERR_USERNAME_EXISTS;

             return false;
         }
    }

    /**
     * 编辑用户帐号信息的函数
     *
     * @access      public
     * @param       int         $user_id        用户编号
     * @param       string      $username       用户名
     * @param       string      $email          邮件地址
     * @return      bool
     */
    function edit_user($user_id, $username = '', $email = '')
    {
        $fields = '';
        if (!empty($username))
        {
            $username = $this->convert_to($username);

            /* 检查用户名是否重复 */
            $sql = 'SELECT COUNT(*) FROM ' . $this->table('user') . ' WHERE ' . $this->field_name . " = '$username' AND " . $this->field_id . " <> '$user_id' ";

            if ($this->db->GetOne($sql))
            {
                $this->error = ERR_USERNAME_EXISTS;

                return false;
            }
            else
            {
                $fields .= $this->field_name . " = '$username'";
            }
        }

       if (!empty($email))
       {
           /* 检查邮件地址是否重复 */
           $sql = 'SELECT COUNT(*) FROM ' . $this->table('user') .' WHERE ' . $this->field_email . " = '$email' AND " . $this->field_id . " <> '$user_id'";

           if ($this->db->GetOne($sql))
           {
               $this->error = ERR_EMAIL_EXISTS;

               return false;
            }
            else
            {
                $fields .= (empty($fields)) ? '' : ',';
                $fields .= $this->field_email . " = '$email'";
            }
       }

       $sql = 'UPDATE ' . $this->table('user') . " SET $fields WHERE " . $this->field_id . " = '$user_id'";
       $this->db->query($sql);

       return true;
    }

    /**
     * 删除用户帐号
     *
     * @access      public
     * @param       mix     users   用户编号
     * @return      bool
     */
    function remove_user($users)
    {
        $where = is_array($users) ? $this->field_id . db_create_in($users) : $this->field_id . " = '$users'";
        $sql = 'DELETE FROM ' . $this->table('user') . " WHERE $where";

        return $this->db->query($sql);
    }

    /**
     * 编辑用户密码的函数
     * 在这个函数里判断用户输入的原来的密码是否正确，如果不正确则返回FALSE
     *
     * @access      public
     * @param       int         user_id         用户编号
     * @param       string      password        原来的登录密码
     * @param       string      new_password    新的登录密码
     * @param       string      code            附加的
     * @return      void
     */
    function edit_password($user_id, $password, $new_password)
    {
        /* 比较原密码是否相符 */
        $sql = 'SELECT COUNT(*) FROM ' . $this->table('user') ." WHERE $this->field_id = '$user_id'" . " AND $this->field_pass = '" .$this->compile_password($password) . "'";

        if ($GLOBALS['db']->getOne($sql) == 0)
        {
            return false;
        }

        if (!$this->update_password($user_id, $new_password))
        {
            return false;
         }
         else
         {
             return true;
         }
    }

    /**
     * 找回用户密码的函数
     *
     * @access      public
     * @param       int         user_id         用户编号
     * @param       string      code            验证串
     * @param       string      new_password    新的登录密码

     * @return      void
     */
    function fetch_password($user_id, $code, $new_password)
    {
        /* 比较code是否合法 */
        $sql = "SELECT $this->field_pass FROM " . $this->table('user') . " WHERE $this->field_id = '$user_id'";
        $password = $this->db->getOne($sql);
        $md5_password = md5($user_id . $password);

        if ($md5_password <> $code)
        {
            return false;
        }

        if (!$this->update_password($user_id, $new_password))
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    /*生成加密密码*/
    function compile_password($str)
    {
        return substr(md5($str), 8, 16);
    }

    /**
     * 更新用户密码的函数
     *
     * @access      private
     * @param       int         user_id         用户编号
     * @param       string      new_password    新的登录密码
     * @return      void
     */
    function update_password($user_id, $new_password)
    {
         if (empty($user_id) || empty($new_password))
         {
             return false;
         }

         /* 更新密码 */
         $sql = 'UPDATE ' . $this->table('user') . ' SET ' ."$this->field_pass = '" . $this->compile_password($new_password) . "' ". "WHERE $this->userid = '$user_id'";
         $result = $this->db->query($sql);

         if ($result)
         {
             return true;
         }
         else
         {
             return false;
         }
    }

    /**
     * 获得用户总数
     *
     * @access      public
     * @param       string      查询的关键字
     * @return      int
     */
    function get_user_count($keyword = '', $ex_where = '')
    {
        $sql = 'SELECT COUNT(*) FROM ' . $this->table('user');

        if (!empty($keyword))
        {
            $keyword = $this->convert_to($keyword);
            $sql .= ' AND ' . $this->field_name . " LIKE '%$keyword%'";
        }

        if (!empty($ex_where))
        {
            $sql .= ' AND ' . $this->field_id . $ex_where;
        }

        return $this->db->GetOne($sql);
    }

    /**
     * 获得指定用户的帐号信息
     *
     * @access: public
     * @param:  int     $id     会员编号
     *
     * @return  array
     */
    function get_user_info($id)
    {
        $sql = 'SELECT ' . $this->field_name . ', ' .$this->field_email .' FROM ' . $this->table('user') . ' WHERE ' . $this->field_id . " = '$id'";
        $row = $this->db->GetRow($sql);

        $row[$this->field_name] = $this->convert($row[$this->field_name]);

        $arr['user_id']  = $id;
        $arr['username'] = $row ? htmlspecialchars($row[$this->field_name]) : '';
        $arr['email']    = $row ? htmlspecialchars($row[$this->field_email]) : '';
        $arr['question'] = '';
        $arr['answer']   = '';

        return $arr;
    }

    /**
     * 会员列表列表函数
     *
     * @access      public
     * @param       int     page      当前的页数
     * @param       int     limit     记录总数
     * @return      mysql result
     */
    function &get_users($page = 1, $limit = 15, $sort = 'userid', $order = 'DESC', $keywords = '', $ex_where = '')
    {
        $start = ($page - 1) * $limit;
        $where = ' WHERE 1 ';

        if (!empty($keywords))
        {
            $keywords = $this->convert_to($keywords);
            $where .= ' AND ' . $this->field_name . " LIKE '%$keywords%' ";
        }

        if (!empty($ex_where))
        {
            $where .= ' AND ' . $this->field_id . $ex_where;
        }

        $sql = 'SELECT * FROM ' . $this->table('user') . " $where " ."ORDER BY $sort $order, " . $this->field_reg_date . ' DESC';
        $res = $this->db->SelectLimit($sql, $limit, $start);

        $list = array();
        while ($row = $this->db->fetchRow($res))
        {
            $list[] = array($this->field_id   => $row[$this->field_id],
                            $this->field_name => $this->convert($row[$this->field_name]),
                            $this->field_email    => $row[$this->field_email],
                            $this->field_reg_date => $row[$this->field_reg_date]
                        );
        }

        return $list;
    }

    /**
     * 实现单个用户同步，如果商城不存在某用户id就在商城插入一条记录，记录用户id保持一致。
     * 否则什么也不做。
     *
     * @access  public
     * @param
     *
     * @return void
     */
    function user_sync($user_id, $user_name)
    {
         $sql = "SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('users').
               " WHERE user_id = '$user_id' AND user_name = '$user_name'";
        if ($GLOBALS['db']->getOne($sql) == 0)
        {
            $sql = "SELECT `$this->field_name`, `$this->field_email`, `$this->field_pass`,  `$this->field_reg_date`, `$this->field_usersex`, `$this->field_truepassword`, `$this->field_bday`".
                   " FROM " . $this->table('user') . " WHERE `userid` = '$user_id'";

            $result = $this->db->getRow($sql);
            if ($result)
            {
                $result[$this->field_name] = $this->convert($result[$this->field_name]);

                $sql = "INSERT INTO ".$GLOBALS['ecs']->table('users')." (`user_id`, `user_name`, `email`, `password`, `reg_time`, `sex`, `birthday`) VALUES ('$user_id', '".$result[$this->field_name]."', '".$result[$this->field_email]."', '".$result[$this->field_truepassword].$result[$this->field_pass]."', '".$result[$this->field_reg_date]."', '".$result[$this->field_usersex]."', '".$result[$this->field_bday]."')";

                return $GLOBALS['db']->query($sql);
            }
        }

        return false;
    }

    /**
     * 设置用户session
     *
     * @access  public
     * @param
     *
     * @return void
     */
    function set_user_session($user_id, $user_name, $email)
    {
        $_SESSION['user_id']   = $user_id;
        $_SESSION['user_name'] = $user_name;
        $_SESSION['email']     = $email;
    }

   /*生成truepassword验证码 */
   function Createpass($length, $numeric = 0)
   {
       if ($numeric)
       {
           mt_srand((double)microtime() * 1000000);
           $string = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
       }
       else
       {
           srand(date('s'));
           $possible_charactors = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
           $string = '';

           while (strlen($string) < $length)
           {
               $string .= $possible_charactors{(rand()%(strlen($possible_charactors)))};
           }
       }

        return $string;
    }

    /**
     * 检验在找回密码输入的用户名和email是否匹配
     *
     * @access      public
     * @param       int         user_name        用户名
     * @param       string      email            email
     * @return      array
     */
    function check_pwd_info($user_name, $email)
    {
        $sql = "SELECT ".$this->field_id.", ".$this->field_pass." FROM " .$this->table('user').
                " WHERE ".$this->field_name." = '$user_name' AND ".$this->field_email." = '$email'";
        $res = $this->db->getRow($sql);
        if ($res)
        {
            $res[0] = $res[$this->field_id];
            $res[1] = $res[$this->field_pass];

            return $res;
        }
        else
        {
            return false;
        }
    }

    /**
     * 检验从邮件地址链接过来的code是否合法
     *
     * @access      public
     * @param       int         user_id        用户ID
     * @param       string      code           code值
     * @return      array
     */
    function check_param($user_id, $code)
    {
        /* 比较code是否合法 */
        $sql = "SELECT ".$this->field_pass." FROM " .$this->table('user').
               " WHERE ".$this->field_id." = '$user_id'";
        $password = $this->db->getOne($sql);

        $md5_password = md5($user_id . $password);
        if ($md5_password <> $code)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

?>