<?php

set_include_path( get_include_path() . PATH_SEPARATOR . APP_ROOT . 'sso/phpseclib/');

/**
 * Class CharterSSO
 */
class CharterSSO
{
    /**
     * @var string
     */
    private static $privatekey2048 = <<<EOT
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAic+PHLYH1cArOxizZ7M1xuy1/pPlKiDDBVTSatvEBSP4Llnc
mUQQ17ZgDIkQXLDfUjzbY3yAn9t7zl6o7YC8SSCxGFIQ7YF1dygB7Akf57lj0X49
mO5cUVqnA3XOGIXhdx6KdC4Z0Wr3LY2Lxkpm+yVezXySsSJVa/Sj49FpmepQouCI
bkwCzoYRybvfIifHOAnjILWUSnip5HHF1W/75FRrCaCWFjFjrNnyDizl7pgi7sDR
K9M7zWmM/84dAjNdAXJE3FLtF8Tfj/zIZXyaYeq51HEC51DJAuOP1JolZi2gvK4J
p4CUETSpnyMA8kSOlyVn65zGGTwifFm9uH0sVwIDAQABAoIBAB9udyopvFy8wT9v
0U9oGO5fg9zmF4EFyuU25O0ZZbp0a0ELHtzYIO1KO9rwEgrKDo1fsvwcY+vR8Alw
HqBY2djl+25cHV9GRSfhuJqAtEWyS3l3DQ6J4wVtIyWPY2vFcVitXw/DigDxICJE
I+qcgqNqcRZ2ALEk7w251P17gFXpulYDw+M27bEQ/IcQbIyWFlCw2XzxDdCtX0gF
W/awn8FeJd+pA07RfGw/kOwq3AtLqfXMDp/n63SKHmy3TSP4+YcLZ/YVoan1+WOx
Q9z+ESBDXe5G0ncCWrsZArfz8GEkKwJYfemLixOo3taR5WcDlEzbc93B7fWwKFgL
zE+6sw0CgYEAkNR1bsesnxgVvRzDw7jlMnwCnfdWjkP50wtoNn3d/STBsqvuZivX
YaRxmTaOI0KBgI2ThLJb5gohDM8MAiAjy7Wc+yNWgTvMCeibReO7RH8XKSxY7wu6
4mHPYf1EGIZ0fxglz65K7KC3K2/uwwrbdaCVgNpRLbNRdiasClQ43MUCgYEA85fR
JplTszbnBm6PhYB0q2Ex0XMBnoIYUfBGl0MlMwKkgIT4JC/E7w1zmtge3SW1n/LC
6wq1Jbb+XDo3gHcAGiv4YVuEFeQCteyG5W8uvy7v7GSRbI0A0XYnyJs8dRrnQmWp
C5F7qDCDwLJUd0v4QOLnrmRasn8+tE/r6mSvrmsCgYB2zdGHDkSMPTWX7ACqjQF2
aEO9USevjBNjC/hwus9e2MgLyP3G0i/b6QlGpXnzcprI2VopgCXijmyOFUnEdJjo
ghJD8LkFSggWGLlGm4kCpz5YiAhsDzM+gP2dZCR3+dOWbjiWJGNRuISJHUi+tilQ
VGpPSMdOtcodIZv+3RfIAQKBgQCsH/m9QZjASSpEBDnMBvHp67sNGivpulm/BH6N
Afg2LEbbPZotz8djd+jZYJ+meq/1Ps/2z9EivkTMHKL9Vpku5SUUfls+MKitrl2/
n6mzlFIagxGzV4tddxUzjmXRBdqlszoZH4r2VJm0vw4qYfcgunUlaGoiOQGw3cyB
CvaM0wKBgQCOaQvjAaJMeATsk4+LNx+inPFpHbG/VpFJa8L2ZWzqm6SD4iUDGqzw
zIj1h0dlt4vySoUInfqBRJZLJASek4+LELRiVPQ6JqndfI1/JPR6k00UPim99sx8
tXn1loIoFsYDJGoj2jcuEuS2zT0CnOqjzr8eLzLYAvtoYu7oPqQnpw==
-----END RSA PRIVATE KEY-----
EOT;

    /**
     * @var string
     */
    private static $publickey2048 = <<<EOT
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAic+PHLYH1cArOxizZ7M1
xuy1/pPlKiDDBVTSatvEBSP4LlncmUQQ17ZgDIkQXLDfUjzbY3yAn9t7zl6o7YC8
SSCxGFIQ7YF1dygB7Akf57lj0X49mO5cUVqnA3XOGIXhdx6KdC4Z0Wr3LY2Lxkpm
+yVezXySsSJVa/Sj49FpmepQouCIbkwCzoYRybvfIifHOAnjILWUSnip5HHF1W/7
5FRrCaCWFjFjrNnyDizl7pgi7sDRK9M7zWmM/84dAjNdAXJE3FLtF8Tfj/zIZXya
Yeq51HEC51DJAuOP1JolZi2gvK4Jp4CUETSpnyMA8kSOlyVn65zGGTwifFm9uH0s
VwIDAQAB
-----END PUBLIC KEY-----
EOT;

    private static $debug = false;

    /**
     * @var int
     */
    protected $_statuscode = -1;

    /**
     * @var string
     */
    protected $_statusmessage = '';

    /**
     * @var string
     */
    protected $_username = '';

    /**
     * @var string
     */
    protected $_password = '';

    protected $_rsaCrypt;
    protected $_rsaEncrypt;

    /**
     * @var bool
     */
    protected $_isLoggedIn = false;

    /**
     * @return int
     */
    public function getStatusCode()
    {
        return $this->_statuscode;
    }

    /**
     * @return string
     */
    public function getStatusMessage()
    {
        return $this->_statusmessage;
    }

    /**
     * @return string
     */
    public function getUsername()
    {
        return $this->_username;
    }

    /**
     * @return string
     */
    public function getPassword()
    {
        return $this->_password;
    }

    /**
     * @return bool
     */
    public function getIsLoggedIn()
    {
        return $this->_isLoggedIn;
    }

    function __construct()
    {
        $this->_rsaCrypt = new Crypt_RSA();
        $this->_rsaCrypt->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
        $this->_rsaCrypt->loadKey(self::$privatekey2048);

        $this->_rsaEncrypt = new Crypt_RSA();
        $this->_rsaEncrypt->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
        $this->_rsaEncrypt->loadKey(self::$publickey2048);
    }

    /**
     *
     */
    public function setCredentials($responseBody)
    {
        if (false)
        {
            $responseBody = <<<EOT
Ow15kpWBELerVNPjetClUl+Uvx1twXbXeUlxLQUQqQAbyFmAXE6ZQI3E9CbBBPcy8SV+r8X8AxfCgJOmRrhvs3rlQOZO7cyMGqyhecNK+1QlHzM51/6qx9Eba8nC9xYhDj3S75hfi7wyQR7rFO8OL8WRKEFtYmm4SHuKF32mDeNN6ONTeJwG0TsW5VT4F6xm6nEWVvoafXQLh8ihotW6CQKQxHSiFyqNFUZOSmFW/eTAPyHiu1SMnvId+1NlZC82J0x+aVa4s7/nk9i2e6FtMs3teOA8BJuOiMN6Kh3MVKFb3FgwbpNPvN1u1slrZi0knPls4kCwwEYJMr1S7TQZ9w==
EOT;

$responseBody = <<<EOT
GriQhrnIyLEIxTPNcyTh/zpi7eYrXnw86oVKwUnKy3mJy1PWubINP4tGXNviE0vEgNnNfVOuJa2x8I92AfeoyR6LbA/c5PNLK0pjTzM2sknUdxVsEg0dFN+L2QD71NkGfiAE0CA9VwOGSU3HDbvTOd1GGVYH1cLyFmUdKRRaec+T09mm/EE4cBUcwIUkfTMfaUuSPoNkksNdsYo3zzMJ+u/LQmToQES+PRM+02H9qCR/spXUs21UgG4yMBX8qNbciANbDWyKlhnCqGyMreKcSrWFpwbo5TgYotPQte+VkonIX4Sxjh14s3Wuu0T93g6KJ5uxiZuEsSa2lK9xIlJjQw==
EOT;
	}
            
        if (self::$debug) Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ": " . "responseBody: $responseBody");

        $ciphertext = base64_decode($responseBody);
        // if (self::$debug) Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ": " . "ciphertext decode: $ciphertext");

        $decrypttext = $this->_rsaCrypt->decrypt($ciphertext);
        if (self::$debug) Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ": " . "decrypttext: $decrypttext");

        $responseObject = json_decode($decrypttext);

        if (self::$debug) 
        {
            // var_dump($responseObject);
            Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ": " . print_r($responseObject, true));
        }

        $this->_statuscode = (int)$responseObject->{'statusCode'};
        $this->_statusmessage = $responseObject->{'statusMessage'};
        $this->_username = $responseObject->{'username'};
        $this->_password = $responseObject->{'secret'};

        $this->_isLoggedIn = ($this->_statuscode === 0);

        if (self::$debug) 
        {
            Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ": " . "statuscode:    $this->_statuscode");
            Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ": " . "statusmessage: $this->_statusmessage");
            Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ": " . "username:      $this->_username");
            Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ": " . "secret:        $this->_password");
        }
    }

    public function encodeString($plainText)
    {
        $encrypttext = $this->_rsaEncrypt->encrypt($plainText);
        $endcodedText = base64_encode($encrypttext);
        return $endcodedText;
    }

    public function decodeString($endcodedText)
    {
        $decodedText = base64_decode($endcodedText);
        $decryptText = $this->_rsaCrypt->decrypt($decodedText);
        return $decryptText;
    }
}
