OWE/index.php

186 lines
5.9 KiB
PHP

<?php
function get_color_from_ip($ip) {
$ip_elem = explode(".", $ip);
$css = "background-color: hsl(";
$number = abs(crc32($ip));
$css .= ($number % 360).", ";
$css .= (50 + (($number >> 3) % 51))."%, ";
$css .= (50 + (($number >> 5) % 51))."%);";
return $css;
}
//header("refresh: 28");
header("Cache-Control: no-cache, no-store, must-revalidate");
if (array_key_exists("submitted", $_REQUEST)) {
$word = urldecode($_REQUEST["submitted"]);
//print("Jemand schreibt ".$word."<br>");
$sentences = fopen("./data/sentences.txt", "a") or die("unable to open sentences file");
$content = "<span style='";
$content .= get_color_from_ip($_SERVER['REMOTE_ADDR'])."'>";
$ends_of_sentence = ['.', '!', '?'];
if (preg_match("/\p{L}/", $word[0])) { // check if first character is letter (including ä, ê, ß stuff)
$content .= " ";
}
$content .= htmlentities($word);
$content .= "</span>";
if (in_array($word[-1], $ends_of_sentence)) {
$content .= "<br>\n";
}
if (!empty($word)) {
fwrite($sentences, $content);
}
fclose($sentences);
header("location: ".htmlentities($_SERVER['PHP_SELF']));
}
$raw_json_config = file_get_contents("data/config.json");
$config_data = json_decode($raw_json_config, false);
?>
<html>
<head>
<title><?php print($config_data->title ?? "One Word Each"); ?></title>
<link rel="stylesheet" href="style.css?newinputarea">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA==" crossorigin="anonymous" />
<link rel="icon" href="<?php print($config_data->logo->icon_path ?? "favicon.ico"); ?>" type="image/x-icon">
</head>
<body>
<table>
<tr>
<td width="50%"><img src="<?php print($config_data->logo->image_path ?? "OWE_Logo.png"); ?>" width="90%"></td>
<td><h1><?php print($config_data->headline ?? "One Word Each Seite"); ?></h1></td>
</tr>
</table>
<p>
<?php
$content = file_get_contents("./data/archive-links.txt") or die("ungültiger Dateiname");
print($content);
?>
</p>
<p class="sentences">
<?php
//print(file_get_contents("./data/sentences.txt"));
?>
</p>
<button onclick="onReloadClicked()" id="but-reload">aktualisieren</button>
<br>
<form action="./#wordform" method="post" autocomplete="off" id="wordform"></form>
<div class="word_input_area">
<input type="text" name="submitted" id="wordinput" form="wordform" placeholder="Nächstes Wort"> <button type="submit" form="wordform" class="send_button"><i class="far fa-paper-plane"></i></button>
</div>
<script>
var previousTextLength;
var config_data;
var unread_words = 0;
document.getElementById("wordinput").focus();
function loadSentences(alertIfNew = false) {
fetch("./data/sentences.txt", {headers: {"Cache-Control": "no-cache, no-store"}})
.then((response) => {
return response.text().then((text) => {
document.querySelector(".sentences").innerHTML = text;
if (text.length > previousTextLength) {
document.getElementsByTagName("title")[0].innerText = (config_data.title ? config_data.title : "One Word Each") + " (" + ++unread_words + ")";
if (alertIfNew) {
var newtxt = text.substring(previousTextLength, text.length);
//var parser = new DOMParser();
//var xmltxt = parser.parseFromString(newtxt, "text/xml");
//var newword = xmltxt.getElementsByTagName("span")[0].innerHTML.trim();
var htmltxt = document.createElement("html");
htmltxt.innerHTML = newtxt;
var newword = htmltxt.getElementsByTagName("span")[0].innerHTML.trim();
if (Notification.permission == 'granted') {
displayNotification(newword);
}
else {
alert("Neues Wort: " + newword);
}
}
}
previousTextLength = text.length;
// color
var spans = document.querySelector(".sentences").getElementsByTagName("span");
// we expect this to be from the user who's turn it is now (3 users)
var histurnspan = spans[spans.length - 3];
//console.log(histurnspan.getAttribute("style"));
document.getElementById("wordinput").setAttribute("style", histurnspan.getAttribute("style"));
});
});
}
function loadConfig() {
fetch("./data/config.json").then((response) => {
return response.text().then((text) => {
config_data = JSON.parse(text);
});
});
}
function onReloadClicked() {
loadSentences();
document.querySelector("#but-reload").style.visibility = "hidden";
setTimeout(function(){
document.querySelector("#but-reload").style.visibility = "initial";
}, 100);
}
function displayNotification(word) {
if (Notification.permission == 'granted') {
navigator.serviceWorker.getRegistration().then(function(reg) {
reg.showNotification("Neues Wort auf " + (config_data.title ? config_data.title : "OWE"),
{ body: word, icon: config_data.logo.image_path ? config_data.logo.image_path : "OWE_Logo.png", requireInteraction: true });
});
}
}
window.onfocus = function() {
unread_words = 0;
document.getElementsByTagName("title")[0].innerText = (config_data.title ? config_data.title : "One Word Each");
}
//setTimeout(loadSentences, 500);
loadConfig();
loadSentences();
setInterval(loadSentences, 5000, true);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js')
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
})
.catch(function(error) {
console.log('Service worker registration failed, error:', error);
});
}
navigator.serviceWorker.register('./service-worker.js', {
scope: './'
});
navigator.serviceWorker.register('./service-worker.js', {
scope: '.'
});
Notification.requestPermission(function(status) {
console.log('Notification permission status:', status);
});
</script>
</body>
</html>