hedera-web/vn/web/service.php

229 lines
5.2 KiB
PHP
Executable File

<?php
namespace Vn\Web;
require_once ('vn/lib/app.php');
require_once (__DIR__.'/db-session-handler.php');
use Vn\Lib\Locale;
/**
* Thrown when user credentials could not be fetched.
**/
class SessionExpiredException extends Lib\UserException {}
/**
* Thrown when user credentials are invalid.
**/
class BadLoginException extends Lib\UserException {}
/**
* Thrown when client version is outdated.
**/
class OutdatedVersionException extends Lib\UserException {}
/**
* Main class for web applications.
**/
abstract class Service
{
protected $app;
function __construct ($app)
{
$this->app = $app;
}
/**
* Starts the user session.
**/
function startSession ()
{
$db = $this->app->getSysConn ();
ini_set ('session.cookie_secure', TRUE);
ini_set ('session.use_only_cookies', FALSE);
ini_set ('session.cookie_path', 'cookies');
ini_set ('session.hash_function', 'sha512');
session_set_save_handler (new DbSessionHandler ($db));
session_start ();
// Setting the locale
if (isset ($_SERVER['HTTP_ACCEPT_LANGUAGE']))
if (!isset ($_SESSION['httpLanguage'])
|| $_SESSION['httpLanguage'] != $_SERVER['HTTP_ACCEPT_LANGUAGE'])
{
$_SESSION['httpLanguage'] = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$regexp = '/([a-z]{1,4})(?:-[a-z]{1,4})?\s*(?:;\s*q\s*=\s*(?:1|0\.[0-9]+))?,?/i';
preg_match_all ($regexp, $_SERVER['HTTP_ACCEPT_LANGUAGE'], $languages);
foreach ($languages[1] as $lang)
if (stream_resolve_include_path ("locale/$lang"))
{
$_SESSION['lang'] = $lang;
break;
}
}
if (!isset ($_SESSION['lang']))
$_SESSION['lang'] = NULL;
Locale::set ($_SESSION['lang']);
// Registering the visit
if (!isset ($_COOKIE['PHPSESSID'])
|| isset ($_SESSION['access'])
|| isset ($_SESSION['skipVisit']))
return;
$agent = $_SERVER['HTTP_USER_AGENT'];
$browser = get_browser ($agent, TRUE);
if (isset ($browser['crawler']) && $browser['crawler'])
{
$_SESSION['skipVisit'] = TRUE;
return;
}
if (isset ($_SERVER['REMOTE_ADDR']))
$ip = ip2long ($_SERVER['REMOTE_ADDR']);
$row = $db->getRow (
'CALL visitRegister (#, #, #, #, #, #, #, #, #)',
[
nullIf ($_COOKIE, 'vnVisit')
,nullIf ($browser, 'platform')
,nullIf ($browser, 'browser')
,nullIf ($browser, 'version')
,nullIf ($browser, 'javascript')
,nullIf ($browser, 'cookies')
,isset ($agent) ? $agent : NULL
,isset ($ip) && $ip ? $ip : NULL
,nullIf ($_SERVER, 'HTTP_REFERER')
]
);
if (isset ($row['access']))
{
setcookie ('vnVisit', $row['visit'], time () + 31536000); // 1 Year
$_SESSION['access'] = $row['access'];
}
else
$_SESSION['skipVisit'] = TRUE;
}
/**
* Tries to retrieve user credentials from many sources such as POST,
* SESSION or COOKIES. If $_POST['remember'] is defined the user credentials
* are saved on the client brownser for future logins, cookies names are
* 'vn_user' for the user name and 'vn_pass' for user password, the
* password is encoded using base64_encode() function and should be decoded
* using base64_decode().
*
* return Db\Conn The database connection
**/
function login ()
{
$db = $this->getSysConn ();
$user = NULL;
$wasLoged = isset ($_SESSION['user']);
if (isset ($_POST['user']) && isset ($_POST['password']))
{
$user = strtolower ($_POST['user']);
try {
$db->query ('CALL account.userLogin (#, #)',
[$user, $_POST['password']]);
}
catch (\Exception $e)
{
throw new BadLoginException ();
}
}
else
{
if (isset ($_POST['token']) || isset ($_GET['token']))
{
if (isset ($_POST['token']))
$token = $_POST['token'];
if (isset ($_GET['token']))
$token = $_GET['token'];
$key = $db->getValue ('SELECT jwt_key FROM config');
$jwtPayload = Jwt::decode ($token, $key);
$expiration = $jwtPayload['exp'];
if (isset ($expiration) && $expiration > time())
throw new SessionExpiredException ();
$user = $jwtPayload['user'];
}
else
$user = $db->getValue ('SELECT guest_user FROM config');
$db->query ('CALL account.userLoginWithName (#)', [$user]);
}
$_SESSION['user'] = $user;
// Registering the user access
if (isset ($_SESSION['access'])
&& (!isset ($_SESSION['visitUser'] || $wasLoged)))
{
$_SESSION['visitUser'] = TRUE;
$db->query (
'CALL visitUserNew (#, #)',
[$_SESSION['access'], session_id ()]
);
}
$db->query ('CALL userSessionStart (#)', [session_id ()]);
}
function deinit ()
{
$db = $this->getSysConn ();
$db->query ('CALL userSessionEnd ()');
$db->query ('CALL account.userLogout ()');
}
/**
* Logouts the current user. Cleans the last saved used credentials.
**/
function logout ()
{
unset ($_SESSION['visitUser']);
unset ($_SESSION['user']);
}
/**
* Checks if the HTTP connection is secure.
*
* @return boolean Return %TRUE if its secure, %FALSE otherwise
**/
function isHttps ()
{
return isset ($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
}
/**
* Obtains the application version number. It is based on de last
* modification date of the main script.
**/
function getVersion ()
{
return (int) strftime ('%G%m%d%H%M%S',
filectime ($_SERVER['SCRIPT_FILENAME']));
}
}
?>