<?php

$logid = 'OAuth1';

$path = ini_get('include_path');
$path =  dirname(dirname(__FILE__)).'/lib' . PATH_SEPARATOR . $path;
ini_set('include_path', $path);

require_once("/var/www/lib/util.php");
require_once("/var/www/lib/oauth.php");
require_once 'SignedRequestValidator.php';

$conf = parse_ini_file("/var/www/conf/oauth1.conf");
if (empty($conf)) {
     $log->crit(logformat("Can't read oauth1.conf"));
     echo '{"error" : true, "message" : "Can\'t read config file"}';
     exit(1);
}

require_once("config.php");

$validator = new SignedRequestValidator($conf['gadgeturl']);
$validator->validate_request();

$authenticated = false;
$conf['usercol'] = $conf['requestorcol'];
$requestorid = $_GET['opensocial_viewer_id'];
$login = new AutoLogin('DB', $conf);
$rc = $login->setUser($requestorid, true);
if (PEAR::isError($rc)) {
    if ($rc->getCode() !== AUTO_LOGIN_NO_USER) {
        $log->err(logformat("Can't get user: ". $rc->getMessage()));
        echo '{"error" : true, "message" : "Can\'t get user"}';
        exit(1);
    }
} else if ($login->storage->get('expires') > time()) {
    $authenticated = true;
}

if (!$authenticated) {
    ini_set('session.use_trans_sid', 1);
    session_name('oauth1');
    session_start();
    $_SESSION['requestorid'] = $requestorid;
    $_SESSION['client_id'] = $conf['gadgeturl'];
    $_SESSION['expires'] = time() + 180;
    header("HTTP/1.0 401 Unauthorized");
    echo '{"popup" : "'.$conf['authurl'].'?'.session_name().'='.session_id().'"}';
    exit(0);
}

for ($i = 0; $i < 3; $i++) {
    $session = $login->storage->get('session');
    if (!$session) {
        $session = login($conf, $login->storage);
        if (PEAR::isError($session)) {
            $log->err(logformat("Application authentication failed: ". $session->getMessage()));
            echo '{"error" : true, "message" : "Application authentication failed"}';
            exit(1);
        }
    }

    $response = sendRequest($conf, $session);
    if (PEAR::isError($response)) {
        $log->err(logformat("Application access failed: ".$response->getMessage()));
        echo '{"error" : true, "message" : "Application access failed"}';
        exit(1);
    } else if ($response['status'] == 401 || (isset($conf['login_check']) && preg_match('/'.$conf['login_check'].'/', $response['body']))) {
        continue;
    }
    break;
}

header('HTTP/1.1 '.$response['status']);
foreach ($response['headers'] as $key => $value) {
    header("$key: $value");
}
print $response['body'];

exit(0);

?>
