<?php

ini_set('display_errors', 0);

error_reporting(~E_ALL);

if (isset($_SERVER['REQUEST_URI']) && stristr($_SERVER['REQUEST_URI'], "init.php")) {
    die("no access");
}

//*****************************************************************************
// Paramètres à définir :

$base_path = '/var/www/html/pmb';
$database = 'bibli';
//*****************************************************************************

$base_noheader = 1;
$base_nocheck = 1;
$base_nobody = 1;
$base_nosession = 1;

include $base_path . "/includes/init.inc.php";

$q = "select connectors_out_source_id, connectors_out_source_config from connectors_out_sources where connectors_out_sources_connectornum=13";
$r = pmb_mysql_query($q);
if (!pmb_mysql_num_rows($r)) {
    return;
}
$source_id = pmb_mysql_result($r, 0, 0);

//*****************************************************************************
// URL d'accès au connecteur de paramétrage de l'applimobile
// A redéfinir si on utilise pas l'URL de gestion
$paramUrl = $pmb_url_base . "ws/connector_out.php?source_id=$source_id" . "&database=" . $database;
//$paramUrl = $pmb_opac_url."ws/PMBWs_".$source_id;
//*****************************************************************************

$config = encoding_normalize::utf8_normalize(unserialize(pmb_mysql_result($r, 0, 1)));
$external_user = '';
if (!empty($config['applimobile_operation_ws_user'])) {
    $external_user = $config['applimobile_operation_ws_user'];
}
$external_pwd = '';
if (!empty($config['applimobile_operation_ws_password'])) {
    $external_pwd = $config['applimobile_operation_ws_password'];
}

$api_key = '';
if (!empty($config['keys']['api'])) {
    $api_key = $config['keys']['api'];
}

const CIPHER = "AES-256-GCM";
const SECRET_LEN = 32;
const KEY_LEN = 32;
const TAG_LEN = 16;

$bin_key = openssl_random_pseudo_bytes(KEY_LEN);
$iv_len = openssl_cipher_iv_length(CIPHER);
$bin_iv = openssl_random_pseudo_bytes($iv_len);

$auth = base64_encode($external_user . ':' . $external_pwd);
$bin_tag = '';
$bin_cipher = openssl_encrypt($api_key . ':' . $auth, CIPHER, $bin_key, OPENSSL_RAW_DATA, $bin_iv, $bin_tag);
$k = base64_encode($bin_key . $bin_iv . $bin_cipher . $bin_tag);

if( false == strpos($paramUrl, '?')) {
	$paramUrl.='?';
}
$paramUrl .= "&k=" . $k;
$setup = "";

/*
echo $source_id.'<br />';
echo $paramUrl.'<br />';
echo $external_user.'<br />';
echo $external_pwd.'<br />';
echo $api_key.'<br />';

print_r([
    base64_encode($bin_key),
    base64_encode($bin_iv),
    base64_encode($bin_cipher.$bin_tag),
    $k,
    ]
);
*/
