spaceapi/update_open_state.php

86 lines
2.3 KiB
PHP

<?php
/**
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <nupilios@flexibledeveloper.eu> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return.
* ----------------------------------------------------------------------------
*/
function validateRequest(array $post)
{
$authorizationString = '';
$isLabOpen = '';
if (array_key_exists('authorization', $post)) {
$authorizationString = urlencode($post['authorization']);
validateAuthorizationKey($authorizationString);
} else {
echo 'Please send an authorization';
exit;
}
if (array_key_exists('open', $post)) {
$isLabOpen = urlencode($post['open']);
if ('false' === $isLabOpen || 'true' === $isLabOpen) {
saveStateToFile($isLabOpen);
} else {
print 'wrong';
}
}
print $isLabOpen;
}
function validateAuthorizationKey(string $authorizationString)
{
$authorizationServerValue = '';
$filename = './authorization';
if (!$handle = fopen($filename, 'r')) {
echo 'Authorization failed';
exit;
}
if ($fileHandle = fopen($filename, 'r')) {
$authorizationServerValue = fread($fileHandle, filesize($filename));
fclose($fileHandle);
}
if (strlen($authorizationServerValue) < 30) {
echo 'Key not valid';
exit;
}
if ($authorizationServerValue !== $authorizationString) {
echo 'Authorization failed';
exit;
}
}
function saveStateToFile(string $isLabOpen)
{
$filename = './openState';
if (is_writeable($filename)) {
// Open filename to write content, start at the first position in the file
// overwrite all content
if (!$handle = fopen($filename, 'w')) {
echo sprintf('Cannot open file (%s)', $filename);
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $isLabOpen) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo sprintf('Success, wrote (%s) to file (%s)', $isLabOpen, $filename);
fclose($handle);
}
}
validateRequest($_POST);