<?php

class InternalPassport {
	public static function auth() {
		if (isset($_COOKIE['Session_id'])) {
			require_once './Blackbox.php';
			$bb = new Blackbox();
			$r = $bb->sessionid($_COOKIE['Session_id'], $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_HOST'], array(BLACKBOX_LOGIN));
			if (!$bb->isValid($r)) {
				return false;
			}
			$redirect = $bb->isNeedRenew($r);
			if ($redirect && empty($_POST)) {
				header('Location: '. $redirect . urlencode(self::getUrl()));
				exit();
			}
			return '' . $r->dbfields[BLACKBOX_LOGIN];
		}
	}

	private static function getUrl() {
		return 
			(!empty($_SERVER['HTTPS']) ? 'https://' : 'http://') .
			$_SERVER['HTTP_HOST'] .
			(!empty($_SERVER['SERVER_PORT']) && ((empty($_SERVER['HTTPS']) && $_SERVER['SERVER_PORT']!=80) || (!empty($_SERVER['HTTPS']) && $_SERVER['SERVER_PORT']!=443)) ? ':'. $_SERVER['SERVER_PORT'] : '') .
			$_SERVER['REQUEST_URI'];
	}
}
