<?php
# ************** LICENCE ****************
/*
	Copyright (c) PORTANEO.

	This file is part of POSH (Portaneo Open Source Homepage) http://sourceforge.net/projects/posh/.

	POSH 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 3 of the License, or
	(at your option) any later version

	POSH 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 Posh.  If not, see <http://www.gnu.org/licenses/>.
*/
# ***************************************
# Users connection checks & start session
#
# !! be careful, this file must be saved under uft8 format, and display an e accentuated here : é
# ***************************************
/**
*
* \brief Test connection to the server
*
* @param   (String) u : email
*		String) pass : password
*
*   return xml file
*
*  \relatesalso
*   ajax.js
*   $p.app.connection.set
*   admin.js
*   $p.admin.login
*
* !! be careful, this file must be saved under uft8 format, and display an e accentuated here : é
*
**/

$user = (isset($_POST["u"])) ? $_POST["u"]
                             :exit();
$password = (isset($_POST["pass"])) ? $_POST["pass"]
                                    : exit();

$folder     = "";
$not_access = 0;
$isScript   = true;
$isPortal   = false;
$pagename   = "portal/scr_connect.php";
//includes
require_once('includes.php');
require_once('../l10n/'.__LANG.'/lang.php');
require_once('../includes/authentification.inc.php');
require_once('../includes/xml.inc.php');
require_once('../includes/log.inc.php');
require_once('../includes/misc.inc.php');

if (user_login($user,$password,false,$user,$errormsg))
{
	launch_hook('logged_in',$user);
	$nbMonth = 0;
	// Get the total number of month for the last connection
	$diff =  strtotime(date("Y-m-d")) - strtotime($user->lastconnect_date);
	$nbday = intval($diff/(24*3600));
	if( (($diff%(24*3600))) > (24*3600) ) $nbday++;
	$nbMonth = $nbday/30;
	

	if( ( $nbMonth >= __IDLE_CONNECTIONS_EXPIRATION_DELAY) && __CONNECTION_SECURITY_LEVEL>=3) {
		
		$chk = $DB->execute($users_unsubscribe,
							$DB->escape($user->id),
							$DB->quote($user->md5user));
		$msg_error = "userExpired";
		$file = new xmlFile();
		$file->header();
		$file->status(0);
		$file->error("".$msg_error);
		$file->footer();
		exit();
	}
	
	// Get the total number of month for the last change of password
	$diff =  strtotime(date("Y-m-d")) - strtotime($user->password_change_date);
	$nbday = intval($diff/(24*3600));
	if( (($diff%(24*3600))) > (24*3600) ) $nbday++;
	$nbMonth = $nbday/30;
	$cnx = true;
	if( 
		(
		($nbMonth>=__PASSWORD_CHANGE_DELAY || $user->password_change_date==0 || $user->password_change_date=='0000-00-00') && __CONNECTION_SECURITY_LEVEL>=3  
		) || $user->force_user_change_password
	) {
		$cnx = false;
		$newpass = (isset($_POST["newpass"])) ? $_POST["newpass"]:'';
		$newpassconf = (isset($_POST["newpassconf"])) ? $_POST["newpassconf"]:'';
		$msg_error = '';
		if(!empty($newpass)) {
			if (strlen($newpass) < 8 && __CONNECTION_SECURITY_LEVEL>=2 ) {
				$msg_error = "msgSubPassToShort8";
				$file = new xmlFile();
				$file->header();
				$file->status(0);
				$file->error("".$msg_error);
				$file->footer();
				exit();
			}elseif( __CONNECTION_SECURITY_LEVEL<2 && strlen($newpass) < 6) {
				$msg_error = "msgSubPassToShort";
				$file = new xmlFile();
				$file->header();
				$file->status(0);
				$file->error("".$msg_error);
				$file->footer();
				exit();
			}
			
			if(md5($newpass) != md5($newpassconf) ) {
					$msg_error = "error:passwordAndConfirmationAreNotTheSame";
					$file = new xmlFile();
					$file->header();
					$file->status(0);
					$file->error("".$msg_error);
					$file->footer();
					exit();
			}
			
			// Get user name and long_name
			$username = $user->username;
			$long_name = $user->longname;

			$msg_error = isMixPassword($newpass);
			if( !empty($msg_error) ) {
				$file = new xmlFile();
				$file->header();
				$file->status(0);
				$file->error("".$msg_error);
				$file->footer();
				exit();
			}
			if ( preg_match('/'.$username.'/',$newpass) && __CONNECTION_SECURITY_LEVEL>=2 ){
				$msg_error = "msgLoginInPass";
				$file = new xmlFile();
				$file->header();
				$file->status(0);
				$file->error("".$msg_error);
				$file->footer();
				exit();
			}
			if ( preg_match('/'.$long_name.'/',$newpass) && __CONNECTION_SECURITY_LEVEL>=2 ){
				$msg_error = "msgNameInPass";
				$file->status(0);
				$file->error("".$msg_error);
				$file->footer();
				exit();
			}
			$DB->freeResults();
			
			if(__CONNECTION_SECURITY_LEVEL>=3) {
				// Check if password is used
				$DB->getResults($user_getUserOldPass,
								$DB->escape($user->id)
								);
				while($row = $DB->fetch(0)) {
					if($row['md5pass']==md5($newpass)) {
						$msg_error = "msgErrPasswordUsed";
						$file = new xmlFile();
						$file->header();
						$file->status(0);
						$file->error("".$msg_error);
						$file->footer();
						exit();
					}
				}
				$DB->freeResults();
			}
			
			// Change password in user information table
			$chk = $DB->execute($scrchangepwd_changeExpiredPass,
								$DB->quote($newpass),
								$DB->escape($user->id),
								$DB->quote($user->password));
			$test = $DB->nbAffected();
			
			$DB->freeResults();
			if($test) {
				$cnx = true;
			}
			
		} else {
			$file = new xmlFile();
			$file->header();
			$file->status(1);
			$file->returnData("passwordExpired");
			$file->footer();
		}
	}
	
	
	if($cnx){
		
		// create and store encryption key
		$_SESSION['encrypt_key'] = uniqid(strval(mt_rand()));
		set_cookie('encrypt_key', $_SESSION['encrypt_key']);

		if (isset($_POST["auto"]) && $user->type=='I')
		{
			user_setcookie($user);
		}

		//Session initialization
		init_session($user->id,$user->username,$user->type,$user->lang,$user->longname,$user->activity,$user->picture,$user->email);
		$_SESSION['mdp'] = 1;

		launch_hook('scr_connect_session_initialized',$user);

		if (isset($_POST["rtype"]))
		{
			if ($user->type == "I")
			{
				$ret = "scr_defportal.php";
			}
			elseif ($user->type == "A")
			{   
				$ret = "../admin/index.php";
			}
			else
			{
				$ret = "index.php";
			}
		}
		else
		{
			if ($user->type == "A")
			{
				$ret = "admin";
			}
			elseif ($user->type == "R")
			{
				$ret = "redactor";
			}
			else
			{
				$ret = "user";
			}
		}

		if ($user->type == "A")
		{
			//init logs
            $log=new log();
			$log->addLog($DB,'Admin connection');
            
            //Define if the current admin is a general admin or not
            $_SESSION['general_admin'] = 0;
            if ($_SESSION['user_id'] == 1)  $_SESSION['general_admin'] = 1;
            else {
                $DB->getResults($adm_getGroupId,$DB->escape($_SESSION['user_id']));
                if ($DB->nbResults() == 0)  $_SESSION['general_admin'] = 1;
                else    $DB->freeResults();
            }
		}
			
		//do not send xml response before (cookie creation needs to be done before header sent)
		$file = new xmlFile();

		$file->header();
		
		$file->status(1);
		$file->returnData($ret);
		
		$file->footer();
	}
}
else
{
	$file = new xmlFile();

	$file->header();

	$file->status(0);
	$file->error($errormsg);
	
	$file->footer();
}
?>