/*	Authentication flow. Requests and stores an OAuth based token. See the following for details:
	- http://developer.yahoo.com/oauth/guide/oauth-auth-flow.html
*/
require './inc/config.inc.php';
try {
    $o = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
    $o->enableDebug();
    $m = new YahooMessageArchiver(FALSE);
    /********************************************************************************************************************************************
    	/** Stage #1: Request Token
    	/********************************************************************************************************************************************/
    if (empty($_GET['oauth_token']) && empty($_GET['oauth_verifier'])) {
        $response = $o->getRequestToken('https://api.login.yahoo.com/oauth/v2/get_request_token', APPLICATION_URL . $_SERVER['SCRIPT_NAME']);
        if ($response && is_array($response)) {
            if (!$m->saveRequest($response)) {
                echo "Unable to save response.";
                $m->printR($m->getLog());
                exit;
            }
            // @todo add error reporting
            if (empty($response['xoauth_request_auth_url'])) {
                $m->printR($m->getLog());
                echo 'Error: Did not receive authentication url. Hmm...', PHP_EOL;
                exit;
            }
            header('Location: ' . $response['xoauth_request_auth_url']);
            exit;
        } else {
            // @todo add error reporting
            echo 'Error: Unknown problem.' . PHP_EOL;