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


use DOMDocument;
use DOMElement;
use HipPlayConnect\Configuration\AxBranding;
use HipPlayConnect\Configuration\AxOERelease;

class AxAuthenticationCode {

    /**
     * Call the HipServ CS to transform an authentication code into a username.
     *
     * @param string $authCode The authentication code to transform into a username.
     *
     * @return string The username returned from the HipServ CS.
     * @throws AxAuthenticationCodeErrorException
     * @throws AxInvalidAuthenticationCodeException
     */
    public static function getUserName($authCode) {
        $mDocument = new DOMDocument( '1.0', 'UTF-8' );
        $mRootNode = $mDocument->createElement( 'hipserv' );
        $mRootNode->setAttribute( 'serial', AxOERelease::get('Serial') );
        $mRootNode->setAttribute( 'authenticationCode', $authCode );
        $mDocument->appendChild( $mRootNode );

        $URL = 'https://' . AxBranding::get('PortalServer'). '/rest/1.0/authentication/hipserv';

        $ch = curl_init( $URL );
        if (!$ch) {
            error_log( "curl_init(): failed to POST to $URL: " . curl_error( $ch ) );
            throw new AxAuthenticationCodeErrorException();
        }

        curl_setopt( $ch, CURLOPT_POST, TRUE ); // POST method
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $mDocument->saveXML() );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 ); // do not check SSL certificate
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); // do not check SSL certificate
        curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, false ); // do not follow redirections
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); //Return output as XML

        $authXML = curl_exec( $ch );

        if ( false != $authXML )
            $HTTPCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
        else {
            error_log( "curl_exec(): failed to POST to $URL: " . curl_error( $ch ) );
            throw new AxAuthenticationCodeErrorException();
        }

        curl_close( $ch );

        if ( !preg_match( '/^20[0-9]$/', $HTTPCode ) ) {
            error_log( "Bad HTTP status code from $URL: " . $HTTPCode);
            throw new AxInvalidAuthenticationCodeException();
        }

        $mDoc = new DOMDocument();
        if (!$mDoc->loadXML($authXML)) {
            error_log( "Invalid XML response from $URL: $authXML");
            throw new AxAuthenticationCodeErrorException();
        }

        $mUserElements = $mDoc->getElementsByTagName( 'hipserv' );
        if (!$mUserElements || $mUserElements->length != 1) {
            error_log( "Invalid XML response from $URL: $authXML");
            throw new AxAuthenticationCodeErrorException();
        }

        /** @var DOMElement $mUserElement */
        $mUserElement = $mUserElements->item(0);
        $login = $mUserElement->getAttribute('username');

        if ($login)
            return $login;

        error_log("Missing 'username' from 'hipserv' element from $URL: $authXML");
        throw new AxAuthenticationCodeErrorException();
    }
}
