server log

This commit is contained in:
Lukas Schaefer
2021-05-08 18:53:23 -04:00
commit 6465ed6f78
31 changed files with 1100 additions and 0 deletions

Binary file not shown.

BIN
__pycache__/router.cpython-37.pyc Executable file

Binary file not shown.

18
html/.htaccess Executable file
View File

@@ -0,0 +1,18 @@
<IfModule mod_rewrite.c> # Will check if maintenance mode is enabled and will redirect to maintenance.php if that is true
# activate mod_rewrite
RewriteEngine On
# check if a file exists called "maintenance-mode-on" in the document root
RewriteCond %{DOCUMENT_ROOT}/maintenance-mode -f
# safety check to prevent redirect loops
RewriteCond %{REQUEST_URI} !/maintenance.php$
# redirect internally all requests to maintenance.php
RewriteRule $ /maintenance.php [L]
</IfModule>
#Will redirect from all json files
RedirectMatch 403 \.(json)$
#All invalid sites are directed to the main page index.php
ErrorDocument 403 /index.php
ErrorDocument 404 /index.php

62
html/css/website.css Executable file
View File

@@ -0,0 +1,62 @@
body {
background-color: black;
color: white;
font-family: 'Calibri';
}
.main {
margin-left: 200px;
}
h1 {
font-size: 50px;
}
h2 {
color: red;
}
.vertical-menu {
background-color: green;
padding-top: 50px;
width: 200px;
height: 100%;
font-size: 20px;
z-index: 1;
top: 0;
left: 0;
position: fixed;
}
.vertical-menu a {
padding: 6px 6px 6px 30px;
background-color: green;
color: white;
display: block;
padding: 12 px;
text-decoration: none;
}
.vertical-menu a:hover {
background-color: darkgreen;
font-size: 22px;
}
.vertical-menu a.active {
background-color: black;
}
button {
color: white;
background-color: black;
}
input[type=submit] {
color: white;
background-color: black;
}
select {
color: white;
background-color: black;
}

1
html/data.json Executable file
View File

@@ -0,0 +1 @@
[["Apr", "26", "2021", "08", "26", "00", "4"], ["Apr", "26", "2021", "08", "26", "00", "4"], ["Apr", "26", "2021", "08", "26", "00", "4"], ["May", "07", "2021", "20", "12", "13", "5"], ["May", "07", "2021", "20", "12", "13", "5"], ["May", "07", "2021", "20", "12", "13", "5"], ["May", "07", "2021", "20", "12", "13", "5"], ["May", "07", "2021", "20", "13", "18", "5"], ["May", "07", "2021", "20", "13", "18", "5"], ["May", "07", "2021", "20", "13", "18", "5"], ["May", "07", "2021", "20", "13", "18", "5"], ["May", "07", "2021", "20", "13", "50", "5"], ["May", "07", "2021", "20", "13", "50", "5"], ["May", "07", "2021", "20", "13", "50", "5"], ["May", "07", "2021", "20", "13", "50", "5"], ["May", "07", "2021", "20", "14", "47", "5"], ["May", "07", "2021", "20", "14", "47", "5"], ["May", "07", "2021", "20", "14", "47", "5"], ["May", "07", "2021", "20", "14", "47", "5"], ["May", "07", "2021", "20", "15", "48", "5"], ["May", "07", "2021", "20", "15", "48", "5"], ["May", "07", "2021", "20", "15", "48", "5"], ["May", "07", "2021", "20", "15", "48", "5"], ["May", "07", "2021", "20", "18", "22", "5"], ["May", "07", "2021", "20", "18", "22", "5"], ["May", "07", "2021", "20", "18", "22", "5"], ["May", "07", "2021", "20", "18", "22", "5"], ["May", "07", "2021", "20", "19", "53", "5"], ["May", "07", "2021", "20", "19", "53", "5"], ["May", "07", "2021", "20", "20", "01", "5"], ["May", "07", "2021", "20", "20", "01", "5"], ["May", "07", "2021", "20", "20", "20", "5"], ["May", "07", "2021", "20", "20", "20", "5"], ["May", "07", "2021", "20", "20", "20", "5"], ["May", "07", "2021", "20", "20", "20", "5"], ["May", "07", "2021", "20", "21", "04", "5"], ["May", "07", "2021", "20", "21", "04", "5"], ["May", "07", "2021", "20", "21", "32", "5"], ["May", "07", "2021", "20", "21", "32", "5"], ["May", "07", "2021", "20", "22", "06", "5"], ["May", "07", "2021", "20", "22", "06", "5"], ["May", "07", "2021", "20", "22", "40", "5"], ["May", "07", "2021", "20", "22", "40", "5"], ["May", "07", "2021", "20", "24", "35", "5"], ["May", "07", "2021", "20", "24", "35", "5"], ["May", "07", "2021", "20", "26", "00", "5"], ["May", "07", "2021", "20", "26", "00", "5"], ["May", "07", "2021", "20", "27", "39", "5"], ["May", "07", "2021", "20", "27", "39", "5"], ["May", "07", "2021", "20", "27", "39", "5"], ["May", "07", "2021", "20", "27", "39", "5"], ["May", "07", "2021", "20", "29", "23", "5"], ["May", "07", "2021", "20", "29", "23", "5"], ["May", "07", "2021", "20", "29", "33", "5"], ["May", "07", "2021", "20", "29", "33", "5"], ["May", "07", "2021", "20", "29", "48", "5"], ["May", "07", "2021", "20", "29", "48", "5"], ["May", "07", "2021", "20", "30", "01", "5"], ["May", "07", "2021", "20", "30", "01", "5"], ["May", "07", "2021", "20", "30", "26", "5"], ["May", "07", "2021", "20", "30", "26", "5"], ["May", "07", "2021", "20", "31", "01", "5"], ["May", "07", "2021", "20", "31", "01", "5"], ["May", "07", "2021", "20", "31", "27", "5"], ["May", "07", "2021", "20", "31", "27", "5"], ["May", "07", "2021", "20", "31", "35", "5"]]

66
html/electricity.php Executable file
View File

@@ -0,0 +1,66 @@
<!DOCTYPE html>
<html>
<head>
<title>
Schaefer Family
</title>
<?php
include 'include/all.php';
?>
</head>
<body>
<?php
include 'include/menu.php';
echo "<div class='main'>";
?>
<h1>Electricity Log</h1>
<?php
// Gets the data.json file and goes through every line to output the data.
$jsonInfo = file_get_contents("data.json");
$jsonData = json_decode($jsonInfo, true);
$internet = True;
$electricity = True;
foreach ($jsonData as $date) {
if ($internet == True) {
$internet = False;
if ($electricity == True) {
echo "Electricity on from ";
$electricity = False;
} else {
echo "Electricity off from ";
$electricity = True;
}
echo "$date[0] $date[1], $date[2] at $date[3]:$date[4]";
echo " to ";
} else {
$internet = True;
echo "$date[0] $date[1], $date[2] at $date[3]:$date[4]";
echo "<br>";
}
}
// Resets the outage reporter when requested by deleting all of data.json and using the last entry and putting that in twice into the json
if ($PRIVILEGE["deleteElectricity"]) {
if ($_POST["reset"] == True) {
echo "Resetting Outage Reporter";
$jsonInfo = file_get_contents("data.json");
$jsonFile = fopen("data.json", "w");
$jsonData = json_decode($jsonInfo, true);
$important = $jsonData[count($jsonData) - 1];
$important = json_encode([$important, $important]);
fwrite($jsonFile, $important);
fclose($jsonFile);
header("Refresh:1; url=/electricity.php");
} else {
echo '<form method="post" action="/electricity.php">
<button name="reset" value="True" type="submit<br>">reset outage reporter</button>
</form>';
}
}
?>
</div>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 426 KiB

BIN
html/favicon/apple-touch-icon.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

BIN
html/favicon/favicon-16x16.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 869 B

BIN
html/favicon/favicon-32x32.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

BIN
html/favicon/favicon.ico Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

1
html/favicon/site.webmanifest Executable file
View File

@@ -0,0 +1 @@
{"name":"","short_name":"","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}

1
html/floppy.json Executable file
View File

@@ -0,0 +1 @@
{"kind":"youtube#searchListResponse","etag":"r-bAW9f7KuSqEfNyrWiyyo7osVY","regionCode":"US","pageInfo":{"totalResults":5,"resultsPerPage":5},"items":[{"kind":"youtube#searchResult","etag":"zohGGM0uHTB3FCp0VHuz-vxThgY","id":{"kind":"youtube#video","videoId":"nziK24_qBZw"}},{"kind":"youtube#searchResult","etag":"Vy0C7SAe07RU9z7ewv-qWQMSwaQ","id":{"kind":"youtube#video","videoId":"F3Px6CXS9r4"}},{"kind":"youtube#searchResult","etag":"f7sLZR5ACE413iASVK31aTdGxo4","id":{"kind":"youtube#video","videoId":"BlZFpV8ynok"}},{"kind":"youtube#searchResult","etag":"eoOCKt3qZsgmr72ijAvVlVcLvoY","id":{"kind":"youtube#video","videoId":"McHbiGwUPgo"}},{"kind":"youtube#searchResult","etag":"BrgS5NLFOCkKM3BHduUuJsgQP10","id":{"kind":"youtube#channel","channelId":"UCUkQSe5Dk-ch8QjONDMXEpw"}}],"date":1620338917}

44
html/floppy.php Executable file
View File

@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html>
<head>
<title>
Schaefer Family
</title>
<?php
include 'include/all.php';
?>
</head>
<body>
<?php
include 'include/menu.php';
echo "<div class='main'>";
?>
<h1>Floppy Videos!</h1>
<?php
$youtubeInfo = file_get_contents("floppy.json");
$youtubeInfo = json_decode($youtubeInfo, true);
$newData = false;
if ($youtubeInfo["date"] + 3600 < time()) {
$newData = true;
}
if ($newData) {
$onlineFile = file_get_contents("https://www.googleapis.com/youtube/v3/search?part=id&channelId=UCUkQSe5Dk-ch8QjONDMXEpw&maxResults=50&order=date&key=AIzaSyB7tFlnH-GW24yDYYeWsNegN4ct_0wHqAI");
$youtubeInfo = json_decode($onlineFile, true);
$youtubeInfo["date"] = time();
$youtubeJson = json_encode($youtubeInfo);
$jsonFile = fopen("floppy.json", "w");
fwrite($jsonFile, $youtubeJson);
fclose($jsonFile);
}
foreach ($youtubeInfo["items"] as $link) {
if ($link["id"]["kind"] == "youtube#video") {
$ID = $link["id"]["videoId"];
echo "<iframe width='560' height='315' src='https://www.youtube-nocookie.com/embed/$ID' title='YouTube video player' frameborder='0' allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>";
}
}
?>
</div>
</body>
</html>

142
html/include/all.php Executable file
View File

@@ -0,0 +1,142 @@
<?php
function sanitize($value)
{
$validChars = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
$validChars = str_split($validChars);
$valueSplit = str_split($value);
$value = "";
foreach ($valueSplit as $char) {
if (array_search($char, $validChars) !== false) {
$value .= $char;
}
}
return $value;
}
function dbConnect()
{ // Is used to connect to the database
$SERVERNAME = "localhost";
$DATA_USERNAME = "website";
$KEY = "q1azcp2!las";
$connection = mysqli_connect($SERVERNAME, $DATA_USERNAME, $KEY, $DATA_USERNAME);
return $connection;
}
function dbRequest($result, $table, $searchCat, $searchCriteria, $Type)
{ //Sends a request to the database for a search
$connection = dbConnect();
if ($Type == 1) {
$response = mysqli_query($connection, "SELECT $result FROM $table WHERE $searchCat < $searchCriteria");
} elseif ($Type == 0) {
$response = mysqli_query($connection, "SELECT $result FROM $table WHERE $searchCat='$searchCriteria'");
} else {
$response = mysqli_query($connection, "SELECT $result FROM $table");
}
mysqli_close($connection);
if (mysqli_num_rows($response) > 0) {
$data = [];
while ($row = mysqli_fetch_assoc($response)) {
array_push($data, $row[$result]);
}
return $data;
} else {
return False;
}
}
function dbRemove($table, $searchCat, $searchCriteria, $Type)
{ // Deletes from the database a value
$connection = dbConnect();
if ($Type == 1) {
mysqli_query($connection, "DELETE FROM $table WHERE $searchCat < $searchCriteria");
} else {
mysqli_query($connection, "DELETE FROM $table WHERE $searchCat='$searchCriteria'");
}
mysqli_close($connection);
}
function dbEdit($table, $replace, $search, $type)
{ // Edits values in the database
$connection = dbConnect();
if ($type == 0) {
$command = "UPDATE $table SET ";
foreach ($replace as $replacers) {
$command .= "$replacers[0] = '$replacers[1]', ";
}
$command = substr($command, 0, -2);
$command .= " WHERE $search[0] = '$search[1]'";
$result = mysqli_query($connection, $command);
}
mysqli_close($connection);
}
function dbAdd($Term, $table)
{ // Adds to the database a new term
$connection = dbConnect();
$values = "";
foreach ($Term as $data) {
$values .= "'";
$values .= $data;
$values .= "'";
$values .= ', ';
}
$values = substr($values, 0, -2);
$result = mysqli_query($connection, "INSERT INTO $table VALUES ($values)");
mysqli_close($connection);
}
function root($user) {
$connection = dbConnect();
if (mysqli_num_rows(mysqli_query($connection, "SELECT * FROM privileges WHERE username='$user' AND privilege='root'")) > 0) {
return True;
} else {
return False;
}
mysqli_close($connection);
}
// Creates a way to see uncleaned user input if neccessary
$OGPOST = $_POST;
$OGGET = $_GET;
$OGCOOKIE = $_COOKIE;
// cleans all data
foreach ($_POST as $pointer=>$value) {
$_POST[$pointer] = sanitize($value);
}
foreach ($_GET as $pointer=>$value) {
$_GET[$pointer] = sanitize($value);
}
foreach ($_COOKIE as $pointer=>$value) {
$_COOKIE[$pointer] = sanitize($value);
}
// Contains the favicon and the css stylesheet
echo '<link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png">
<link rel="manifest" href="/favicon/site.webmanifest">
<link rel="stylesheet" type="text/css" href="/css/website.css" />';
// Removes all expired cookies from the database
$Time = mkTime();
dbRemove("cookies", "expire", $Time, 1);
$PRIVILEGELIST = ["root", "editUser", "deleteUser", "deleteElectricity", "deleteLog", "viewLog", "changeCredintials"];
// Checks the cookie value and sees if the database contains that value
$COOKIEID = $_COOKIE["user"];
if ($COOKIEID) {
$USERNAME = dbRequest("username", "cookies", "cookie", $COOKIEID, 0);
if ($USERNAME) {
setcookie("user", $COOKIEID, time() + 600, "/");
$USERNAME = $USERNAME[0];
$PRIVILEGES = dbRequest("privilege", "privileges", "username", $USERNAME, 0);
if (!$PRIVILEGES) {
$PRIVILEGES = ["sajdhsakjdjksshsadksagd"];
}
foreach ($PRIVILEGELIST as $option) {
if (array_search($option, $PRIVILEGES) !== false) {
$PRIVILEGE[$option] = True;
} else {
$PRIVILEGE[$option] = false;
}
}
$ROOTUSERS = dbRequest("username", "privileges", "privilege", "root", 0);
if ($PRIVILEGE["root"]) {
foreach ($PRIVILEGELIST as $type) {
if (!$PRIVILEGE[$type]) {
dbAdd([$USERNAME, $type], "privileges");
}
}
}
}
}

37
html/include/menu.php Executable file
View File

@@ -0,0 +1,37 @@
<?php
$MENUITEMS = [["Main Page", "/index.php"], ["Electricity Log", "/electricity.php"], ["Floppy", "/floppy.php"], ["Soccer", "/soccer.php"], ["privilege", "viewLog", "/log.php", "Server Log"], ["user", "/usermenu.php", "User Menu"], ["notUser", "/login.php", "Login/Signup"], ["user", "/login.php", "Logout"]];
echo "<div class='vertical-menu'>";
function menuItem($link, $name) {
$location = $_SERVER["PHP_SELF"];
if ($location == $link) {
echo "<a href='$link' class='active'>$name</a>";
} else {
echo "<a href='$link'>$name</a>";
}
}
foreach ($MENUITEMS as $menu) {
$menuLink = $menu[1];
$menuName = $menu[0];
switch ($menuName) {
case "notUser":
if (!$USERNAME) {
menuItem($menu[1], $menu[2]);
}
break;
case "user":
if ($USERNAME) {
menuItem($menu[1], $menu[2]);
}
break;
case "privilege":
if ($USERNAME and $PRIVILEGE[$menu[1]]) {
menuItem($menu[2], $menu[3]);
}
break;
default:
menuItem($menuLink, $menuName);
break;
}
}
echo "</div>";

26
html/index.php Executable file
View File

@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<title>
Schaefer Family - Main Page
</title>
<?php
include 'include/all.php';
?>
</head>
<body>
<?php
include 'include/menu.php';
?>
<div class='main'>
<h1>Welcome to the Schaefer Family website!</h1>"
<a href="/floppy.php">
<img src="/favicon/android-chrome-512x512.png">
</a>
</div>
</body>
</html>

1
html/internet.json Executable file
View File

@@ -0,0 +1 @@
["23", "0", "5", "0", "2147483000", "1"]

61
html/log.php Executable file
View File

@@ -0,0 +1,61 @@
<!DOCTYPE html>
<html>
<head>
<title>
Schaefer Family - Log Page
</title>
<?php
include 'include/all.php';
?>
</head>
<body>
<?php
include 'include/menu.php';
echo "<div class='main'>";
if ($USERNAME == NULL) {
echo "<h2>You are not logged in redirecting...</h2>";
header("Refresh:3; url=/login.php");
} elseif (array_search("viewLog", $PRIVILEGE) === false) {
header("Refresh:3; url=/index.php");
echo "<h2>Forbidden redirecting...</h2>";
} else {
// Will clear the log.json file except for the first entry. This entry contains important info
echo "<h1>Server Log</h1>";
if ($_GET["reset"] == True and array_search("deleteLog", $PRIVILEGE)) {
header("Refresh:2; url=log.php");
echo "<h3>Resetting Log</h3>";
$jsonInfo = file_get_contents("log.json");
$jsonFile = fopen("log.json", "w");
$jsonData = json_decode($jsonInfo, true);
$important = json_encode([$jsonData[0]]);
fwrite($jsonFile, $important);
fclose($jsonFile);
} else {
// Will echo the server log if logged in and create some buttons that link to other portions or do actions
$jsonInfo = file_get_contents("log.json");
$jsonData = json_decode($jsonInfo, true);
$first = True;
foreach ($jsonData as $data) {
if ($first) {
$first = False;
continue;
}
$date = $data[2];
echo "$data[1] at $date[3]:$date[4]:$date[5] on $date[0] $date[1], $date[2]<br>";
}
echo '<form method="get" action="/log.php">
<input type="submit" value="reload"><br>';
if (array_search("deleteLog", $PRIVILEGE)) {
echo '<button name="reset" value="True" type="submit<br>">reset log</button>';
}
}
}
?>
</div>
</body>
</html>

40
html/login.php Executable file
View File

@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html>
<head>
<title>
Schaefer Family
</title>
<?php
include 'include/all.php';
?>
</head>
<body>
<?php
include 'include/menu.php';
echo "<div class='main'>";
?>
<h1>Login or Signup Here</h1>
<?php
if ($USERNAME != NULL) {
setcookie("user", "", time() - 300);
$USERNAME = Null;
echo "You have logged out<br><br>";
}
// If logged out a login form will come
echo '<form method="post" action="/usermenu.php">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"/><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"/><br>
<input type="checkbox" id="signup" name="signup" value="True">
<label for="signup">Check this to signup</label><br>
<input type="submit" value="Login">
</form>';
?>
</div>
</body>
</html>

22
html/maintenance.php Executable file
View File

@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html>
<head>
<title>
Schaefer Family - Maintenance
</title>
<?php
include 'include/all.php';
header("Refresh:3; url=/index.php");
?>
</head>
<style>
body {
font-size: 50px;
color: red;
font-weight: 850;
}
</style>
<body>
The website is currently under maintenance please wait!
</body>

1
html/soccer.json Executable file
View File

@@ -0,0 +1 @@
{"kind":"youtube#searchListResponse","etag":"C5L3MAK448zCmZQg4dk292Ieop8","regionCode":"US","pageInfo":{"totalResults":7,"resultsPerPage":7},"items":[{"kind":"youtube#searchResult","etag":"Fi2Y_4hXQ-039pPJNEl0DnteB5c","id":{"kind":"youtube#video","videoId":"--rbJmLfunE"}},{"kind":"youtube#searchResult","etag":"Lwf6fo3T-SxSFvXwzn5og4KbqjE","id":{"kind":"youtube#video","videoId":"-20mUxbqSjs"}},{"kind":"youtube#searchResult","etag":"g-KTmdiFq8bNyLB-rwTku_JgyeE","id":{"kind":"youtube#video","videoId":"TqAnqR-jeR8"}},{"kind":"youtube#searchResult","etag":"jg6rkgP3VnykolUp8s7Arjpusy4","id":{"kind":"youtube#video","videoId":"aUYmf1MilDo"}},{"kind":"youtube#searchResult","etag":"h2w1MTTIhStTPdP3RQTGIb1pzTo","id":{"kind":"youtube#video","videoId":"ZA3ORzQ5D74"}},{"kind":"youtube#searchResult","etag":"ytAdiSh_aisxQiIVLMqjpGPhG9Q","id":{"kind":"youtube#video","videoId":"WaW3665X4xo"}},{"kind":"youtube#searchResult","etag":"4oCpnkp9MXifFTLd0vroHPPSq2U","id":{"kind":"youtube#channel","channelId":"UC3yfjZGDJutrB0kSYpd9u-A"}}],"date":1620338874}

44
html/soccer.php Executable file
View File

@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html>
<head>
<title>
Schaefer Family
</title>
<?php
include 'include/all.php';
?>
</head>
<body>
<?php
include 'include/menu.php';
echo "<div class='main'>";
?>
<h1>Soccer Videos!</h1>
<?php
$youtubeInfo = file_get_contents("soccer.json");
$youtubeInfo = json_decode($youtubeInfo, true);
$newData = false;
if ($youtubeInfo["date"] + 3600 < time()) {
$newData = true;
}
if ($newData) {
$onlineFile = file_get_contents("https://www.googleapis.com/youtube/v3/search?part=id&channelId=UC3yfjZGDJutrB0kSYpd9u-A&maxResults=50&order=date&key=AIzaSyB7tFlnH-GW24yDYYeWsNegN4ct_0wHqAI");
$youtubeInfo = json_decode($onlineFile, true);
$youtubeInfo["date"] = time();
$youtubeJson = json_encode($youtubeInfo);
$jsonFile = fopen("soccer.json", "w");
fwrite($jsonFile, $youtubeJson);
fclose($jsonFile);
}
foreach ($youtubeInfo["items"] as $link) {
if ($link["id"]["kind"] == "youtube#video") {
$ID = $link["id"]["videoId"];
echo "<iframe width='560' height='315' src='https://www.youtube-nocookie.com/embed/$ID' title='YouTube video player' frameborder='0' allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>";
}
}
?>
</div>
</body>
</html>

20
html/template.php Executable file
View File

@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html>
<head>
<title>
Schaefer Family
</title>
<?php
include 'include/all.php';
?>
</head>
<body>
<?php
include 'include/menu.php';
echo "<div class='main'>";
?>
</div>
</body>
</html>

167
html/usermenu.php Executable file
View File

@@ -0,0 +1,167 @@
<!DOCTYPE html>
<html>
<head>
<title>
Schaefer Family - User Page
</title>
<?php
include 'include/all.php';
// Checks for a signup and creates that user if neccessary
if ($_POST["signup"]) {
$RESULT = dbRequest("username", "users", "username", $_POST["username"], 0);
if ($RESULT == False) {
$PASSWORD = password_hash($_POST["password"], PASSWORD_BCRYPT);
dbAdd([$_POST["username"], $PASSWORD], "users");
}
}
// Will check if a username and password was sent to the server and checks if that pair exists in the database
if ($_POST["username"] != NULL and $_POST["password"] != NULL and $USERNAME == NULL) {
$RESULT = dbRequest("password", "users", "username", $_POST["username"], 0);
if (password_verify($_POST["password"], $RESULT[0])) {
// If the username and password are valid a cookie entry is put into the database and the cookie is put on the user
$USERNAME = $_POST["username"];
$Time = time() + 3600;
$Cookie = $USERNAME;
$Cookie .= $Time;
$Cookie = sanitize(substr(password_hash($_POST["password"], PASSWORD_BCRYPT),15));
$Test = [$Cookie, $USERNAME, $Time];
dbAdd($Test, "cookies");
setcookie("user", $Cookie, time() + 600, "/");
header("Refresh:0; url=/usermenu.php");
}
}
if ($USERNAME == NULL) {
header("Refresh:3; url=/login.php");
}
?>
</head>
<body>
<?php
include 'include/menu.php';
echo "<div class='main'>";
if ($USERNAME == NULL) { // Checks that the user is logged in or if the new user or login information is valid
if ($_POST["username"] == NULL) {
echo "<h2>You are not logged in redirecting...</h2>";
} else {
if ($_POST["signup"] != True) {
echo "<h2>Wrong password or username redirecting...</h2>";
} else {
echo "<h2>This username is already taken...</h2>";
}
}
} else {
echo "<h1>Edit User(s) Here</h1>";
if ($_POST["create"]) {
$USERNAME2 = $_POST["username"];
$RESULT = dbRequest("username", "users", "username", $USERNAME2, 0);
if ($RESULT == False) {
$PASSWORD2 = $_POST["password"];
$PASSWORD = password_hash($_POST["password"], PASSWORD_BCRYPT);
dbAdd([$USERNAME2, $PASSWORD], "users");
echo "You have created a new user with username $USERNAME2 and password <span title='$PASSWORD2'>(hold cursor over this text to see)</span><br><br>";
} else {
echo "Username; $USERNAME2 is already being used<br><br>";
}
}
if ($_POST["delete"]) {
if (!$PRIVILEGE["deleteUser"]) {
$_POST['user'] = $USERNAME;
}
if (!root($_POST["user"])) {
$user = $_POST['user'];
echo "User $user has been deleted<br>";
dbRemove("privileges", "username", $user, 0);
dbRemove("users", "username", $user, 0);
dbRemove("cookies", "username", $user, 0);
} else {
echo "User $user has root privileges<br>";
}
} elseif ($_POST["saveEdit"] == True and (!root($_POST["OGUsername"]) or $PRIVILEGE["root"])) {
$oldUsername = $_POST['OGUsername'];
if (!$PRIVILEGE["editUser"]) {
$oldUsername = $USERNAME;
}
echo "Saved edits on user $oldUsername<br>";
if ($_POST["password"]) {
dbEdit("users", ["password", password_hash($_POST["password"], PASSWORD_BCRYPT)], ["username", $oldUsername], 0);
$newPass = $_POST["password"];
echo "new password of <span title='$newPass'>(hold cursor over this text to see)</span><br>";
}
dbRemove("privileges", "username", $oldUsername, 0);
foreach ($PRIVILEGE as $type=>$ignore) {
if ($_POST[$type]) {
dbAdd([$oldUsername, $type], "privileges");
echo "User has privilege: $type<br>";
}
}
if ($_POST["username"] and !dbRequest("username", "users", "username", $_POST["username"], 0)) {
dbEdit("users", [["username", $_POST["username"]]], ["username", $oldUsername], 0);
dbEdit("privileges", [["username", $_POST["username"]]], ["username", $oldUsername], 0);
$newName = $_POST['username'];
echo "new username of $newName";
}
echo "<br>";
}
echo '<form method="post" action="/usermenu.php" autocomplete="off">';
if ($_POST["edit"] != True) {
if ($PRIVILEGE["editUser"] or $PRIVILEGE["deleteUser"]) {
echo '<label for="user">Choose a user:</label>
<select name="user">';
$LIST = dbRequest("username", "users", NULL, NULL, 2);
foreach ($LIST as $USER) {
var_dump($PRIVILEGE);
if (!root($USER) or $PRIVILEGE["root"]) {
echo "<option value='$USER'><a>$USER</a></option>";
}
}
echo '</select><br>';
}
if ($PRIVILEGE["editUser"]) {
echo '<button name="edit" value="True" type="submit<br>">Edit the User</button><br>';
} else {
echo '<button name="edit" value="True" type="submit<br>">Edit your user</button><br>';
}
if ($PRIVILEGE["deleteUser"]) {
echo '<button name="delete" value="True" type="submit<br>">Delete the User</button><br>';
} else {
echo '<button name="delete" value="True" type="submit<br>">Delete your user</button><br>';
}
$text = ["create", "Create new user", "password"];
} else {
if ($PRIVILEGE["editUser"]) {
$user = $_POST['user'];
} else {
$user = $USERNAME;
}
$existing = dbRequest("privilege", "privileges", "username", $user, 0);
if ($existing == False) {
$existing = [];
}
echo "<h3>Privileges for $user </h3>";
echo "<input type='hidden' name='OGUsername' value='$user'>";
foreach ($PRIVILEGE as $type=>$ignore) {
if ($PRIVILEGE[$type]) {
if (array_search($type, $existing) !== false) {
echo "<input type='checkbox' name='$type' checked='yes' value='True'>$type<br>";
} else {
echo "<input type='checkbox' name='$type' value='True'>$type<br>";
}
}
}
$text = ["saveEdit", "Save", "text"];
}
echo "<br><label for='username'>Username:</label><br>
<input type='text' id='username' name='username'/><br>
<label for='password'>Password:</label><br>
<input type='$text[2]' id='password' name='password'/><br>
<button name='$text[0]' value='True' type='submit'>$text[1]</button><br>
</form>";
}
?>
</div>
</body>
</html>

Binary file not shown.

Binary file not shown.

71
python/database.py Executable file
View File

@@ -0,0 +1,71 @@
import mysql.connector as mysql
import os
db = mysql.connect(host="localhost", passwd="q1azcp2!las",
user="website", database="website")
cursor = db.cursor()
def deleteTable(name): # WIll delete a table in the database
command = "DROP TABLE " + name + ";"
mycursor.execute(command)
db.commit()
def createTable(name, coulumns): # Will create a table in the database
command = "CREATE TABLE " + name + " ("
for x in coulumns:
command += x[0]
if x[1] == 0:
command += " varchar(255), "
else:
command += " int, "
command = command[:len(command) - 2]
command += ");"
cursor.execute(command)
db.commit()
def appendValue(table, value, coulumns=""): # Will add a value to a table
command = "INSERT INTO " + table + " " + coulumns + " VALUES ("
for x in value:
command += "'" + x + "', "
command = command[:len(command) - 2]
command += ");"
cursor.execute(command)
db.commit()
# Will backup(restore does nothing right now) a database
def backUp(dbLocation, location, restore):
f = open("/var/www/html/maintenance-mode", "w")
f.close()
os.system("sudo service mariadb stop")
command = "cp -pr "
if restore:
command += location
command += " "
command += dbLocation
else:
command += dbLocation
command += " "
command += location
command += " -r"
print("Check")
os.remove("/var/www/html/maintenance-mode")
os.system(command)
os.system("sudo service mariadb start")
def search(table, where, value="*"):
cursor.execute("SELECT " + value +
" FROM " + table + " WHERE " + where + ";")
value = cursor.fetchall()
try:
return value[0]
except:
return value
def delete(table, where):
cursor.execute("DELETE FROM " + table + " WHERE " + where + ";")
db.commit()

164
python/restart.py Executable file
View File

@@ -0,0 +1,164 @@
#!/usr/bin/env python3
import os
import datetime
import time
import json
import RPi.GPIO as GPIO
import router # Custom library that has router controls
f = open("/var/www/html/maintenance-mode", "w")
f.close()
# Makes sure that the permissions are not wrong
os.system("chown -R www-data:www-data /var/www/html")
os.system("chmod 750 /var/www/html -R")
os.system("chown -R mysql:mysql /var/lib/mysql")
os.system("chmod 750 /var/lib/mysql -R")
while True: # Imports this library in a slow way because it is a pain and likes to not work
try:
import database
break
except:
continue
location = "/var/www/html/"
internetOnDeafult = ["23", "0", "5", "0", "2147483000", "1"]
internet = False
def writeLog(message, kind): # Will automatically add to the log
database.appendValue("log", [str(kind), message, str(time.time())])
print(message, time.time())
# Checks if an action is neccessary to do on the wifi
def internetAction(times, rule, status):
timeStart = int(rule[0]) * 60 + int(rule[1])
timeEnd = int(rule[2]) * 60 + int(rule[3])
times = int(times[3]) * 60 + int(times[4])
if timeEnd < timeStart:
if timeEnd > times:
times += 60 * 24
timeEnd += 60 * 24
if times >= timeStart and times <= timeEnd:
if status:
GPIO.output(8, GPIO.HIGH)
writeLog("Internet turning off", 6)
status = router.turnOffInternet()
writeLog("Internet turning off", 6)
GPIO.output(8, GPIO.LOW)
else:
if not status:
GPIO.output(8, GPIO.HIGH)
writeLog("Internet turning on", 7)
status = router.turnOnInternet()
writeLog("Internet turning on", 7)
GPIO.output(8, GPIO.LOW)
return status
def writeFile(location, info): # Will write info in json format to a file
with open(location, 'w') as f:
json.dump(info, f)
os.system("chown -R www-data:www-data " + location)
def readFile(location): # Loads the location of a certain file and returns that file if it is json
with open(location) as f:
return json.load(f)
def callTime(): # Will return the time
time = datetime.datetime.now()
time2 = [time.strftime("%b"), time.strftime("%d"), time.strftime(
"%Y"), time.strftime("%H"), time.strftime("%M"), time.strftime("%S"), time.strftime("%-m")]
return time2
def buttonPress(): # Will run this script everytime the button is pressed
minimum = database.search("internet", "id=(SELECT MIN(id) FROM internet)")
minimum = int(minimum[5]) - 1
writeLog("Internet Schedule changed due to button", 5)
if minimum == 0:
minimum = -1
database.appendValue(
"internet", ["0", "0", "23", "59", str(time.time()+3600), str(minimum)])
# Will make sure that the internal clock is right for 2 minutes
times = time.time()
change = 0
startTime = times
while change < 1:
totalTime = time.time() - startTime
if totalTime > 120:
writeLog("Time may be wrong; time check failed", 9)
break
time.sleep(0.5)
change = time.time() - times
times = time.time()
break
# Will start the internet schedule file
try:
internetOn = readFile(location + "internet.json")
internetFormula(internetOn, internetOnDeafult)
writeFile(location + "internet.json", internetOnDeafult)
except:
writeFile(location + "internet.json", internetOnDeafult)
# Will try to open the json location and will create a new file if the old one is gone and will store the date in it.
try:
info = readFile(location + "data.json")
info.append(info[-1])
info.append(callTime())
info.append(callTime())
info.append(callTime())
except:
info = [callTime(), callTime()]
writeFile(location + "data.json", info)
# Will setup the gpio button
GPIO.setmode(GPIO.BOARD)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(8, GPIO.OUT)
lastBackup = callTime()[1] # Makes sure that a backup does not happen on boot
# Will update the time every minute to make sure electricity outages are reported to the minute precise and will request a check to see if the wifi status needs to be changed
os.remove("/var/www/html/maintenance-mode")
while True:
info = readFile(location + "data.json")
info[-1] = callTime()
writeFile(location + "data.json", info)
if lastBackup != callTime()[1]:
try:
database.backUp("/var/lib/mysql", "/backup/main", False)
database.backUp("/var/lib/mysql", "/backup/reserve", False)
except:
writeLog("Database backup failed", 9)
lastBackup = callTime()[1]
minimum = database.search("internet", "id=(SELECT MIN(id) FROM internet)")
if not minimum:
database.appendValue("internet", internetOnDeafult)
minimum = internetOnDeafult
writeLog("No internet schedule found creating a new one", 8)
while(minimum[4] < time.time()):
oldMinimum = minimum
database.delete("internet", f"id={minimum[5]}")
minimum = database.search(
"internet", "id=(SELECT MIN(id) FROM internet)")
if not minimum:
database.appendValue("internet", internetOnDeafult)
minimum = internetOnDeafult
writeLog(
f"Changing internet schedule from; {oldMinimum[0]}:{oldMinimum[1]} to {oldMinimum[2]}:{oldMinimum[3]}, to {minimum[0]}:{minimum[1]} to {minimum[2]}:{minimum[3]}", 8)
internetOn = internetAction(callTime(), internetOn, minimum[0:4])
# Will check every 2 seconds if the button is pressed and when it is show it on the led and then wait another second to verify that it is an actual press
while True:
time.sleep(2)
if GPIO.input(10):
GPIO.output(8, GPIO.HIGH)
time.sleep(.2)
GPIO.output(8, GPIO.LOW)
time.sleep(.1)
if GPIO.input(10):
GPIO.output(8, GPIO.HIGH)
buttonPress()
break
if time.time() % 60 <= 2:
break

111
python/router.py Executable file
View File

@@ -0,0 +1,111 @@
import RPi.GPIO as GPIO
import requests
from urllib.request import urlopen
def loginInternet(): # Makes sure that the server is logged in
urlLogin = "http://192.168.1.254/cgi-bin/login.ha"
login = {
"nonce": "76d8f8d800112e9573bacb9c56f0ecf82c9f2ed23fa10a83",
"password": "@<*08<**89",
"Continue": "Continue"
}
loginCode = lol(urlLogin).read().decode("utf-8")
start = loginCode.find('<input type="hidden" name="nonce" value=')
end = loginCode.find('/>', start)
loginCode = loginCode[start+41:end-2]
login["nonce"] = loginCode
login2 = requests.post(urlLogin, data=login)
return loginCode
def turnOnInternet(): # Turns on the internet
return True
code = loginInternet()
postObjectOff = {
"nonce": code,
"owl80211on": "on",
"ostandard": "bgn",
"obandwidth": "20",
"ochannelplusauto": "0",
"opower": "100",
"oussidenable": "off",
"ossidname": "ATT7MTctna",
"ohide": "off",
"osecurity": "defwpa",
"owpaversion": "2",
"owps": "on",
"omaxclients": "80",
"ogssidenable": "off",
"ossidname2": "ATT7MTctna_Guest",
"ohide2": "off",
"osecurity2": "wpa",
"owpaversion2": "2",
"omaxclients2": "10",
"owpspin": "",
"twl80211on": "on",
"tstandard": "ac",
"tbandwidth": "80",
"tchannelplusauto": "0",
"tpower": "100",
"tussidenable": "on",
"tssidname": "ATT7MTctna",
"thide": "off",
"tsecurity": "defwpa",
"twps": "on",
"tmaxclients": "80",
"twpspin": "",
"Restore": "Restore Defaults"
}
urlSet = "http://192.168.1.254/cgi-bin/wconfig-adv.ha"
turnOn = requests.post(urlSet, data=postObjectOff)
return True
def turnOffInternet(): # Turns of the internet
return False
code = loginInternet()
postObjectOn = {
"nonce": code,
"owl80211on": "off",
"ostandard": "bgn",
"obandwidth": "20",
"ochannelplusauto": "0",
"opower": "100",
"oussidenable": "off",
"ossidname": "ATT7MTctna",
"ohide": "off",
"osecurity": "defwpa",
"owpaversion": "2",
"owps": "on",
"omaxclients": "80",
"ogssidenable": "off",
"ossidname2": "ATT7MTctna_Guest",
"ohide2": "off",
"osecurity2": "wpa",
"owpaversion2": "2",
"omaxclients2": "10",
"owpspin": "",
"twl80211on": "off",
"tstandard": "ac",
"tbandwidth": "80",
"tchannelplusauto": "0",
"tpower": "100",
"tussidenable": "on",
"tssidname": "ATT7MTctna",
"thide": "off",
"tsecurity": "defwpa",
"twps": "on",
"tmaxclients": "80",
"twpspin": ""
}
warn = {
"nonce": code,
"ReturnWarned": "Continue"
}
urlSet = "http://192.168.1.254/cgi-bin/wconfig-adv.ha"
urlWarn = "http://192.168.1.254/cgi-bin/wifiwarn-adv.ha"
turnOff1 = requests.post(urlSet, data=postObjectOn)
turnOff2 = urlopen(urlWarn).read().decode("utf-8")
turnOff3 = requests.post(urlSet, data=warn)
return False