getProfile.php 5.49 KB
<?php
declare(strict_types=1);

use \Firebase\JWT\JWT;

require __DIR__ . '/vendor/autoload.php';

// .storeフォルダにアクセストークン、エラーログを出力する
// .storeの権限を設定する必要あり(apache or www-data)
$store_folder = "/var/www/.store/";
// 研究者番号
$erad_id = null;
if (array_key_exists('erad_id', $_GET)){
    $erad_id = $_GET['erad_id'];
}
if (is_null($erad_id)) {
    header('Content-Type: application/json; charset=utf8');
    header('Access-Control-Allow-Origin: https://www.nifs-k.ac.jp');
    print(json_encode([], JSON_FORCE_OBJECT));
    exit;
}

$type = $_GET["type"];
$start = $_GET["start"];
$limit = 1000;

function api_request (string $url, array $header, string $method, ?array $post_params = null) {
    global $store_folder;

    $curl = curl_init($url);
    $setopt_array = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_URL => $url,
        CURLOPT_HTTPHEADER => $header,
    ];
    $post_fields = '';
    if (is_null($post_params) === false) {
        $post_fields = http_build_query($post_params);
        $setopt_array[CURLOPT_POSTFIELDS] = $post_fields;
    }
    curl_setopt_array($curl, $setopt_array);
    $api_responese = curl_exec($curl);
    if ($api_responese === false) {
        // 失敗
        $errno = curl_errno($curl);
        $error = curl_error($curl);

        $ymd = date('Ymd');
        $file = $store_folder . "error_{$ymd}.txt";

        $error_message = '[' . date('Y-m-d H:i:s') . ']'
            . 'ErrorNo:' . $errno . "\n"
            . 'Error:' . $error . "\n"
            . 'URL:' . $url . "\n"
            . 'Method:' . $method . "\n"
            . 'header:' . print_r($header, true) . "\n"
            . 'post_fields:' . $post_fields . "\n";
        file_put_contents($file, $error_message, FILE_APPEND | LOCK_EX);
    }
    // ステータスコード取得
    $http_status_code = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
    if (($http_status_code < 200) || ($http_status_code >= 300)) {
        $ymd = date('Ymd');
        $file = $store_folder . "error_{$ymd}.txt";
        $error_message = '[' . date('Y-m-d H:i:s') . ']'
            . 'HTTP Status Code:' . $http_status_code . "\n"
            . 'response:' . $api_responese . "\n"
            . 'URL:' . $url . "\n"
            . 'Method:' . $method . "\n"
            . 'header:' . print_r($header, true) . "\n"
            . 'post_fields:' . $post_fields . "\n";
        file_put_contents($file, $error_message, FILE_APPEND | LOCK_EX);
        return false;
    }
    return $api_responese;
}

// アクセストークン
$access_token = null;
// 保存している情報からアクセストークン取得
$access_token_file = $store_folder . "access_token.txt";
if (file_exists($access_token_file)) {
    $access_token_text = file_get_contents($access_token_file);
    $access_token_json = json_decode($access_token_text, true);
    if (is_null($access_token_json) === false) {
        $expire = $access_token_json['expire'];
        $expiration = (new DateTime())->format('U');
        // 有効期限確認
        if ($expiration < $expire) {
            $access_token = $access_token_json['access_token'];
        }
    }
}
if (is_null($access_token)) {
    // トークン取得URL
    $url = 'https://api.researchmap.jp/oauth2/token';
    // キー取得
    $client_key = file_get_contents('/var/www/.rmap_keys/rmap_client_id.key');
    $client_key = rtrim($client_key);
    $private_key = file_get_contents('/var/www/.rmap_keys/rmap_jwt_private.key');

    // JWTの発行時間と有効期限を設定
    $date_time = new DateTime(date('Y-m-d H:i:s'));
    $date_time->setTimezone(new DateTimeZone('UTC'));
    // JWTの発行時間
    $iat = $date_time->format('U');
    // JWTの有効期限
    $expiration = $date_time->modify('+30 minutes')->format('U');

    $claim = [
        'iss' => $client_key,
        'aud' => $url,
        'sub' => "0",
        'exp' => $expiration,
        'iat' => $iat
    ];

    $jwt = JWT::encode($claim, $private_key, 'RS256');

    $post_params = [
        "grant_type"  => "urn:ietf:params:oauth:grant-type:jwt-bearer",
        "assertion"   => $jwt,
        "version"     => "2"
    ];

    $header = [
    "Content-Type:  application/x-www-form-urlencoded;"
    ];

    $api_responese = api_request($url, $header, 'POST', $post_params);
    if ($api_responese) {
        $response = json_decode($api_responese, true);
        $access_token = $response['access_token'];
        $response['expire'] = $expiration;
        file_put_contents($access_token_file, json_encode($response));
    }
}
// プロフィール情報取得
$profile = [];
if (is_null($access_token) === false) {
    $url = "https://api.researchmap.jp/erad_id:{$erad_id}";
    if (!empty($type)) {
        $url = $url . '/' . $type . '?limit=' . $limit;
    };

    if (!empty($start)) {
        $url = $url . '&start=' . $start;
    }

    $header = array(
        "Authorization: Bearer $access_token",
        "Accept: application/ld+json,application/json;q=0.1",
        "Accept-Encoding: gzip",
        // "X-HTTP-Method-Override: GET",
        // "Content-Type: application/json;"
        // "Content-Type: application/x-www-form-urlencoded;"
    );
    $api_responese = api_request($url, $header, 'GET', null);
    if ($api_responese) {
        $profile = json_decode($api_responese, true);
    }
}
header('Content-Type: application/json; charset=utf8');
header('Access-Control-Allow-Origin: https://www.nifs-k.ac.jp');
print(json_encode($profile, JSON_FORCE_OBJECT));