<?php

/**
 * @file
 * Authorization grant endpoint.
 *
 * Nifty OAuth Specification based on OAuth 2.0 draft 26.
 *
 */

$logid = 'OAuth';

//require "lib/MemcacheOAuth2.inc";
require "lib/PDOOAuth2.inc";
require_once("/var/www/lib/util.php");

$log = &Log::singleton('syslog', LOG_LOCAL5, $logid);

// 設定ファイル取得
$conf_oauth = parse_ini_file("/var/www/conf/oauth.conf");
if (empty($conf_oauth)) {
    $log->crit(logformat("Can't read oauth.conf"));
    $smarty = new Smarty();
    $smarty->template_dir = 'templates';
    $smarty->compile_dir = 'templates_c';
	$smarty->assign('error', "system_error99");
	$smarty->display('fatal.tpl');
    exit();
}

$conf = $conf_oauth;
$conf['endpoint'] = 'authorize';

// NIFTYIDと入力ID取得
$inputname = NULL;
$username = NULL;
$pleasyid = NULL;
if (preg_match('/#id=([^#]*)/', $_SERVER['REMOTE_USER_DATA'], $matches)) {
	$inputname = $matches[1];
}
if (preg_match('/#niftyid=([^#]*)/', $_SERVER['REMOTE_USER_DATA'], $matches)) {
	$username = $matches[1];
}
if (preg_match('/#pleasyid=([^#]*)/', $_SERVER['REMOTE_USER_DATA'], $matches)) {
	$pleasyid = $matches[1];
}
if (!$username || !$inputname) {
	$log->err(logformat("User isn't authenticated"));
    $smarty = new Smarty();
    $smarty->template_dir = 'templates';
    $smarty->compile_dir = 'templates_c';
	$smarty->assign('error', "system_error99");
	$smarty->display('fatal.tpl');
	exit();
}

session_start();
if (!session_id()) {
	session_regenerate_id();
}

// auth_level設定
$request_uri = $_SERVER["REQUEST_URI"];
if (preg_match('/\/Oauth-middle\//', $request_uri)) {
	$conf['auth_level'] = 'middle';
}
else if (preg_match('/\/Oauth-high\//', $request_uri)) {
	$conf['auth_level'] = 'high';
}

//==============================================================================

//$oauth = new MemcacheOAuth2($conf);
$oauth = new PDOOAuth2($conf);

// OAuthパラメータチェック
$auth_params = $oauth->getAuthorizeParams();

if (!$auth_params['scope']) {
	$auth_params['scope'] = $conf['default_scopes'];
}

$already_authorized = FALSE;
$authorization_status = FALSE;
$authorized_scopes = NULL;
// get authorization status and authorized scopes
$query_result = $oauth->getAuthorizedApps($username, $auth_params["client_id"]);
if ($query_result === FALSE) {
	$log->err(logformat("OAuth exception occured: "."Can't connect MySQL"));
	$oauth->showError("system_error04", $auth_params["client_id"]);
    exit();
}
if (is_array($query_result) && !empty($query_result)) {
    $authorization_history = $query_result[0];
	if (is_array($authorization_history) && isset($authorization_history['deleted']) && $authorization_history['deleted'] == '0') {
		$authorization_status = TRUE;
	}
	if (is_array($authorization_history) && isset($authorization_history['scope']) && $authorization_history['scope']) {
	    $authorized_scopes = $authorization_history['scope'];
	}
	// 認可済みのサービスで同一ID、同一スコープの場合には認可画面を表示させない
	if ($authorization_status && $oauth->checkScope2($auth_params['scope'], $authorized_scopes)) {
		$already_authorized = TRUE;
	}
}

//==============================================================================

// 「認可画面表示フラグ」設定しない場合、認可画面出さずに認可コードを発行する
if ($auth_params['scope_flag'] == '0') {
	$auth_params['scope'] = '';
	$auth_params['username'] = $username;
	$auth_params['additional_data'] = $inputname;
	$oauth->finishClientAuthorization(TRUE, $auth_params);
}
else {
	// 既に認可しているサービスは、認可画面出さずに認可コードを発行する
	if ($already_authorized) {
		$auth_params['username'] = $username;
		$auth_params['additional_data'] = $inputname;
	    $oauth->finishClientAuthorization(TRUE, $auth_params);
	}
	// 認可画面でユーザ同意のうえ、認可コードを発行する
	else if (isset($_GET['csrf'])) {
		$is_authorized = checkCsrf($_GET['csrf']);
		if ($is_authorized) {
			$auth_params['username'] = $username;
			$auth_params['additional_data'] = $inputname;
		    $oauth->finishClientAuthorization($is_authorized, $auth_params);
		}
		else {
			$log->err(logformat("OAuth get auth code failed for ".$auth_params['client_id'].": csrf failed"));
		}
	}
	// 上記の条件満たさない場合、認可画面を表示/再表示する
}

//==============================================================================

// 認可画面を表示
$smarty = new Smarty();
$smarty->template_dir = 'templates';
$smarty->compile_dir = 'templates_c';
$smarty->assign('auth_params', $auth_params);

// CSRF設定
setCsrf();
$smarty->assign('csrf', $_SESSION['csrf']);

// ようこそ設定
$smarty->assign('additional_data', $inputname);
$smarty->assign('username', $username);
$smarty->assign('pleasyid', $pleasyid);

// アプリケーションの情報設定
try {
	$client = $oauth->getClient($auth_params['client_id']);
}
catch (Exception $e) {
	$log->err(logformat("OAuth exception occured: "."Can't connect LDAP"));
	$oauth->showError("system_error01", $auth_params["client_id"]);
    exit();
}
if ($auth_params['client_id']) {
    $smarty->assign('client_id', $auth_params['client_id']);
}
if ($client) {
	$smarty->assign('crmode1', $client["crmode1"]);
	$smarty->assign('crmode2', $client["crmode2"]);
	$smarty->assign('crmode3', $client["crmode3"]);
	$smarty->assign('samode1', $client["samode1"]);
	$smarty->assign('samode2', $client["samode2"]);
	$smarty->assign('samode3', $client["samode3"]);
	$smarty->assign('name', $client["name"]);
	$smarty->assign('serverurl', $client["serverurl"]);
	$smarty->assign('logouturl', $client["logouturl"]);
	$smarty->assign('pattern', $client["pattern"]);
	$smarty->assign('logoutlink', $client["logoutlink"]);
	$smarty->assign('ticket_name', $client["ticket_name"]);
	$smarty->assign('skip_post_url_decode', $client["skip_post_url_decode"]);
	//$smarty->assign('client_secret', $client["client_secret"]);
	$smarty->assign('redirect_uri', $client["redirect_uri"]);
	$smarty->assign('scope_flag', $client["scope_flag"]);
	$smarty->assign('id_hash_flag', $client["id_hash_flag"]);
	$smarty->assign('salt', $client["salt"]);
	$smarty->assign('provider', $client["provider"]);
	$smarty->assign('icon_url', $client["icon_url"]);
	$smarty->assign('email', $client["email"]);
}

// お客様の情報設定
$scope = $oauth->displayScopeJP($auth_params['scope'], $conf['japanese_scopes']);
$smarty->assign('scope', $scope);

// 認可画面を表示
$smarty->display('authroize.tpl');

$log->notice(logformat("OAuth show authorization page succeeded for ".$auth_params['client_id']));
//==============================================================================

?>
