<commit_before><?php
/**
 * SURFconext EngineBlock
 *
 * LICENSE
 *
 * Copyright 2011 SURFnet bv, The Netherlands
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 *
 * @category  SURFconext EngineBlock
 * @package
 * @copyright Copyright © 2010-2011 SURFnet SURFnet bv, The Netherlands (http://www.surfnet.nl)
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 */

/**
 * The bindings module for Corto, which implements support for various data
 * bindings.
 * @author Boy
 */
class EngineBlock_Corto_Module_Bindings extends EngineBlock_Corto_Module_Abstract
{
    const KEY_REQUEST  = 'SAMLRequest';
    const KEY_RESPONSE = 'SAMLResponse';

    protected static $ASSERTION_SEQUENCE = array(
        'saml:Issuer',
        'ds:Signature',
        'saml:Subject',
        'saml:Conditions',
        'saml:Advice',
        'saml:Statement',
        'saml:AuthnStatement',
        'saml:AuhzDecisionStatement',
        'saml:AttributeStatement',
    );

    /**
     * Supported bindings in Corto.
     * @var array
     */
    protected $_bindings = array(
        'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'        => '_sendHTTPRedirect',
        'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST'            => '_sendHTTPPost',
        'INTERNAL'                                                  => 'sendInternal',
        'JSON-Redirect'                                             => '_sendHTTPRedirect',
        'JSON-POST'                                                 => '_sendHTTPPost',
        null                                                        => '_sendHTTPRedirect'
    );

    protected $_internalBindingMessages = array();

    /**
     * @var EngineBlock_Corto_ProxyServer
     */
    protected $_server;

    /**
     * Process an incoming SAML request message. The data is retrieved automatically
     * depending on the binding used.
     */
    public function receiveRequest()
    {
        return $this->receive();
        $request = $this->_receiveMessage(self::KEY_REQUEST);

        // Remember idp for debugging
        $_SESSION['currentServiceProvider'] = $request['saml:Issuer']['__v'];

        $log = $this->_server->getSessionLog();
        $log->attach($request, 'Request')
            ->info('Received request');

        $this->_verifyRequest($request);
        $this->_c14nRequest($request);

        return $request;
    }

    public function receive()
    {
        $binding = SAML2_Binding::getCurrentBinding();
        $message = $binding->receive();

        // Remember idp for debugging
        $_SESSION['currentServiceProvider'] = $message->getIssuer();

        $log = $this->_server->getSessionLog();
        $log->attach($message, 'Message')
            ->info('Received message');

        $idpMetadata = new

        sspmod_saml_Message::validateMessage($idpMetadata, $spMetadata, $message);

    }

    /**
     * Process an incoming SAML response message.
     */
    public function receiveResponse()
    {
        $response = $this->_receiveMessage(self::KEY_RESPONSE);

        $log = $this->_server->getSessionLog();
        $log->attach($response, 'Response')
            ->info('Received response');

        if (isset($response[EngineBlock_Corto_XmlToArray::PRIVATE_PFX]['Binding']) &&
            $response[EngineBlock_Corto_XmlToArray::PRIVATE_PFX]['Binding'] === "INTERNAL") {
            return $response;
        }

        // Remember idp for debugging
        $_SESSION['currentIdentityProvider'] = $response['saml:Issuer']['__v'];

        $this->_decryptResponse($response);
        $this->_verifyResponse($response);

        return $response;<commit_msg>Work In Progress<commit_after><?php
/**
 * SURFconext EngineBlock
 *
 * LICENSE
 *
 * Copyright 2011 SURFnet bv, The Netherlands
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 *
 * @category  SURFconext EngineBlock
 * @package
 * @copyright Copyright © 2010-2011 SURFnet SURFnet bv, The Netherlands (http://www.surfnet.nl)
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 */

require ENGINEBLOCK_FOLDER_VENDOR . 'simplesamlphp/simplesamlphp/lib/_autoload.php';

/**
 * The bindings module for Corto, which implements support for various data
 * bindings.
 * @author Boy
 */
class EngineBlock_Corto_Module_Bindings extends EngineBlock_Corto_Module_Abstract
{
    const KEY_REQUEST  = 'SAMLRequest';
    const KEY_RESPONSE = 'SAMLResponse';

    protected static $ASSERTION_SEQUENCE = array(
        'saml:Issuer',
        'ds:Signature',
        'saml:Subject',
        'saml:Conditions',
        'saml:Advice',
        'saml:Statement',
        'saml:AuthnStatement',
        'saml:AuhzDecisionStatement',
        'saml:AttributeStatement',
    );

    /**
     * Supported bindings in Corto.
     * @var array
     */
    protected $_bindings = array(
        'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'        => '_sendHTTPRedirect',
        'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST'            => '_sendHTTPPost',
        'INTERNAL'                                                  => 'sendInternal',
        'JSON-Redirect'                                             => '_sendHTTPRedirect',
        'JSON-POST'                                                 => '_sendHTTPPost',
        null                                                        => '_sendHTTPRedirect'
    );

    protected $_internalBindingMessages = array();

    /**
     * @var EngineBlock_Corto_ProxyServer
     */
    protected $_server;

    /**
     * Process an incoming SAML request message. The data is retrieved automatically
     * depending on the binding used.
     */
    public function receiveRequest()
    {
        //return $this->receive();
        $request = $this->_receiveMessage(self::KEY_REQUEST);

        // Remember idp for debugging
        $_SESSION['currentServiceProvider'] = $request['saml:Issuer']['__v'];

        $this->_server->getSessionLog()
            ->attach($request, 'Request')
            ->info('Received request');

        $this->_verifyRequest($request);
        $this->_c14nRequest($request);

        return $request;
    }

    public function idpReceive()
    {
        $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
        $idpEntityId = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
        $idp = SimpleSAML_IdP::getById('saml2:' . $idpEntityId);
        sspmod_saml_IdP_SAML2::receiveAuthnRequest($idp);
    }

    public function spReceive()
    {
        $configs = $this->_server->getConfigs();
        $publicPem = $configs['certificates']['public'];
        $publicPem = str_replace(
            array('-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----', "\n", "\t", " "),
            '',
            $publicPem
        );

        $spMetadata = SimpleSAML_Configuration::loadFromArray(
            array(
                'entityid' => $this->_server->getUrl('spMetadataService'),
                'SingleSignOnService' => array (
                        array (
                            'Binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
                            'Location' => $this->_server->getUrl('spMetadataService'),
                        ),
                ),
                'keys' => array (
                    array (
                        'signing' => true,
                        'type' => 'X509Certificate',
                        'X509Certificate' => $publicPem,
                    ),
                )
            )
        );

        $binding = SAML2_Binding::getCurrentBinding();
        if ($binding instanceof SAML2_HTTPArtifact) {
            $binding->setSPMetadata($spMetadata);
        }

        $response = $binding->receive();
        if (!($response instanceof SAML2_Response)) {
            throw new SimpleSAML_Error_BadRequest('Invalid message received to AssertionConsumerService endpoint.');
        }

        $idp = $response->getIssuer();
        if ($idp === NULL) {
            throw new Exception('Missing <saml:Issuer> in message delivered to AssertionConsumerService.');
        }

        $cortoIdpMetadata = $this->_server->getRemoteEntity($idp);
        $publicPem = $cortoIdpMetadata['certificates']['public'];
        $publicPem = str_replace(
            array('-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----', "\n", "\t", " "),
            '',
            $publicPem
        );

        $sspIdpMetadata = SimpleSAML_Configuration::loadFromArray(
            array(
                'entityid'             => $cortoIdpMetadata['EntityID'],
                'SingleSignOnService'  => $cortoIdpMetadata['SingleSignOnService']['Location'],
                'keys' => array (
                    array (
                        'signing' => true,
                        'type' => 'X509Certificate',
                        'X509Certificate' => $publicPem,
                    ),
                ),
            )
        );

        try {
            $assertions = sspmod_saml_Message::processResponse($spMetadata, $sspIdpMetadata, $response);

            if (count($assertions) > 1) {
                throw new SimpleSAML_Error_Exception('More than one assertion in received response.');
            }
            $assertion = $assertions[0];
        } catch (sspmod_saml_Error $e) {
            /* We don't have an error handler. Show an error page. */
            throw new SimpleSAML_Error_Error('RESPONSESTATUSNOSUCCESS', $e);
        }

        echo "<pre>";var_dump($assertion);exit;

//        $binding = SAML2_Binding::getCurrentBinding();
//        $message = $binding->receive();
//
//        // Remember idp for debugging
//        $_SESSION['currentServiceProvider'] = $message->getIssuer();
//
//        $log = $this->_server->getSessionLog();
//        $log->attach($message, 'Message')
//            ->info('Received message');
//
//        if ($message instanceof SAML2_AuthnRequest) {
//            $this->_verifyRequest();
//        } else if ($message instanceof SAML2_Response) {
//
//        } else {
//
//        }
//
//        $this->_verifyRequest()
//
//        $idpMetadata = new SimpleSAML_Configuration();
//        $spMetadata  = new SimpleSAML_Configuration();
//
//        sspmod_saml_Message::validateMessage($idpMetadata, $spMetadata, $message);

    }

    /**
     * Process an incoming SAML response message.
     */
    public function receiveResponse()
    {
        $this->spReceive();
        exit;

        $response = $this->_receiveMessage(self::KEY_RESPONSE);

        $log = $this->_server->getSessionLog();
        $log->attach($response, 'Response')
            ->info('Received response');

        if (isset($response[EngineBlock_Corto_XmlToArray::PRIVATE_PFX]['Binding']) &&
            $response[EngineBlock_Corto_XmlToArray::PRIVATE_PFX]['Binding'] === "INTERNAL") {
            return $response;
        }

        // Remember idp for debugging
        $_SESSION['currentIdentityProvider'] = $response['saml:Issuer']['__v'];

        $this->_decryptResponse($response);
        $this->_verifyResponse($response);

        return $response;
{'fraction_non_alphanumeric': 0.1279422619535799, 'fraction_numerical': 0.00647912736816206, 'mean_word_length': 2.137123745819398, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 89, 'https://': 0, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5704977', 'n_tokens_mistral': 3442, 'n_tokens_neox': 3258, 'n_words': 704}