<?php

class GptwrAuthService
{
	public static $MAJOR_VER = "1.1"; 
	public static $MINOR_VER = "0.1"; 

    public static function auth($ip = '', $port = '', $secret = '', $username = '', $password = '', $timeout = '3')
    {
		/***********************************************************************************/
		require_once('radius.class.php');
		/***********************************************************************************/

		/***********************************************************************************/
		$SEPARATE = "#";
		$DEFAULT_SUCCESS_CODE = '0';
		$DEFAULT_INVALID_INPUT_ERROR_CODE = '6007';
		$DEFAULT_IO_EXCEPTION_ERROR_CODE = '6040';
		$DEFAULT_RADIUS_EXCEPTION_ERROR_CODE ='6041';
		$DEFAULT_SDK_ERROR_CODE = '6042';
		$RADIUS_REPLY_ATTRIBUTE = 18;
		/***********************************************************************************/


		/***********************************************************************************/
		if ( $ip == NULL || $port == NULL || $secret == NULL || $username == NULL || $password == NULL )
		{
			return ($DEFAULT_INVALID_INPUT_ERROR_CODE . $SEPARATE . '0' . $SEPARATE . 'INVALID_INPUT_ERR');
		}
		if ( strlen(trim($ip)) == 0 || strlen(trim($port)) == 0 || strlen(trim($secret)) == 0 || strlen(trim($username)) == 0 || strlen(trim($password)) == 0) 
		{
			return ($DEFAULT_INVALID_INPUT_ERROR_CODE . $SEPARATE . '0' . $SEPARATE . 'INVALID_INPUT_ERR');
		}

		if ( intval($port) < 0 || intval($timeout) <= 0)
		{
			return ($DEFAULT_INVALID_INPUT_ERROR_CODE . $SEPARATE . '0' . $SEPARATE . 'INVALID_INPUT_ERR');
		}
		/***********************************************************************************/


		/***********************************************************************************/
		$radius = new Radius( $ip, $secret, '', intval($timeout), intval($port) );
		//$radius->SetDebugMode(TRUE);
		$radius->AccessRequest($username, $password);

		if ( $radius->_last_error_code == 0){
			$reply_message = $radius->GetAttribute($RADIUS_REPLY_ATTRIBUTE);
			if ( strlen(trim($reply_message)) == 0 ){ 
				return ( $DEFAULT_RADIUS_EXCEPTION_ERROR_CODE . $SEPARATE . '0' . $SEPARATE . 'INVALID_RADIUS_FORMAT_ERR' ) ;
			}
			return $reply_message;   
		}else if ( $radius->_last_error_code == 6040){
			return ( $DEFAULT_IO_EXCEPTION_ERROR_CODE . $SEPARATE . '0' . $SEPARATE . 'ERR_NETWORK_FAIL') ;
		}else {
			return ( $DEFAULT_SDK_ERROR_CODE . $SEPARATE . '0' . $SEPARATE . 'ERR_SDK_INTERNAL(' . $radius->GetLastError()  .')') ;
		}
		/***********************************************************************************/
    }

	public static function info()
	{
		return ( 'Grippin Tower SDK for PHP ver ' . self::$MAJOR_VER . '.' . self::$MINOR_VER);
	}
}

?>
