/**
 * Creates a SAML authentication request.
 * @param string $acsURL The URL to the SSO ACS
 * @param string $providerName The domain name of the identity requestor
 * @return string
 */
function createAuthnRequest($acsURL, $providerName)
{
    $tml = file_get_contents('templates/AuthnRequestTemplate.xml');
    $tml = str_replace('<PROVIDER_NAME>', $providerName, $tml);
    $tml = str_replace('<AUTHN_ID>', samlCreateId(), $tml);
    $tml = str_replace('<ACS_URL>', $acsURL, $tml);
    $tml = str_replace('<ISSUE_INSTANT>', samlGetDateTime(time()), $tml);
    return $tml;
}
/**
 * Signs a SAML response with the given private key, and embeds the public key.
 * @param string $responseXmlString
 * @param string $pubKey
 * @param string $privKey
 * @return string
 */
function signResponse($responseXmlString, $pubKey, $privKey)
{
    // NOTE: You may want to point this function to a directory on your
    // web server that is suitable for temporary files and is not in your
    // web server path.
    global $error;
    // generate unique temporary filename
    $tempFileName = 'saml-response-' . samlCreateId() . '.xml';
    while (file_exists($tempFileName)) {
        $tempFileName = 'saml-response-' . samlCreateId() . '.xml';
    }
    if (!($handle = fopen($tempFileName, 'w'))) {
        echo 'Cannot open temporary file (' . $tempFileName . ')';
        exit;
    }
    if (fwrite($handle, $responseXmlString) === FALSE) {
        echo 'Cannot write to temporary file (' . $tempFileName . ')';
        exit;
    }
    fclose($handle);
    // The path to xmlsec/xmlsec1 may need to be adjusted here.
    // xmlsec supports many key types, which can be selected
    // by using other command-line parameters.
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        // on Windows the anonymous IIS user account needs access to run cmd.exe
        // this can be done with the following command line:
        // cacls %COMSPEC% /E /G %COMPUTERNAME%\IUSR_%COMPUTERNAME%:R
        $cmd = 'C:\\libs\\xmlsec-win32\\xmlsec sign --privkey-pem ' . $privKey . ' --pubkey-der ' . $pubKey . ' --output ' . $tempFileName . '.out ' . $tempFileName;
    } else {
        $cmd = '/usr/bin/xmlsec1 sign --privkey-pem ' . $privKey . ' --pubkey-der ' . $pubKey . ' --output ' . $tempFileName . '.out ' . $tempFileName;
    }
    exec($cmd, $resp);
    var_dump($resp);
    unlink($tempFileName);
    $xmlResult = @file_get_contents($tempFileName . '.out');
    if (!$xmlResult) {
        $error = 'Unable to sign XML response. Please ensure that xmlsec is ' . 'installed, and check your keys.';
        // uncomment the line below to print xmlsec error messages
        // $error .= '<br><br>'.
        //             str_replace('[br]', '<br>',
        //                         htmlentities(implode($resp, '[br]')));
        return false;
    } else {
        unlink($tempFileName . '.out');
        return $xmlResult;
    }
}