<?php
define ('SAVE_DIR', "${_SERVER['DOCUMENT_ROOT']}/drafts/");

$json = getParamJSON ();

if (!(isset ($json['data'])))
  {
    sendResult (false, 'Empty query Parameter: data');

    exit (1);
  }

if (!(preg_match ('/^data:image\/png;base64,/', $json['data'])))
  {
    sendResult (false, 'Not Allow data type: data');

    exit (1);
  }

$data = $json['data'];
$data = str_replace ('data:image/png;base64,', '', $data);
$data = str_replace (' ', '+', $data);
$image = base64_decode ($data);

$file = sprintf ('%s.png', $_GET['id']);
$result = file_put_contents (SAVE_DIR . $file, $image, LOCK_EX);

setcookie ('backup', $file, time () + 60 * 60 * 24 * 30);


function
getParamJSON ():
array
{
  $buff = file_get_contents ('php://input');
  $json = json_decode ($buff, true);

  return ($json);
}

function
sendResult (
    $status,
    $data):
string
{
  header ('Access-Control-Allow-Origin: *');
  header ('Access-Control-Allow-Headers: *');

  echo json_encode(["status" => $status,
                    "result" => $data]);
}
?>

