<?php
// ------------------------------------------------------------------------- //
//                XOOPS - PHP Content Management System                      //
//                       <http://www.xoops.org/>                             //
// ------------------------------------------------------------------------- //
//  This program is free software; you can redistribute it and/or modify     //
//  it under the terms of the GNU General Public License as published by     //
//  the Free Software Foundation; either version 2 of the License, or        //
//  (at your option) any later version.                                      //
//                                                                           //
//  This program is distributed in the hope that it will be useful,          //
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
//  GNU General Public License for more details.                             //
//                                                                           //
//  You should have received a copy of the GNU General Public License        //
//  along with this program; if not, write to the Free Software              //
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
// ------------------------------------------------------------------------- //
// Author of File: 							     //
// Kazumi Ono (http://www.mywebaddons.com/ , http://www.myweb.ne.jp/)        //
// ------------------------------------------------------------------------- //

include_once(XOOPS_ROOT_PATH."/class/xoopsgroup.php");
include_once(XOOPS_ROOT_PATH."/class/xoopsobject.php");

class XoopsUserSession{

	var $sessionID;
	var $cookie;
	var $expiretime;
	var $db;
	var $hash;
	var $uid;

	function XoopsUserSession($sessionid=""){
		global $xoopsConfig;
		$this->db =& Database::getInstance();
		$this->cookie = $xoopsConfig['sessioncookie'];
		$this->expiretime = $xoopsConfig['sessionexpire'];
		if($sessionid != ""){
			$this->sessionID = $sessionid;
		}
	}

	/*
	* creates new session for user 
	* and sets a cookie containing the session id
	*/
	function store(){
		global $REMOTE_ADDR;
		$this->hash = md5(uniqid(rand()));
		$this->db->query("DELETE FROM ".$this->db->prefix("session")." WHERE uid=".$this->uid." AND ip='".$REMOTE_ADDR."'");
        	if (!$this->db->query("INSERT INTO ".$this->db->prefix("session")." (uid, time, ip, hash) VALUES ($this->uid, ".time().", '$REMOTE_ADDR', '$this->hash')")) {
			return false;
		}
		setcookie($this->cookie, $this->hash, time()+360000, "/",  "", 0);
		return true;
	}

	function setUid($value){
		$this->uid = $value;
	}

	function uid(){
		return $this->uid;
	}

	function isValid() {
		unset($uid);
		$mintime = time() - $this->expiretime;
        	$this->db->queryF("DELETE FROM ".$this->db->prefix("session")." WHERE time < $mintime");
		$sql = "SELECT uid FROM ".$this->db->prefix("session")." WHERE hash='".$this->sessionID."'";
    		if ( !$result = $this->db->query($sql) ) {
			return false;
		}
    		list($uid) = $this->db->fetchRow($result);
		if ( !empty($uid) ) {
			$this->uid = $uid;
    			return true;
    		}
    		return false;
	}

	/*
	* updates the session table
	*/
	function update(){
		global $REMOTE_ADDR;
		$this->db->queryF("UPDATE ".$this->db->prefix("session")." SET time=".time()." WHERE uid=".$this->uid." AND ip='$REMOTE_ADDR'");
	}
}


Class XoopsUser extends XoopsObject{

	var $inactive = false;
	var $groups = array();

	function XoopsUser($id=NULL){
		$this->XoopsObject();
		$this->initVar("uid", "int", NULL, false);
		$this->initVar("name", "textbox", NULL, false, 60, true);
		$this->initVar("uname", "textbox", NULL, true, 25, false);
		$this->initVar("email", "textbox", NULL, true, 60, false);
		$this->initVar("url", "textbox", NULL, false, 100, false);
		$this->initVar("user_avatar", "textbox", NULL, false, 30);
		$this->initVar("user_regdate", "int", NULL, false);
		$this->initVar("user_icq", "textbox", NULL, false, 15, true);
		$this->initVar("user_from", "textbox", NULL, false, 100, true);
		$this->initVar("user_sig", "textarea", NULL, false, NULL, true);
		$this->initVar("user_viewemail", "int", 0, false);
		$this->initVar("actkey", "other", NULL, false);
		$this->initVar("user_aim", "textbox", NULL, false, 18, true);
		$this->initVar("user_yim", "textbox", NULL, false, 25, true);
		$this->initVar("user_msnm", "textbox", NULL, false, 25, true);
		$this->initVar("pass", "textbox", NULL, false, 32, false);
		$this->initVar("posts", "int", NULL, false);
		$this->initVar("attachsig", "int", 0, false);
		$this->initVar("rank", "int", NULL, false);
		$this->initVar("level", "int", 0, false);
		$this->initVar("theme", "other", NULL, false);
		$this->initVar("timezone_offset", "other", NULL, false);
		$this->initVar("last_login", "int", 0, false);
		$this->initVar("umode", "other", NULL, false);
		$this->initVar("uroder", "int", 1, false);
		$this->initVar("user_occ", "textbox", NULL, false, 100, true);
		$this->initVar("bio", "textarea", NULL, false, NULL, true);
		$this->initVar("user_intrest", "textbox", NULL, false, 150, true);
		if ( !empty($id) ) {
			if ( is_array($id) ) {
				$this->set($id);
			} else {
				$this->load(intval($id));
			}
		}
	}

	function login($uname, $pass){
		$myts =& MyTextSanitizer::getInstance();
		$uname = $myts->makeTboxData4Save($uname);
		$result = $this->db->query("SELECT uid, pass, level FROM ".$this->db->prefix("users")." WHERE uname='".$uname."'");
		if ( $this->db->getRowsNum($result) == 1 ) {
			$convert = false;
			$passed = false;
			$myrow = $this->db->fetchArray($result);
			if ( $myrow['level'] == 0 && !empty($myrow['uid']) ) {
				$this->inactive = true;
				return false;
			}
			if ($myrow['uid'] != 0) {
				if ($pass == $myrow['pass']) {
					$convert =true;
					$passed=true;
				}
				if (function_exists('crypt')) {
					if (crypt($pass,substr($myrow['pass'],0,2))== $myrow['pass'] ) {
						$convert = true;
						$passed=true;
					}
				}
				if ($myrow['pass']==md5($pass)) {
					$passed=true;
				}
				if ( $convert ) {
					$newpass = md5($pass);
					$this->db->query("UPDATE ".$this->db->prefix("users")." SET pass = '$newpass' WHERE uname = '$uname'");
				}
				if ( $passed ) {
					$session = new XoopsUserSession;
					$session->setUid($myrow['uid']);
					if (!$session->store()) {
						return false;
					}
					$this->db->query("UPDATE ".$this->db->prefix("users")." SET last_login=".time()." WHERE uid=".$myrow['uid']."");
					return $myrow['uid'];
				} else {
					return false;
				}
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	/*
	* Logs out user
	* removes user session from session table 
	*/
	function logout(){
		$this->db->queryF("DELETE FROM ".$this->db->prefix("session")." WHERE uid=".$this->getVar("uid")."");
	}

	function load($id){
		$sql = "SELECT * FROM ".$this->db->prefix("users")." WHERE uid=".$id."";
		if ( !$result = $this->db->query($sql) ) {
			die("ERROR");
		}
		//echo $sql;
		$numrows = $this->db->getRowsNum($result);
		if ( $numrows == 1 ) {
			$myrow = $this->db->fetchArray($result);
			$this->set($myrow);
			if ( $this->getVar("level") == 0 ) {
				$this->inactive = true;
			}
		} elseif ( $numrows == 0 ) {
			$this->inactive = true;
		} else {
			die("Duplicate User Entries!");
		}
	}

	function store(){
		if ( !$this->isCleaned() ) {
			if ( !$this->cleanVars() ) {
				return false;
			}
		}
		foreach ( $this->cleanVars as $k=>$v ) {
			$$k = $v;
		}
		if ( empty($uid) ) {
			$uid = $this->db->genId($this->db->prefix("users")."_uid_seq");
			$sql = "INSERT INTO ".$this->db->prefix("users")." (uid, uname, name, email, url, user_avatar, user_regdate, user_icq, user_from, user_sig, user_viewemail, actkey, user_aim, user_yim, user_msnm, pass, posts, attachsig, rank, level, theme, timezone_offset, last_login, umode, uorder, user_occ, bio, user_intrest) VALUES ($uid, '$uname', '$name', '$email', '$url', '$user_avatar', ".time().", '$user_icq', '$user_from', '$user_sig', '$user_viewemail', '$actkey', '$user_aim', '$user_yim', '$user_msnm', '$pass', '$posts', '$attachsig', '$rank', '$level', '$theme', '$timezone_offset', 0, '$umode', '$uorder', '$user_occ', '$bio', '$user_intrest')";
		}  else {
			$sql ="UPDATE ".$this->db->prefix("users")." SET uname='$uname', name='$name', email='$email', url='$url', user_avatar='$user_avatar', user_icq='$user_icq', user_from='$user_from', user_sig='$user_sig', user_viewemail='$user_viewemail', user_aim='$user_aim', user_yim='$user_yim', user_msnm='$user_msnm', pass='$pass', attachsig='$attachsig', rank='$rank', theme='$theme', timezone_offset='$timezone_offset', umode='$umode', uorder='$uorder', user_occ='$user_occ', bio='$bio', user_intrest='$user_intrest' WHERE uid=$uid";
		}
		//echo $sql;
		if ( !$result = $this->db->query($sql) ) {
			$this->setErrors("Could not store data in database.");
			return false;
		}
		if ( empty($uid) ) {
			$uid = $this->db->getInsertId();
		}
		return $uid;
	}

	function delete(){
		if ( $this->getVar("uid") > 0 ) {
			$sql = "DELETE FROM ".$this->db->prefix("users")." WHERE uid=".$this->getVar("uid")."";
			if ( !$result = $this->db->query($sql) ) {
				return false;
			}
			$this->db->query("DELETE FROM ".$this->db->prefix("groups_users_link")." WHERE uid=".$this->getVar("uid")."");
			$this->db->query("DELETE FROM ".$this->db->prefix("bb_forum_mods")." WHERE user_id=".$this->getVar("uid")."");
			$this->db->query("DELETE FROM ".$this->db->prefix("priv_msgs")." WHERE to_userid=".$this->getVar("uid")."");
			$this->logout();
		}
		return true;
	}

	function activate(){
		$sql = "UPDATE ".$this->db->prefix("users")." SET level=1 WHERE uid=".$this->getVar("uid")." AND actkey='".$this->getVar("actkey")."'";
		if ( !$result = $this->db->queryF($sql) ) {
			return false;
		}
		return true;
	}
		
	function isActive(){
		if ( $this->inactive == true) {
			return false;
		} else {
			return true;
		}
	}

	function isAdmin($moduleid=0){
		$groups = $this->groups();
		if ( XoopsGroup::checkRight("module", $moduleid, $groups, "A") ) {
			return true;
		}
		return false;
	}

	function rank($astitle=true){
		if ( $astitle ) {
			return $this->getRank();
		} else {
			return $this->getVar("rank");
		}
	}

	function getRank(){
		$myts =& MyTextSanitizer::getInstance();
		if ( $this->getVar("rank") != 0 ) {
        		$sql = "SELECT rank_title AS title, rank_image AS image FROM ".$this->db->prefix("ranks")." WHERE rank_id = ".$this->getVar("rank")."";
		} else {
			$sql = "SELECT rank_title AS title, rank_image AS image FROM ".$this->db->prefix("ranks")." WHERE rank_min <= " . $this->getVar("posts") . " AND rank_max >= " . $this->getVar("posts") . " AND rank_special = 0";
		}
		$result = $this->db->query($sql);
        	$myrow = $this->db->fetchArray($result);
		$myrow['title'] = $myts->makeTboxData4Show($myrow['title']);
		$myrow['id'] = $this->getVar("rank");
		return $myrow;
	}

	/*
	*  returns an array of group ids this user belongs
	*/
	function groups(){
		$this->groups = XoopsGroup::getByUser($this);
		return $this->groups;
	}

	/*
	 * Function to get user name from a certain user id
	 */
	function getUnameFromId($userid) {
		global $xoopsConfig;
		$db =& Database::getInstance();
		$sql = "SELECT uname FROM ".$db->prefix("users")." WHERE uid = $userid";
		if ( !$result = $db->query($sql) ) {
			return false;
		}
		if ( !$arr = $db->fetchArray($result) ) {
			return false;
		}
		$myts =& MyTextSanitizer::getInstance();
		$uname = $myts->makeTboxData4Show($arr['uname']);
		return $uname;
	}

	function incrementPost($uid){
		$db =& Database::getInstance();
		$sql = "UPDATE ".$db->prefix("users")." SET posts=posts+1 WHERE uid=".$uid."";
		$result = $db->query($sql);
	}

	// this requires whosonline module to be installed
	// if not installed, it will always return false
	function isOnline(){
		$sql = "SELECT COUNT(*) FROM ".$this->db->prefix("lastseen")." WHERE uid=".$this->getVar("uid")." AND online=1";
		if ( !$result = $this->db->query($sql) ) {
			return false;
		}
		list($count) = $this->db->fetchRow($result);
		if ( $count > 0 ) {
			return true;
		}
		return false;
	}

	function getAllUsers($criteria=array(), $asobject=false, $orderby="uid ASC", $limit=0, $start=0){
		$db =& Database::getInstance();
		$ret = array();
		$where_query = "";
		if ( is_array($criteria) && count($criteria) > 0 ) {
			$where_query = " WHERE";
			foreach ( $criteria as $c ) {
				$where_query .= " $c AND";
			}
			$where_query = substr($where_query, 0, -4);
		}
		if ( !$asobject ) {
			$sql = "SELECT uid FROM ".$db->prefix("users")."$where_query ORDER BY $orderby";
			$result = $db->query($sql,$limit,$start);
			while ( $myrow = $db->fetchArray($result) ) {
				$ret[] = $myrow['uid'];
			}
		} else {
			$sql = "SELECT * FROM ".$db->prefix("users")."".$where_query." ORDER BY $orderby";
			$result = $db->query($sql,$limit,$start);
			while ( $myrow = $db->fetchArray($result) ) {
				$ret[] = new XoopsUser($myrow);
			}
		}
		//echo $sql;
		return $ret;
	}

	function getAllUsersList($criteria=array(), $orderby="uid ASC", $limit=0, $start=0){
		$db =& Database::getInstance();
		$myts =& MyTextSanitizer::getInstance();
		$ret = array();
		$where_query = "";
		if ( is_array($criteria) && count($criteria) > 0 ) {
			$where_query = " WHERE";
			foreach ( $criteria as $c ) {
				$where_query .= " $c AND";
			}
			$where_query = substr($where_query, 0, -4);
		}
		$sql = "SELECT uid, uname FROM ".$db->prefix("users")."".$where_query." ORDER BY $orderby";
		$result = $db->query($sql,$limit,$start);
		while ( $myrow = $db->fetchArray($result) ) {
			$ret[$myrow['uid']] = $myts->makeTboxData4Show($myrow['uname']);
		}
		return $ret;
	}

	function countAllUsers($criteria=array()){
		$db =& Database::getInstance();
		$where_query = "";
		if ( is_array($criteria) && count($criteria) > 0 ) {
			$where_query = " WHERE";
			foreach ( $criteria as $c ) {
				$where_query .= " $c AND";
			}
			$where_query = substr($where_query, 0, -4);
		}
		$sql = "SELECT COUNT(*) FROM ".$db->prefix("users")."".$where_query."";
		$result = $db->query($sql);
		list($ret) = $db->fetchRow($result);
		return $ret;
	}



//### Methods from here will be deprecated. Use getVar() instead! ###

	function uid(){
		return $this->getVar("uid");
	}
	function name($format="S"){
		return $this->getVar("name", $format);
	}
	function uname($format="S"){
		return $this->getVar("uname", $format);
	}
	function email($format="S"){
		return $this->getVar("email", $format);
	}
	function url($format="S"){
		return $this->getVar("url", $format);
	}
	function user_avatar($format="S"){
		return $this->getVar("user_avatar");
	}
	function user_regdate(){
		return $this->getVar("user_regdate");
	}
	function user_icq($format="S"){
		return $this->getVar("user_icq", $format);
	}
	function user_from($format="S"){
		return $this->getVar("user_from", $format);
	}
	function user_sig($format="S"){
		return $this->getVar("user_sig", $format);
	}
	function user_viewemail(){
		return $this->getVar("user_viewemail");
	}
	function actkey(){
		return $this->getVar("actkey");
	}
	function user_aim($format="S"){
		return $this->getVar("user_aim", $format);
	}
	function user_yim($format="S"){
		return $this->getVar("user_yim", $format);
	}
	function user_msnm($format="S"){
		return $this->getVar("user_msnm", $format);
	}
	function pass(){
		return $this->getVar("pass");
	}
	function posts(){
		return $this->getVar("posts");
	}
	function attachsig(){
		return $this->getVar("attachsig");
	}
	function level(){
		return $this->getVar("level");
	}
	function theme(){
		return $this->getVar("theme");
	}
	function timezone(){
		return $this->getVar("timezone_offset");
	}
	function umode(){
		return $this->getVar("umode");
	}
	function uorder(){
		return $this->getVar("uorder");
	}
	function user_occ($format="S"){
		return $this->getVar("user_occ", $format);
	}
	function bio($format="S"){
		return $this->getVar("bio", $format);
	}
	function user_intrest($format="S"){
		return $this->getVar("user_intrest", $format);
	}
	function last_login(){
		return $this->getVar("last_login");
	}
}
?>