<?php
/**
 * Login logic page
 * 
 * This page is called for user to log-in from admin page only
 * 
 * @package linea21\core\admin
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

ob_start();
session_start();
include_once("../config/define.php");
include_once("../lib/no_cache.php");
include_once('../languages/' . U_L . '/lang_common.'. CHARSET .'.php');
include_once("../class/system/class." . SQL . ".php");

IncludeUserfiles();

include_once(SQL . ".inc.php");

// if page var is not empty we pass the reference to the form
if(isset($_REQUEST['page'])) $page = $_REQUEST['page'];
else $page = 'index.php';

// check if session is not expired
// do comment for more security
if($l21auth->isActive()) {
	header("Location: ".safe_redirect($page));
}

// ////////////////////////////////////
// TENTATIVE D'AUTHENTIFICATION
// ////////////////////////////////////
if (isset($_POST['valid'])) {

	if(isset($_POST['rememberme'])) {
		$rememberme = true;
	} else {
		$rememberme = false;
	}

  $auth_res = $l21auth->logIn($_POST['login'], $_POST['password'], 'ADMIN', $rememberme);

  if ($auth_res === true) {
    // if page var is not empty we reconnect to the given page
    if(!empty($_POST['page'])) {
      $goto = $_POST['page'];
      header("Location: ".safe_redirect($goto));
      exit();
    }

    // else we reconnect to the last page (stored in cookie)
    if(isset($_COOKIE['linea21_lastactivity']) && $_POST['login'] == $_COOKIE['linea21_lastuser']) {
      $goto = $_COOKIE['linea21_lastpage'];
      // up to 3 hours of inactivity, we send the user to the latest consulted page
      $lastcon_date = (integer) date("YmdGi", $_COOKIE['linea21_lastactivity']);
      $buffer_date = $lastcon_date + (3 * 60);

      $current_date = (integer) date('YmdGi', time());
      if($current_date < $buffer_date && isset($_COOKIE['linea21_lastpage'])) {
        header("Location: ".safe_redirect($goto));
        exit();
      } else {
        header("Location: index.php");
        exit();
      }
    }
    else {
      header("Location: index.php");
      exit();
    }
  }

}

include_once(THEME_ADMIN_PATH."login.php");

$sql_object -> DBClose();
ob_end_flush();
?>