<?php

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */


$pubkey = $VARS["publickey"];
$name = $VARS["name"] ?? null;
$email = filter_var($VARS["email"] ?? "", FILTER_VALIDATE_EMAIL) ? $VARS["email"] : null;
$location = $VARS["location"] ?? null;
$commissionexpires = (empty($VARS["expires"]) || strtotime($VARS["expires"]) === false || strtotime($VARS["expires"]) <= time()) ? null : date("Y-m-d H:i:s", strtotime($VARS["expires"]));
$idnumber = $VARS["idnumber"] ?? null;
$state = $VARS["state"] ?? null;

$unarmored = OpenPGP::unarmor($pubkey, 'PGP PUBLIC KEY BLOCK');
$key = OpenPGP_Message::parse($unarmored);

$fingerprint = null;
foreach ($key->packets as $pkt) {
    if ($pkt instanceof OpenPGP_PublicKeyPacket) {
        $fingerprint = $pkt->fingerprint;
    } else if ($pkt instanceof OpenPGP_UserIDPacket) {
        $name = $pkt->name ?? $name;
        $email = $pkt->email ?? $email;
    }
}

if ($database->has("notary_registry", ["fingerprint" => $fingerprint])) {
    sendJsonResp("A public key with fingerprint $fingerprint has already been submitted to the registry. If you need to make changes to the information in the registry, put your old and new information in a PDF file, sign it with your private key, and email the PDF to notary@netsyms.com.", "ERROR");
}

$database->insert("notary_registry", [
    "fingerprint" => $fingerprint,
    "fingerprint_short" => substr($fingerprint, -16),
    "fingerprint_tiny" => substr($fingerprint, -8),
    "name" => $name,
    "email" => $email,
    "location" => $location,
    "commissionexpires" => $commissionexpires,
    "idnumber" => $idnumber,
    "state" => $state,
    "publickey" => $pubkey
]);

sendJsonResp("Your public key and notary profile have been submitted to the registry.", "OK");