<?php // vim:set et ts=4 sw=4 sts=4:
# Copyright (C) 2003-2014 hipplay Inc.
#
# This is UNPUBLISHED PROPRIETARY SOURCE CODE OF hipplay Inc.
# The copyright notice above does not evidence any actual or intended
# publication of such source code. The contents of this file may not
# be disclosed to third parties, copied or duplicated in any form, in
# whole or in part, without the prior written permission of
# hipplay Inc.
#
namespace HipPlayConnect\Identity;



class AxSession {

    const VALID_USERNAME = 'admin';

    /**
     * Check if a user is logged in, and log in if applicable using CS AUTH or TOKEN AUTH.
     *
     * @return bool <tt>TRUE</tt> if the user is logged in,
     *              <tt>FALSE</tt> if not.
     */
    public static function checkLoginFromQuery( )
    {
        if ( !empty( $_GET['AUTH'] ) )
        {
            try {
                $login = AxAuthenticationCode::getUserName($_GET['AUTH']);
                if ($login != self::VALID_USERNAME)
                    throw new AxInvalidAuthenticationCodeException();
                return self::logUserIn();
            }
            catch ( AxAuthenticationCodeErrorException $e ) {}
            catch ( AxInvalidAuthenticationCodeException $e ) {}
        }
        elseif ( !empty( $_GET['token']) && !self::isLoggedIn() )
        {
            try {
                AxAuthenticationToken::verify($_GET['token']);
                return self::logUserIn();
            }
            catch ( AxAuthenticationCodeErrorException $e ) {}
            catch ( AxInvalidAuthenticationCodeException $e ) {}
        }

        return self::isLoggedIn();
    }

    // Assume we've already verified that the given username is eligible to
    // log in, and make it official
    public static function logUserIn()
    {
        if (self::isLoggedIn())
            return TRUE;

        session_start();
        $_SESSION["isloggedin"] = TRUE;
        session_write_close();

        return TRUE;
    }

    public static function isLoggedIn( )
    {
        //check if they are logged in
        if( isset($_SESSION['isloggedin']) && $_SESSION['isloggedin'] == TRUE )
            return TRUE;

        return FALSE;
    }

    public static function logUserOut()
    {
        // Re-open the session for writing
        session_start();

        // Clear the session contents
        session_unset();

        // Remove the session id
        if( session_id() != null)
            session_destroy();

        // Clear the session contents in memory
        $_SESSION = array('isloggedin' => FALSE);

        // Close the session again so we dont block other processes
        session_write_close();

        // Tell the browser to voluntarily unset its cookie
        $CookieInfo = session_get_cookie_params();
        setcookie(session_name(), '', time()-3600, $CookieInfo['path'], $CookieInfo['domain']);
    }
}
