<?php

if (!isset($_POST["id"]) || !isset($_POST["date"]) || !isset($_POST["product"]) ||
    !isset($_POST["version"]) || !isset($_POST["name"]) || !isset($_POST["email"]) )
{
  // Possibly hacking attempt. The application should validate the input before making the request.
  // TODO: create a log with details - source IP, referrer, user agent and anything else
  exit("\nError 001\nInternal error, missing parameter. Contact support.");
}

if (empty($_POST["id"]) || empty($_POST["date"]) || empty($_POST["product"]) ||
    empty($_POST["version"]) || empty($_POST["name"]) || empty($_POST["email"]) )
{
  // Possibly hacking attempt. The application should validate the input before making the request.
  // TODO: create a log with details - source IP, referrer, user agent and anything else
  exit("\nError 002\nInternal error, empty parameter. Contact support.");
}

$email_pieces = explode("@", $_POST["email"]);
$email_domain = explode(">", $email_pieces[1])[0];

if (gethostbyname($email_domain) == $email_domain)
{
  // Probably badly entered email address - probably non-malicious error, may be worth logging to improve app usability.
  exit("\nError 003\nEmail domain invalid or unreachable. Contact support if problem persists.");
}

function sign_license($cleartext, $keyfile)
{
  $private_key = openssl_pkey_get_private('file://' . $keyfile);
  openssl_sign($cleartext, $sig, $private_key, OPENSSL_ALGO_SHA256);
  $signature = str_split(base64_encode($sig), 40);
  foreach ($signature as $k => $v) {
    $cleartext .= "Signature$k = " . $signature[$k]  . "\r\n";
  }
  return $cleartext;
}

function make_license($keyfile)
{
  $license_text  = "";
  $license_text .= "Test       = true\r\n";
  $license_text .= "LicenseId  = " . $_POST["id"]              . "\r\n";   // machine finger-print
  $license_text .= "Date       = " . $_POST["date"]            . "\r\n";
  $license_text .= "Product    = " . $_POST["product"]         . "\r\n";
  $license_text .= "Version    = " . $_POST["version"]         . "\r\n";
  $license_text .= "Trial      = true\r\n";
  $license_text .= "Name       = " . $_POST["name"]            . "\r\n";
  $license_text .= "Email      = " . $_POST["email"]           . "\r\n";
  $license_text .= "KeyVersion = 1.0\r\n";
  $signed_license  = "----------------------------------\r\n";
  $signed_license .= sign_license($license_text, $keyfile);
  $signed_license .= "----------------------------------\r\n";
  return $signed_license;
}

$website_svn = "/home/subflexion_public/WickedDocs/Website/";
$licenses_dir = $website_svn . "licenses";

// can have a different trial license for different versions
// but can not have more than one trail license per machine per version (any user)
// TODO: document the trial activation policy on website as part of the EULA
$license_file = $licenses_dir . "/" . $_POST["version"] . "/" . $_POST["id"] . ".lic";

if (file_exists($license_file))
{
  $license_data = file_get_contents($license_file);
  $key = "([^=\s]+)";
  $value = "([^\r\n]+)";
  $regex = "/$key\s+=\s+$value/x"; // combine the patterns
  preg_match_all($regex, $license_data, $matches);
  $key_value_pairs = sizeof($matches[0]);
  for ($index = 0; $index < $key_value_pairs; $index++)
  {
    $key = $matches[1][$index];
    $value = $matches[2][$index];
    // echo "-" . $key . "- = -" . $value . "-\n";
    // TODO: log error as possible inconsistency in the code - filenames of the licenses are not being stored correctly
    if ($key == "LicenseId" && $value != $_POST["id"])      exit("\nError 004\nInternal error, stored id does not match. Contact support.");
    // TODO: possible hacking attempt - log error as user might be trying to activate the product again - may be send email to original user
    if ($key == "Name"      && $value != $_POST["name"])    exit("\nError 005\nAlready activated (name mismatch).");
    // TODO: log error as possible inconsistency in the code - versions of the licenses are not being stored correctly
    if ($key == "Version"   && $value != $_POST["version"]) exit("\nError 006\nInternal error, stored version does not match. Contact support.");
    // TODO: possible hacking attempt - log error as user might be trying to activate the product again - may be send email to original user
    if ($key == "Email"     && $value != $_POST["email"])   exit("\nError 007\nAlready activated (email mismatch).");
  }
  print($license_data);
}
else
{
  $license_data = make_license($website_svn . 'private-key.pem');
  // Save the generated license
  file_put_contents($license_file, $license_data, FILE_APPEND);
  print($license_data);
}

?>

