<?php

/**
 * @file
 * Authorized applications list.
 *
 * 連携アプリ一覧を表示させる
 *
 */

$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'] = 'applist';

// 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();
}

$service_id = $_POST['service_id'];
// 連携設定画面表示する際に、更新処理行うかどうかを事前判断
if (isset($_POST['csrf']) && checkCsrf($_POST['csrf']) && preg_match('/[a-zA-Z0-9]+/', $service_id)) {
	$isDoRevoke = TRUE;
	$conf['endpoint'] = 'applist_w';
}
else {
	$isDoRevoke = FALSE;
}

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

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


// 許可を取り消す
$revoked_service = '';
if ($isDoRevoke) {
	if ($oauth->removeAuthorizedApps($username, $service_id)) {
		// 許可を取り消す成功の場合
		$log->notice(logformat("OAuth canccel user authorization succeed for $service_id"));
		if ($_POST['service_name']) {
			$revoked_service = $_POST['service_name'];
		}
		else {
			try {
				$client = $oauth->getClient($service_id);
				$revoked_service = $client["name"];
			}
			catch (Exception $e) {
				$log->err(logformat("OAuth exception occured: Can't connect LDAP"));
			}
		}
	}
	else {
		// 許可を取り消す失敗の場合
		$log->err(logformat("OAuth revoke user authorization failed for $service_id: system error"));
		// TODO
		$oauth->showError("system_error04");
	    exit();
	}
}


// 連携アプリリスト取得
$applist = array();
$servicelist = $oauth->getAuthorizedApps($username, NULL, '0');
if ($servicelist !== FALSE) {
	foreach ($servicelist as $app) {
		try {
			$client = $oauth->getClient($app['oauth_service_id']);
			$app['samode1'] = $client["samode1"];
			$app['samode2'] = $client["samode2"];
			$app['samode3'] = $client["samode3"];
			$app['samode1'] = $client["samode1"];
			$app['samode2'] = $client["samode2"];
			$app['samode3'] = $client["samode3"];
			$app['name'] = $client["name"];
			$app['serverurl'] = $client["serverurl"];
			$app['logouturl'] = $client["logouturl"];
			$app['pattern'] = $client["pattern"];
			$app['logoutlink'] = $client["logoutlink"];
			$app['ticket_name'] = $client["ticket_name"];
			$app['skip_post_url_decode'] = $client["skip_post_url_decode"];
			//$app['client_secret'] = $client["client_secret"];
			$app['redirect_uri'] = $client["redirect_uri"];
			$app['scope_flag'] = $client["scope_flag"];
			$app['id_hash_flag'] = $client["id_hash_flag"];
			$app['salt'] = $client["salt"];
			$app['provider'] = $client["provider"];
			$app['icon_url'] = $client["icon_url"];
			$app['email'] = $client["email"];

			if ($client["scope_flag"]) {
				// Use default scope if not specified
				if (!$app['scope']) {
					$app['scope'] = $conf['default_scopes'];
				}
				$app['scope'] = $oauth->displayScopeJP($app['scope'], $conf['japanese_scopes']);
			}
			else {
				// 認可画面表示しないアプリは連携設定画面にも表示しない
				continue;
			}

			// 一覧に追加
			$applist[] = $app;
		}
		catch (Exception $e) {
			$log->err(logformat("OAuth exception occured: Can't connect LDAP"));
			$oauth->showError("system_error01", $app['oauth_service_id']);
		    exit();
		}
	}
	$log->notice(logformat("OAuth get user authorized applist succeeded."));
}
else {
	$log->err(logformat("OAuth get user authorized applist failed: MySQL error"));
	$oauth->showError("system_error04");
    exit();
}

//==============================================================================
// 画面作成
$smarty = new Smarty();
$smarty->template_dir = 'templates';
$smarty->compile_dir = 'templates_c';

setCsrf();
$smarty->assign('csrf', $_SESSION['csrf']);
$smarty->assign('revoked_service', $revoked_service);

$smarty->assign('additional_data', $inputname);
$smarty->assign('username', $username);
$smarty->assign('pleasyid', $pleasyid);

$smarty->assign('applist', $applist);

$smarty->display('applist.tpl');

?>
