<?php

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

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

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

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

    /* 被整合的第三方程序的名称 */
    $modules[$i]['name']    = "BMForum";

    /* 被整合的第三方程序的版本 */
    $modules[$i]['version'] = "5.5";

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

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

    return;
}

class bmforum
{
    /*------------------------------------------------------ */
    //-- PUBLIC ATTRIBUTEs
    /*------------------------------------------------------ */

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

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

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

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

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

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

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

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

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

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

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

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

    /* 会员邮箱的字段名 */
    var $field_email    = 'mailadd';

    /* 注册日期的字段名 */
    var $field_reg_date = 'regdate';

    /* 性别字段名 */
    var $gender         = 'sex';

    /* 生日的字段名 */
    var $bday           = 'birthday';

    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 bmforum($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->cookie_domain = $cookie_domain;
        $this->cookie_path   = $cookie_path;
        $this->db_charset    = $db_charset;

        $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_PAH . 'includes/iconv/cls_iconv.php');
            $this->iconv = new Chinese(ROOT_PAH);
        }
    }
    /**
     * 将整合论字符集转换成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      $user_name    用户名
     * @param       string      $password    登录密码
     *
     * @return bool
     */
    function login($user_name, $password)
    {
        /* 字符集转换 */
        $username = $this->convert_to($user_name);

        /* 查询用户数据 */
        $sql = "SELECT userid, username, pwd, mailadd, ugnum FROM ".$this->table('userlist').
               " WHERE " .$this->field_name." = '" .$username. "' AND ".
                          $this->field_pass." = '".$this->comiple_password($password)."'";
        $row = $this->db->getRow($sql);

        if ($row)
        {
            /* 登陆成功:设置cookie,SESSION,同步数据 */
            $this->set_cookie($row[$this->field_id], $row[$this->field_pass]);
            $this->set_user_session($row[$this->field_id], $user_name, $row[$this->field_email]);
            $this->user_sync($row[$this->field_id], $user_name);

            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 根据cookie来验证用户身份的函数
     *
     * @access      public
     * @return      void
     */
    function get_cookie()
    {
        if (isset($_COOKIE['bmforumerboardidnum']) && isset($_COOKIE['bmforumerboardpbmfym']))
        {
            /* 查询数据,设置session. */
            $sql = "SELECT userid, username, mailadd, pwd FROM ".$this->table('userlist').
                   " WHERE " .$this->field_id." = '".$_COOKIE['bmforumerboardidnum']."'".
                   " AND " . $this->field_pass . "= '" .$_COOKIE['bmforumerboardpbmfym']."'" ;
            $row = $this->db->GetRow($sql);
            if ($row)
            {
                $this->set_cookie($row['userid'], $row['pwd']);

                /* 登陆成功 */
                $row[$this->field_name] = $this->convert($row[$this->field_name]);
                $this->set_user_session($row[$this->field_id], $row[$this->field_name], $row[$this->field_email]);
                $this->user_sync($row[$this->field_id], $row[$this->field_name]);

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

    /**
     * 用户退出
     *
     * @access      public
     * @return      void
     */
    function logout()
    {
        /* 清除cookie */
        setcookie('bmforumerboardidnum', '', time() - 3600, $this->cookie_path, $this->cookie_domain);
        setcookie('bmforumerboardpbmfym', '', time() - 3600, $this->cookie_path, $this->cookie_domain);
        setcookie('bmsess', '', time() - 3600, $this->cookie_path, $this->cookie_domain);
        setcookie('cookie_time_bmb', '', time() - 3600, $this->cookie_path, $this->cookie_domain);
        setcookie('privacybym', '', time() - 3600, $this->cookie_path, $this->cookie_domain);
        setcookie('TNM', '', time() - 3600, $this->cookie_path, $this->cookie_domain);
        setcookie('close_ajax', '', time() - 3600, $this->cookie_path, $this->cookie_domain);
        setcookie('bmbskin', '', time() - 3600, $this->cookie_path, $this->cookie_domain);

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

    /**
     * 登录密码的加密算法
     *
     * @access      private
     * @param       string      password        用户的原始密码
     * @return      string
     */
    function comiple_password($password)
    {
        return md5($password);
    }

    /**
     * 设置用户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;
    }

    /**
     * 实现单个用户同步，如果商城不存在某用户id就在商城插入一条记录，记录用户id保持一致。
     * 否则什么也不做。
     *
     * @access  public
     * @param
     *
     * @return void
     */
    function user_sync($user_id, $user_name)
    {
        /* 查询商城是否存在此用户 */
        $sql = "SELECT COUNT(*)+1 FROM " .$GLOBALS['ecs']->table('users').
               " WHERE user_id = '$user_id' AND user_name = '$user_name'";
        if ($GLOBALS['db']->getOne($sql) == 1)
        {
            /* 查询bmforum会员表,取得数据 */
            $sql = "SELECT username, pwd, mailadd, regdate, birthday, sex, lastlogin FROM " .$this->table('userlist').
                   " WHERE userid = '$user_id'";
            $res = $this->db->GetRow($sql);

            if (!empty($res))
            {
                $res[$this->field_name] = $this->convert($res[$this->field_name]);

                /* 向商城用户表插入用户数据 */
                $sql = "INSERT INTO " .$GLOBALS['ecs']->table('users')."(user_id, user_name, email, password, reg_time, last_time, sex, birthday) VALUES ('$user_id', '".addslashes($res['username'])."', '".addslashes($res['mailadd'])."', '" .$res['pwd']."', '".$res['regdate']."', '".date("Y-m-d H:i:s", $res['lastlogin'])."', '".$res['sex']."', '".$res['birthday']."')";

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

        return false;
    }

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

        /* 检查用户名是否已经存在 */
        $sql = "SELECT COUNT(*) FROM " .$this->table('userlist').
               " WHERE " .$this->field_name. " = '$username'";
        if ($this->db->GetOne($sql) > 0)
        {
            $this->error = ERR_USERNAME_EXISTS;

            return false;
        }

        /* 检查邮件地址是否重复 */
        $sql = "SELECT COUNT(*) FROM " .$this->table('userlist').
               " WHERE " .$this->field_email. "='$email'";
        if ($this->db->GetOne($sql) > 0)
        {
            $this->error = ERR_EMAIL_EXISTS;

            return false;
        }

        /* 插入用户数据 */
        $new_id = $this->insert_user($username, $password, $email, $gender, $bday);

        if ($new_id == 0)
        {
            $this->error = ERR_USERNAME_EXISTS;

            return false;
        }

        return $new_id;
    }

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

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

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

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

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

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

        if (!empty($gender))
        {
            $fields .= (empty($fields)) ? '' : ',';
            $fields .= "`$this->gender` = '$gender'";
        }

        if (!empty($bday))
        {
            $fields .= (empty($fields)) ? '' : ',';
            $fields .= "`$this->bday` = '$bday'";
        }

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

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

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

        $sql = "DELETE FROM " .$this->table('userlist'). " WHERE $where";

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

    /**
     * 编辑用户密码的函数
     * 在这个函数里判断用户输入的原来的密码是否正确，如果不正确则返回FALSE
     *
     * @access      public
     * @param       int         user_id         用户编号
     * @param       string      password        原来的登录密码
     * @param       string      new_password    新的登录密码
     * @return      void
     */
    function edit_password($user_id, $password, $new_password)
    {
        $sql = "SELECT COUNT(*) FROM ".$this->table('userlist')." ".
               "WHERE ".$this->field_id." ='$user_id' AND ".$this->field_pass." ='".$this->comiple_password($password)."'";
        if ($this->db->getOne($sql) == 1)
        {
            if (!$this->update_password($user_id, $new_password))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        else
        {
            return false;
        }
    }

    /**
     * 找回用户密码的函数
     *
     * @access      public
     * @param       int         user_id         用户编号
     * @param       string      new_password    新的登录密码
     * @param       string      code            验证串
     * @return      void
     */
    function fetch_password($user_id, $code, $new_password)
    {
        /* 比较code是否合法 */
        $sql = "SELECT " .$this->field_pass
            . " FROM " .$this->table('userlist')
            . " 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;
        }
    }

    /**
     * 更新用户密码的函数
     *
     * @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('userlist')
            . " SET " .$this->field_pass. "='" .$this->comiple_password($new_password)
            . "' WHERE " .$this->field_id. "='$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('userlist');

        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     $user_id     会员编号
     *
     * @return  array
     */
    function get_user_info($id)
    {
        $sql = "SELECT ugnum, username, pwd, mailadd, regdate, birthday, sex".
               " FROM " .$this->table('userlist').
               " 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['sex']         = $row[$this->gender];
        $arr['birthday']    = $row[$this->bday];
        $arr['last_time']   = 0;

        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('userlist') ."  $where ".
                "ORDER BY $sort $order, regdate DESC";
        $res = $this->db->SelectLimit($sql, $limit, $start);

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

            $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 =>substr($row[$this->field_reg_date], 0, 9));
        }

        return $list;
    }

    /**
     * 获得最后一个错误信息
     *
     * @access  public
     * @return  void
     */
    function error_msg()
    {
        return $this->db->ErrorMsg();
    }

    /*------------------------------------------------------ */
    //-- PRIVATE METHODs
    /*------------------------------------------------------ */

    /**
     * 在给定的表名前加上数据库名以及前缀
     *
     * @access  private
     * @param   string      表名
     *
     * @return void
     */
    function table($str)
    {
        return '`' .$this->db_name. '`.`'.$this->prefix.$str.'`';
    }

    /**
     * 设置整合对象的cookie
     *
     * @access      private
     * @param       int         user_id         用户编号
     * @param       string      user_password   登录密码
     * @return      void
     */
    function set_cookie($user_id, $user_password)
    {
        setcookie('bmforumerboardidnum', $user_id, time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain);
        setcookie('bmforumerboardpbmfym', $user_password, time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain);
        setcookie('cookie_time_bmb', 3600, time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain);
    }

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

        /* 向 bmforum的用户表(userlist)插入数据 */
        $sql = "INSERT INTO " .$this->table('userlist'). "(username, pwd, mailadd, regdate, ugnum, money, birthday, sex, hisipa)".
        " VALUES ('$username', '".$this->comiple_password($password)."', '$email', '".time().'_'.real_ip()."', '4', 100, '".$bday."', '".$gender."', '".real_ip()."')";
        $result = $this->db->query($sql);

        if ($result)
        {
            $new_id = $this->db->Insert_ID();

            return $new_id;
        }
        else
        {
            return false;
        }
    }

    /**
     * 检验在找回密码输入的用户名和email是否匹配
     *
     * @access      public
     * @param       int         user_name        用户名
     * @param       string      email            email
     * @return      array
     */
    function check_pwd_info($user_name, $email)
    {
        $username = $this->convert_to($user_name);

        $sql = "SELECT $this->field_id, $this->field_pass".
                ' FROM ' . $this->table('userlist') .
                " WHERE $this->field_name = '$username' 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('userlist').
               " 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;
        }
    }
}

?>