<?  // vim:set et ts=4 sw=4 sts=4:
# Copyright (C) 2003-2008 Axentra Corporation.
#
# This is UNPUBLISHED PROPRIETARY SOURCE CODE OF Axentra Corporation.
# 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
# Axentra Corporation.
#

use HipPlayConnect\Configuration\AxFeatures;
use HipPlayConnect\Configuration\AxLSBRelease;
use HipPlayConnect\Configuration\AxOERelease;
use HipPlayConnect\Identity\AxSession;
use HipPlayConnect\REST\AxRESTController;

class RESTController {

    const DEBUG_PID = FALSE;

    const REG_SERVER_CONFIG_FILE = '/etc/regserver.conf';

    public static function initialize() {
        self::initializeEnvironment();

        self::initializeResponseDebugging();
        self::initializeLocale();

        self::initializeAutoloader();

        self::initializeSession();
        self::initializeUrls();
        self::initializeCharset();

        self::initializePlatform();

        self::initializeContact();

        self::initializeLogin();

        self::initializeResponseCaching();
    }

    private static function initializeResponseDebugging() {
        header( 'X-PHP-PID: ' .     getmypid() ); // debug/profiling aid
    }

    private static function initializeLocale() {
        // Bug 18038: required otherwise escapeshellarg() strips non-ASCII characters
        define('MC_LOCALE', 'en_US');
        setlocale( LC_CTYPE, 'en_US.UTF-8' );
    }

    private static function initializeResponseCaching() {
        $Expires = gmdate( 'D, d M Y H:i:s' ).' GMT';

        // send headers that should foil proxy servers
        header("Expires: 0");
        header("Last-modified: $Expires");
        header('Pragma:'); // Bug 13462: avoid no-cache otherwise flash cannot get data from Internet Explorer over HTTPS
        header('Cache-Control: private, no-store, must-revalidate'); // Bug 13462: avoid no-cache otherwise flash cannot get data from Internet Explorer over HTTPS
        header('Cache-Control: post-check=0, pre-check=0', false);
    }

    private static function initializeEnvironment() {
        define('MODULE',            dirname( __DIR__ ));
        define('SCRIPT_NAME',       basename(__FILE__)); // bogus if the filename starts with accented characters
        define('APPLICATIONS_DIR',  MODULE.'applications/');
    }

    private static function initializeAutoloader() {
        // HipPlayConnect libraries
        require_once( dirname(__DIR__) . '/classes/AxAutoloader.php' );

        // instantiate the loader
        $loader = new \HipPlayConnect\AxAutoloader;

        // register the autoloader
        $loader->register();

        // register the base directories for the namespace prefix
        $loader->addNamespace( 'HipPlayConnect', __DIR__ . '/../classes/' );
    }

    private static function initializeLogin() {
        // If the user is authenticating with a token or authCode, process it now
        AxSession::checkLoginFromQuery();
    }

    private static function initializeSession () {
        ini_set('session.cookie_domain', '');

        if (!empty($_GET[session_name()]) && !preg_match('/[^0-9a-zA-Z]/', $_GET[session_name()]))
            $_COOKIE[session_name()] = $_GET[session_name()];

        // Load the session info from PHP's session cache
        session_start();

        // Reset the cookie expiry every time we make a request, since clients
        // aren't obligated to honour the cookie expiry anyway
        setcookie(session_name(), session_id(), 2147483647, ini_get('session.cookie_path'), ini_get('session.cookie_domain'));

        // Don't hold up other processes
        session_write_close();
    }

    private static function initializeUrls() {
        // Get the HTTP and HTTPS ports
        $PortsFile = @file('/etc/iptables/alternate-ports');
        if ($PortsFile) {
            $RE = array();
            foreach ($PortsFile as $Line) {
                if (preg_match('/^([A-Z]+)_PORT=([0-9]+)$/', $Line, $RE)) {
                    define($RE[1] . '_PORT', $RE[2]);
                }
            }
        }

        // Defaults to fall back on
        define('HTTP_PORT', 80);
        define('HTTPS_PORT', 443);

        define('HTTP_SUFFIX', (HTTP_PORT == 80 ? '' : ':' . HTTP_PORT));
        define('HTTPS_SUFFIX', (HTTPS_PORT == 443 ? '' : ':' . HTTPS_PORT));

        /* Since we use iptables to support alternate HTTP(S)_PORTs, the
         * server still sees the ports as being 80 and 443.  That's why
         * the following 'if' isn't
         *  if( $_SERVER['SERVER_PORT'] == HTTPS_PORT )
         */
        if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) // SERVER_PORT does not exist in CLI
            define('USE_SSL', TRUE);
        else
            define('USE_SSL', FALSE);
    }

    private static function initializeCharset() {
        // Set the charset encoding (see bug 8249)
        /*
        if( $_SERVER['HTTP_ACCEPT_CHARSET'] )
        {
            // This alone isn't enough.  We really need to check the whole header,
            // and pick out the first charset actually supported by PHP.
            // There's code to do that in accept-to-gettext.php, maybe we can
            // make use of it somehow.
            preg_match( '/^([^;,]+)/', $_SERVER['HTTP_ACCEPT_CHARSET'], $RE );
            define( 'CHARSET', $RE[1] );
        }
        else
            define( 'CHARSET', 'UTF-8' );
        */
        define('CHARSET', 'UTF-8');

        // Use UTF-8 encoding internally
        if (defined('ICONV_VERSION')) {
            // iconv_set_encoding('input_encoding') isn't currently used
            iconv_set_encoding('internal_encoding', 'UTF-8');
            iconv_set_encoding('output_encoding', CHARSET . '//TRANSLIT');
        }
        header('Content-Type: text/html; charset=' . CHARSET);
    }

    private static function initializePlatform() {
        $isBuildroot = AxFeatures::get('isBuildroot', 0);
        if ($isBuildroot) {
            $platform       = 'Buildroot';
            $platformDistro = AxOERelease::get(AxOERelease::CONFIG_KEY_DIST_NAME);
        } else {
            $platform       = 'Full';
            $platformDistro = AxLSBRelease::get(AxLSBRelease::CONFIG_KEY_DISTRIB_ID);
        }

        define('MC_PLATFORM', $platform);
        define('MC_PLATFORM_DISTRO', $platformDistro);
    }

    private static function initializeContact() {
        define('CONTACT_PASSWORD_STATUS_NO_NEED_TO_CHANGE', 0); // password in URL
        define('CONTACT_PASSWORD_STATUS_MUST_CHANGE',       1); // password in URL, must change at first login
        define('CONTACT_PASSWORD_STATUS_CHANGED',           2); // password changed at first login, must enter interactively
    }

    public static function processRequest(){
        AxRESTController::processRequest();
    }
}

RESTController::initialize();
RESTController::processRequest();

#EOF
