<?php

/***************************************************************************
 *
 *      Update to 2.0.20 by Alf (10.04.2006) 20:48
 *
 *	Title: xphpBBi - phpBB Complete Integration project 
 *	Description: Project to turn the phpBB forums into a fully functioning
 *		Xoops2 Module. Based on the phpBB 2.0.11 port from BBpixel.com - 
 *		(PBBoard v1.22).
 *	Credits: Xoops2 Module Development Team - Koudanshi - phpBB Group
 *	Thanks: To Koudanshi for a great start in his port, and phpBB Group for
 *		such a great forum software.
 *	License: GNU/GPL version 2 or later.
 ****************************************************************************/

/***************************************************************************
 *	Title: xphpBBi - phpBB Complete Integration project
 *	Description: Project to turn the phpBB forums into a fully functioning
 *		Xoops2 Module. Based on the phpBB 2.0.9 port from BBpixel.com - 
 *		(PBBoard v1.22).
 *	Credits: Xoops2 Module Development Team - Koudanshi - phpBB Group
 *	Thanks: To Koudanshi for a great start in his port, and phpBB Group for
 *		such a great forum software.
 *	License: GNU/GPL version 2 or later.
 ****************************************************************************/

/***************************************************************************
 *                                sessions.php
 *                            -------------------
 *   begin                : Saturday, Feb 13, 2001
 *   copyright            : (C) 2001 The phpBB Group
 *   email                : support@phpbb.com
 *
 *   $Id: sessions.php,v 1.58.2.16 2005/10/30 15:17:14 acydburn Exp $
 *
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   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.
 *
 ***************************************************************************/

//
// Checks for a given user session, tidies session table and updates user
// sessions at each page refresh
//
function session_pagestart($user_ip, $thispage_id)
{
	global $db, $lang, $board_config, $sid_xphpbbi, $uid_xphpbbi, $uname_xphpbbi, $issess, $lastvisit_xphpbbi;
	global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;
	global $xoopsDB, $xoopsUser, $xoopsTpl, $xoopsConfig;

	$cookiename = $board_config['cookie_name'];
	$cookiepath = $board_config['cookie_path'];
	$cookiedomain = $board_config['cookie_domain'];
	$cookiesecure = $board_config['cookie_secure'];

	$last_visit = 0;
	$current_time = time();
	unset($userdata);
	$sessiondata = array();

	$sessionmethod = SESSION_METHOD_GET;
	$session_id = $sid_xphpbbi;

	$thispage_id = (int) $thispage_id;

	//
	// Does a session exist?
	//	
	if ( !empty($session_id) )
	{
		session_begin($session_id,$user_ip,$thispage_id);

		//
		// session_id exists so go ahead and attempt to grab all
		// data in preparation
		//
		if( is_object($xoopsUser) ) {
			$sql = "SELECT u.*, s.*, ue.*, se.*
				FROM (((" . USERS_TABLE . " u, " . SESSIONS_TABLE . " s)
				LEFT JOIN " . USERS_TABLE_EXT . " ue ON u.uid=ue.uid)
				LEFT JOIN " . SESSIONS_TABLE_EXT . " se ON s.sess_id=se.sess_id)
				WHERE s.sess_id='$session_id' AND u.uid = ".$xoopsUser->getVar('uid');
			if ( !($result = $db->sql_query($sql)) || empty($userdata['user_lastvisit']) ) {
			    $useravatar = $xoopsUser->getVar('user_avatar');
			    if ($useravatar && $useravatar != 'blank.gif' && !preg_match("/^".XOOPS_AVATAR_PREFIX."/", strtolower($useravatar))) {
				$user_avatar_type = '3';
			    }else{
				$user_avatar_type = '1';
			    }
				$sql_1 = "INSERT INTO " . USERS_TABLE_EXT . " (uid, user_lastvisit, user_avatar_type) VALUES (".$xoopsUser->getVar('uid').", ".time().", ".$user_avatar_type.")";
				$db->sql_query($sql_1);
				//if ( !($result_1 = $db->sql_query($sql_1)) ) message_die(CRITICAL_ERROR, 'Error insert user into USERS_EXT table', '', __LINE__, __FILE__, $sql_1);
			}
		}else{
			$sql = "SELECT s.*, ue.*, se.*
				FROM ((" . SESSIONS_TABLE . " s, " . USERS_TABLE_EXT . " ue)
				LEFT JOIN " . SESSIONS_TABLE_EXT . " se ON s.sess_id=se.sess_id)
				WHERE s.sess_id='$session_id' AND ue.uid = 0";
		}

		if ( !($result = $db->sql_query($sql)) )
		{
		    message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
		}

		$userdata = $db->sql_fetchrow($result);
		//var_dump($userdata);exit;

		if (empty($userdata['session_logged_in'])) {
			$userdata['session_logged_in']=$issess;
		}
		if (empty($userdata['user_lastvisit'])) {
			//$userdata['user_lastvisit']=$userdata['last_login'];
			$userdata['user_lastvisit']=$lastvisit_xphpbbi;
		}
		if (empty($userdata['uid'])) {
			//$userdata['uid']=0;
			$userdata['uid']=$uid_xphpbbi;
		}
		if (empty($userdata['uname'])) {
			//$userdata['uname']='Guest';
			$userdata['uname']=$uname_xphpbbi;
		}

	//Update last PM for user
	//$new_pms = $xoopsDB->fetchRow($xoopsDB->query("SELECT COUNT(*) FROM ".$xoopsDB->prefix("priv_msgs")." WHERE to_userid = '".$xoopsUser->getVar("uid")."' AND read_msg = 0"));
	$last_pm_date = $xoopsDB->fetchRow($xoopsDB->query("SELECT MAX(msg_time) FROM ".$xoopsDB->prefix("priv_msgs")." WHERE to_userid = ".$userdata['uid']." AND read_msg = 0"));
	if ($last_pm_date[0] > $userdata['user_last_privmsg']) {
	    if (!empty($last_pm_date[0])) {
		$sql_pm = "UPDATE ".USERS_TABLE_EXT."
			SET user_last_privmsg = ".$last_pm_date[0]."
			WHERE uid = ".$userdata['uid'];
		if ( !$db->sql_query($sql_pm) )
		{
		    message_die(CRITICAL_ERROR, 'Could not update private message new/read time for user', '', __LINE__, __FILE__, $sql_pm);
		}
	    }
	}

		//
		// Initial ban check against user id, IP and email address
		//
		$sql2 = "SELECT ban_ip, ban_userid, ban_email 
			FROM " . BANLIST_TABLE . " WHERE ban_ip = '".$user_ip."' OR ban_userid = ".$userdata['uid'];
		$sql2 .= " OR ban_email LIKE '" . str_replace("\'", "''", $userdata['email']) . "' 
			OR ban_email LIKE '" . substr(str_replace("\'", "''", $userdata['email']), strpos(str_replace("\'", "''", $userdata['email']), "@")) . "'";
		if ( !($result2 = $db->sql_query($sql2)) )
		{
			message_die(CRITICAL_ERROR, 'Could not obtain ban information', '', __LINE__, __FILE__, $sql2);
		}

		if ( $ban_info = $db->sql_fetchrow($result2) )
		{
			if ( $ban_info['ban_ip'] || $ban_info['ban_userid'] || $ban_info['ban_email'] )
			{
				message_die(CRITICAL_MESSAGE, 'You_been_banned');
			}
		}

		//
		// Did the session exist in the DB?
		//
		if ( isset($userdata['uid']) )
		{
			//
			// Do not check IP assuming equivalence, if IPv4 we'll check only first 24
			// bits ... I've been told (by vHiker) this should alleviate problems with
			// load balanced et al proxies while retaining some reliance on IP security.
			//
			$ip_check_s = substr($userdata['sess_ip'], 0, 14);
			$ip_check_u = substr($user_ip, 0, 14);

			if ($ip_check_s == $ip_check_u) 
			{
				$SID = ($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? ($userdata['uid'] > 0 ? 'sid=' . $session_id : '') : '';
			}
		}
	}		

	$userdata['user_lang'] = $xoopsConfig['language'];
	$board_config['default_lang'] = $xoopsConfig['language'];

	return $userdata;
}

function session_begin($sess_id,$sess_ip,$sess_page){
	global $xoopsConfig, $xoopsDB, $xoopsUser;
	global $cookiename, $cookiepath, $cookiedomain, $cookiesecure, $session_id, $sessiondata;

	$sess_id = $xoopsDB->quoteString($sess_id);
	list($count) = $xoopsDB->fetchRow($xoopsDB->query("SELECT COUNT(*) FROM ".SESSIONS_TABLE_EXT." WHERE sess_id=".$sess_id));

	$uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : ANONYMOUS;
	$issess = is_object($xoopsUser) ? 1 : 0;

	$current_time = time();
	$sess_exp     = $xoopsDB->fetchArray($xoopsDB->query("SELECT * FROM ".CONFIG_TABLE." WHERE config_name = 'session_length'"));
	$time_exp_bb  = $sess_exp['config_value'] ? ($current_time - $sess_exp['config_value']) : ($current_time - 3600);
	$time_exp     = $xoopsConfig['session_expire']*60 < $sess_exp['config_value'] ? ($current_time - $xoopsConfig['session_expire']*60) : ($current_time - $sess_exp['config_value']);

	if ( $count > 0 ){
		$sql = "UPDATE ".SESSIONS_TABLE_EXT." SET session_user_id = '$uid', session_logged_in = '$issess', session_page = '$sess_page' WHERE sess_id = $sess_id";
	}else {
		$sql_exp_sess = "SELECT se.sess_id FROM (".SESSIONS_TABLE_EXT." se, ".SESSIONS_TABLE." s) 
				 WHERE s.sess_updated < '".$time_exp."' AND se.sess_id = s.sess_id";
		if (!($res_exp_sess = $xoopsDB->query($sql_exp_sess))) {
		    message_die(CRITICAL_ERROR, 'Error selecting from sessions table', '', __LINE__, __FILE__, $sql_exp_sess);
		}
		while ($row = $xoopsDB->fetcharray($res_exp_sess))
		{
		    $xoopsDB->queryF("DELETE FROM ".SESSIONS_TABLE_EXT." WHERE sess_id = '".$row['sess_id']."'");
		}

		$sql = "INSERT INTO ".SESSIONS_TABLE_EXT." 
			(sess_id, sess_ip, session_user_id, session_start, session_page, session_logged_in) 
			VALUES ($sess_id, '$sess_ip', '$uid', '$current_time', '$sess_page', '$issess')";
	}


	if (!$xoopsDB->queryF($sql))
	{
		message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
		return false;
	}

	if ( $uid != ANONYMOUS )
	{
		$sql = "UPDATE " . USERS_TABLE_EXT . "
			SET user_session_time = $current_time, user_session_page = $sess_page
			WHERE uid = ".$uid;

		if ( !$xoopsDB->queryF($sql) )
		{
		  message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
		}
	}

	setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
	setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);

	return true;
}
 /**
 * Removes expired sessions and auto-login keys from the database
 */
function session_clean($session_id)
{
 	global $board_config, $db;
 
 	//
 	// Delete expired sessions
 	//
 	$sql = 'DELETE FROM ' . SESSIONS_TABLE_EXT . ' 
 		WHERE session_time < ' . (time() - (int) $board_config['session_length']) . " 
 			AND session_id <> '$session_id'";
 	if ( !$db->sql_query($sql) )
 	{
 		message_die(CRITICAL_ERROR, 'Error clearing sessions table', '', __LINE__, __FILE__, $sql);
 	}
 
 	//
 	// Delete expired auto-login keys
 	// If max_autologin_time is not set then keys will never be deleted
 	// (same behaviour as old 2.0.x session code)
 	//
 	if (!empty($board_config['max_autologin_time']) && $board_config['max_autologin_time'] > 0)
 	{
 		$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
 			WHERE last_login < ' . (time() - (86400 * (int) $board_config['max_autologin_time']));
 		$db->sql_query($sql);
 	}
 
 	return true;
}

/**
* Reset all login keys for the specified user
* Called on password changes
*/
function session_reset_keys($user_id, $user_ip)
{
	global $db, $userdata, $board_config;

	$key_sql = ($user_id == $userdata['uid'] && !empty($userdata['session_key'])) ? "AND key_id != '" . md5($userdata['session_key']) . "'" : '';

	$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
		WHERE user_id = ' . (int) $user_id . "
			$key_sql";

	if ( !$db->sql_query($sql) )
	{
		message_die(CRITICAL_ERROR, 'Error removing auto-login keys', '', __LINE__, __FILE__, $sql);
	}

	$where_sql = 'session_user_id = ' . (int) $user_id;
	$where_sql .= ($user_id == $userdata['uid']) ? " AND sess_id <> '" . $userdata['sess_id'] . "'" : '';
	$sql = 'DELETE FROM ' . SESSIONS_TABLE_EXT . "
		WHERE $where_sql";
	if ( !$db->sql_query($sql) )
	{
		message_die(CRITICAL_ERROR, 'Error removing user session(s)', '', __LINE__, __FILE__, $sql);
	}

	if ( !empty($key_sql) )
	{
		$auto_login_key = dss_rand() . dss_rand();

		$current_time = time();
		
		$sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . "
			SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time
			WHERE key_id = '" . md5($userdata['session_key']) . "'";
		
		if ( !$db->sql_query($sql) )
		{
			message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
		}

		// And now rebuild the cookie
		$sessiondata['userid'] = $user_id;
		$sessiondata['autologinid'] = $auto_login_key;
		$cookiename = $board_config['cookie_name'];
		$cookiepath = $board_config['cookie_path'];
		$cookiedomain = $board_config['cookie_domain'];
		$cookiesecure = $board_config['cookie_secure'];

		setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
		
		$userdata['session_key'] = $auto_login_key;
		unset($sessiondata);
		unset($auto_login_key);
	}
}

// append_sid function has moved to functions.php
?>