<?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\REST;



//
// parent of all REST Resources
//
abstract class AxAbstractRESTResource implements AxRESTResourceInterface
{
    const GLOBAL_LOCALE = 'en_US';

    protected $closeSession = true;

    /**
     * Process as REST request.
     *
     * @param string $requestMethod
     * @param array  $queryParams
     * @param string $requestBody
     *
     * @return AxRESTResponse
     */
	public function processRequest( $requestMethod = null, array $queryParams = null, $requestBody = null )
	{
	    // by default, we close the session as early as possible for concurrency; except for the few cases where we need to
	    // modify it
	    if( $this->closeSession ) 	        
	        session_write_close();
	    
	    // if the request method is not provided, use the one from the environement
	    if ( is_null( $requestMethod ) )
	    {            
            //
            // Request method
            //
            $requestMethod = $_SERVER[ 'REQUEST_METHOD' ];
            
            //
            // Workaround in case PUT and DELETE are blocked by firewalls
            //
            if ( $requestMethod == 'POST' )
            {
                if ( isset( $_SERVER[ 'HTTP_X_HTTP_METHOD_OVERRIDE' ] ) )
                    $requestMethod = $_SERVER[ 'HTTP_X_HTTP_METHOD_OVERRIDE' ];
            }
            
            // if Flex mode, get the method from the query string
            if ( isset( $_GET[ 'method' ] ) )
                $requestMethod = $_GET[ 'method' ];	        
	    }
		
	    if ( is_null( $queryParams ) )
	       $queryParams = $_GET;

		switch ( $requestMethod )
		{
			case 'GET'   :
            case 'DELETE':
                return $this->$requestMethod( $queryParams );
			case 'POST'  :
			case 'PUT'   :
			    return $this->$requestMethod( $queryParams, is_null( $requestBody ) ? file_get_contents( 'php://input' ) : $requestBody );
			default      :
			    return new AxRESTResponse( 405 );
		}
	}

    /**
     * Respond to a GET request.
     *
     * @param array $queryParams
     *
     * @return AxRESTResponse
     */
    protected function GET( array $queryParams )
	{
		return new AxRESTResponse( 405 );
	}

    /**
     * Respond to a POST request.
     *
     * @param array $queryParams
     * @param string $requestBody
     *
     * @return AxRESTResponse
     */
    protected function POST( array $queryParams, $requestBody )
	{
		return new AxRESTResponse( 405 );
	}

    /**
     * Respond to a PUT request.
     *
     * @param array $queryParams
     * @param string $requestBody
     *
     * @return AxRESTResponse
     */
	protected function PUT( array $queryParams, $requestBody )
	{
		return new AxRESTResponse( 405 );
	}

    /**
     * Respond to a DELETE request.
     *
     * @param array $queryParams
     *
     * @return AxRESTResponse
     */
    protected function DELETE( array $queryParams )
	{
		return new AxRESTResponse( 405 );
	}


    /**
     * Return an XML response body.
     *
     * @param string $template  XML template to replace '%s' placeholders into.
     * @param array  $arguments List of arguments to replace '%s' placeholders with.
     *
     * @return AxRESTResponse
     */
    protected function generateXmlResponse ($template, array $arguments = array()) {
        static $XML_HEADER = NULL;
        if (NULL === $XML_HEADER)
            $XML_HEADER = '<' . '?' . 'xml version="1.0"' . '?' . '>' . "\n";

        return new AxRESTResponse
        (
                200,
                $XML_HEADER . vsprintf($template, $arguments),
                'text/xml; charset=UTF-8'
        );
    }

    protected function validateClientLocation() {
        if ( !self::isClientLocal() && !self::isClientTunnelSupport() ) {
            error_log("kwiltReady endpoint accessed from external IP: " . $_SERVER["REMOTE_ADDR"]);
            throw new AxForbiddenRESTException();
        }
    }

    /**
     * Determine if the user is local to us or not based on their (and our) IP address/netmask
     * @return boolean true if the user is local, false if not.
     */
    protected static function isClientLocal()
    {
        if ( $_SERVER[ 'REMOTE_ADDR' ] == '127.0.0.1' )
            return true;

        return oeutil_isipintf(OEUTIL_INTF_ID_LAN, $_SERVER[ 'REMOTE_ADDR' ]);
    }

    /**
     * Determine if the user is connected via the tunnel based on their (and our) IP address/netmask
     * @return boolean true if the user is local, false if not.
     */
    protected static function isClientTunnel()
    {
        $tunnelAddress = oeutil_getintf_localip(OEUTIL_INTF_ID_TUN);
        $serverAddress = $_SERVER['SERVER_ADDR'];

        return ($tunnelAddress == $serverAddress);
    }

    protected static function isClientTunnelSupport()
    {
        return self::isClientTunnel() && (!array_key_exists('HTTP_X_FORWARDED_FOR', $_ENV));
    }

}