99 Commits
v2.0.0 ... main

Author SHA1 Message Date
ddb49d44de fixing some bugs in uploader 2025-03-30 10:34:53 +01:00
2fb6ab6254 fixing visual bug 2025-03-20 16:58:22 +00:00
a30dabd57e . 2025-03-20 16:56:00 +00:00
675a08d4bb . 2025-03-20 16:54:39 +00:00
e4997c7dab . 2025-03-17 16:28:53 +00:00
b222b4e86c . 2025-03-17 16:26:40 +00:00
a73ae5dbca . 2025-03-17 16:25:16 +00:00
7850703d55 . 2025-03-17 16:22:53 +00:00
e627b56040 . 2025-03-17 16:21:37 +00:00
60b07447ad . 2025-03-17 16:19:44 +00:00
97486a90b1 . 2025-03-17 16:17:32 +00:00
78c0f76f3e . 2025-03-03 16:32:44 +00:00
8064803d31 . 2025-03-03 16:28:03 +00:00
fdff2aaab5 changin höögli to green 2025-03-03 16:25:01 +00:00
7cedb33783 fixing layout bug 2025-03-03 16:22:51 +00:00
d117017f21 updating uploader 2025-03-03 16:19:57 +00:00
42c4fb70ae replacing old uploader 2025-03-03 16:18:55 +00:00
ba991815ec fixing bugs 2025-02-28 20:05:03 +00:00
Janis Steiner
ff03bb4b2b fixing small bug 2025-02-28 17:55:38 +00:00
Janis Steiner
c236b4a495 testing new uploader 2025-02-28 17:00:53 +00:00
Janis Steiner
7627f33503 Add files via upload 2025-01-04 10:12:42 +01:00
Janis Steiner
e4804664b8 . 2025-01-02 07:53:57 +00:00
Janis Steiner
cfe816d2bb . 2024-12-31 12:14:46 +00:00
Janis Steiner
18b136ed6e . 2024-12-28 18:26:33 +00:00
Janis Steiner
a12f25fbd2 . 2024-12-28 18:25:22 +00:00
Janis Steiner
38e1131035 changin to auth.jakach.ch 2024-12-28 17:41:39 +00:00
root
659c266030 . 2024-12-28 16:22:02 +00:00
root
034ee04e89 setting new jakach auth url 2024-12-28 16:12:35 +00:00
root
524ce4cdf5 . 2024-12-28 09:26:18 +00:00
root
9f21ffc65e Merge branch 'main' of https://github.com/jakani24/system0-test 2024-12-28 09:24:21 +00:00
root
42af1ab302 adding manual 2024-12-28 09:23:47 +00:00
Janis Steiner
4cb9cccc68 Add files via upload 2024-12-28 10:23:12 +01:00
root
71d0bc8856 testing on port 80 2024-12-27 09:52:09 +00:00
root
eca8241cae adding jakach oauth 2024-12-26 18:32:32 +00:00
root
bea68313b3 changing webcams components 2024-12-22 10:28:07 +00:00
root
623cbf5ad4 . 2024-12-22 10:04:06 +00:00
root
abf8ba3af6 fixing bug in freeing printer used by external user 2024-12-22 10:02:49 +00:00
root
3e55c6262a fixing small bug 2024-12-22 10:00:15 +00:00
root
ebbadd78df fixing small bug 2024-12-22 09:58:10 +00:00
root
107dd60cd8 fixing small bug 2024-12-22 09:56:29 +00:00
root
f05d3cfe52 fixing some display 2024-12-22 09:48:20 +00:00
root
849a13f02c fixing a small bug 2024-12-22 09:41:09 +00:00
root
ea0c7f08c1 fixing bugs in reservation system, fixing error messages, checking if print has been started from other location 2024-12-22 09:36:46 +00:00
root
569f72114e fixing broken link 2024-12-21 10:41:21 +00:00
root
bc09f1a0c4 adding some error and success messages 2024-12-21 10:38:02 +00:00
Janis Steiner
8c614b14b5 Update components.php 2024-12-16 20:27:49 +00:00
root
17e656d607 removing some messages 2024-12-15 18:02:32 +00:00
root
5808ffceb1 updating queue system 2024-12-15 17:37:27 +00:00
root
8b94f7f9fe adding error message 2024-12-15 17:33:16 +00:00
root
e5bfbdb5f1 . 2024-12-15 17:30:25 +00:00
root
b838bfd6e2 adding asynv queue check 2024-12-15 17:29:05 +00:00
Janis Steiner
ac8dd3e514 moving more pages to dark mode 2024-12-10 16:21:28 +00:00
Janis Steiner
e9f2c9b310 switching webcam to darkmode 2024-12-09 16:30:50 +00:00
Janis Steiner
049c74ef9b switching webcam to darkmode 2024-12-09 16:29:47 +00:00
Janis Steiner
b06c14dcb8 updating all files to use darkmode 2024-12-09 16:27:04 +00:00
Janis Steiner
dc4d9636c0 bumping bootstrap verison to 5.3.3 2024-12-09 16:14:20 +00:00
Janis Steiner
4f8b9c3ec2 removing old files 2024-12-09 16:06:47 +00:00
Janis Steiner
597ac8cbe0 switching to new verison of overview 2024-12-09 16:05:56 +00:00
Janis Steiner
1d473acb01 adding print percentage to overview 2024-12-09 16:00:39 +00:00
Janis Steiner
f57b690536 adding print percentage to overview 2024-12-09 15:50:01 +00:00
Janis Steiner
2fc7f4f014 adding print percentage to overview 2024-12-09 15:47:26 +00:00
Janis Steiner
9e44d8d95b moving some api files to /api/ 2024-12-09 15:43:08 +00:00
Janis Steiner
72e9f0af38 . 2024-12-08 13:27:29 +00:00
Janis Steiner
e9a27c1928 . 2024-12-08 13:24:46 +00:00
Janis Steiner
680f95a1c5 . 2024-12-08 13:23:20 +00:00
Janis Steiner
6ba266b2e9 . 2024-12-08 13:21:16 +00:00
Janis Steiner
1055d4fcdf . 2024-12-08 13:18:05 +00:00
Janis Steiner
da6cad4984 . 2024-12-08 13:15:35 +00:00
Janis Steiner
21e14e7fcf . 2024-12-08 13:14:35 +00:00
Janis Steiner
fa08d31a90 . 2024-12-08 13:13:42 +00:00
Janis Steiner
5658f45f96 . 2024-12-08 13:10:35 +00:00
Janis Steiner
4880e1dee0 . 2024-12-08 13:08:05 +00:00
Janis Steiner
7295152038 fixing bug 2024-12-08 12:59:48 +00:00
Janis Steiner
4d445228bd fixing bug 2024-12-08 12:57:09 +00:00
Janis Steiner
ba8101036f adding file desc 2024-12-08 12:53:06 +00:00
Janis Steiner
38c7183c8e adding file desc 2024-12-08 12:49:42 +00:00
Janis Steiner
d2a356715f adding file desc 2024-12-08 12:49:02 +00:00
Janis Steiner
6dd73bb8ab adding file desc 2024-12-08 12:46:13 +00:00
Janis Steiner
00169ac80b fixing bugs in new overview 2024-12-08 12:35:28 +00:00
Janis Steiner
2e4b842b00 fixing bugs in new overview 2024-12-08 12:32:01 +00:00
Janis Steiner
d365995ba6 fixing bugs in new overview 2024-12-08 12:30:36 +00:00
Janis Steiner
82ee0186bc working on new overview page 2024-12-08 12:11:30 +00:00
Janis Steiner
276b9299d4 . 2024-12-08 10:51:00 +00:00
Janis Steiner
944479e6f4 adidng tests 2024-12-08 10:50:08 +00:00
Janis Steiner
46da591874 fixing bug 2024-12-08 10:07:56 +00:00
Janis Steiner
9836ea77e4 adding maintenance info 2024-12-08 10:07:14 +00:00
Janis Steiner
c31324c794 fixing error 2024-11-28 14:55:26 +00:00
Janis Steiner
cc280021ed small ui fixes 2024-11-28 14:42:45 +00:00
Janis Steiner
d9a8c83ad9 adding tests 2024-11-28 14:23:45 +00:00
Janis Steiner
87b6dc7e83 testing 2024-11-28 14:22:55 +00:00
Janis Steiner
69403d7741 new user management system using ajax 2024-11-28 07:47:09 +00:00
Janis Steiner
60d68dae88 Add files via upload 2024-11-20 19:56:05 +01:00
Janis Steiner
1ba076a766 adding infra for sys0 presentation in st.gallen 2024-11-18 16:01:44 +00:00
Janis Steiner
84d1a428c7 adding status page 2024-11-13 20:26:21 +00:00
Janis Steiner
687aec96ea Update docker-compose.yml 2024-11-11 15:54:40 +00:00
Janis Steiner
10640917a0 fixing bug where lookahead would not work for cloudprint 2024-10-28 15:07:26 +00:00
Janis Steiner
5bc68a502c adding reservations lookahead 2024-10-28 14:41:59 +00:00
Janis Steiner
37e0991970 adding reservations lookahead 2024-10-28 14:39:50 +00:00
Janis Steiner
a245cfda14 adding image display on first load 2024-10-28 13:53:13 +00:00
45 changed files with 2353 additions and 1349 deletions

BIN
System0 Anleitung.pdf Normal file

Binary file not shown.

View File

@@ -11,6 +11,16 @@
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
# Rewrite-Engine aktivieren
#RewriteEngine On
# IP-Adresse des Entwicklers zulassen
#RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000$
# Alles auf die Wartungsseite umleiten
#RewriteCond %{REQUEST_URI} !/app/maintenance.html$
#RewriteRule ^ /app/maintenance.html [R=307,L]
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular

BIN
connect_jac.pdf Normal file

Binary file not shown.

View File

@@ -11,6 +11,7 @@ services:
ipv4_address: 192.168.178.2
volumes:
- sys0-db:/var/lib/mysql
restart: always
sys0-srv:
build:
@@ -28,6 +29,7 @@ services:
- ./sys0-code:/var/www/html
- ./apache-conf:/etc/apache2/sites-enabled/
- ./php-conf:/usr/local/etc/php/
restart: always
networks:
sys0-network:
driver: bridge

View File

@@ -1,4 +1,6 @@
FROM php:apache
RUN docker-php-ext-install mysqli
RUN a2enmod rewrite
#RUN a2enmod ssl
RUN service apache2 restart

View File

@@ -0,0 +1,5 @@
<?php
require_once "../config/config.php";
include "queue.php";
test_queue($link);
?>

View File

@@ -0,0 +1,44 @@
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"][3] !== "1") {
header("location: /login/login.php");
exit;
}
require_once "../config/config.php";
function deleteDirectory($dir) {
if (!is_dir($dir)) {
return false; // Gibt false zurück, wenn das Verzeichnis nicht existiert
}
$files = array_diff(scandir($dir), array('.', '..')); // Ignoriert "." und ".."
foreach ($files as $file) {
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
deleteDirectory($path); // Rekursiver Aufruf für Unterordner
} else {
unlink($path); // Datei löschen
}
}
return rmdir($dir); // Verzeichnis löschen
}
$userId = $_POST['userId'];
$sql = "SELECT username FROM users WHERE id = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($username);
$stmt->fetch();
$stmt->close();
$sql = "DELETE FROM users WHERE id = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->close();
deleteDirectory("/var/www/html/user_files/$username/");
?>

View File

@@ -0,0 +1,124 @@
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: /login/login.php");
exit;
}
include "../config/config.php";
header('Content-Type: application/json');
function seconds_to_time($seconds) {
$hours = floor($seconds / 3600);
$minutes = floor(($seconds % 3600) / 60);
if($hours != 0) {
if($hours == 1)
return sprintf("%d Stunde %d Minuten", $hours, $minutes);
else
return sprintf("%d Stunden %d Minuten", $hours, $minutes);
} else {
return sprintf("%d Minuten", $minutes);
}
}
function short_path($filePath, $firstCharsCount, $lastCharsCount) {
$filePath = str_replace(".gcode", "", $filePath);
if(strlen($filePath) >= $firstCharsCount + $lastCharsCount + 3) {
$firstChars = substr($filePath, 0, $firstCharsCount);
$lastChars = substr($filePath, -$lastCharsCount);
return $firstChars . "..." . $lastChars;
} else {
return $filePath;
}
}
$printers = [];
$sql = "SELECT rotation, free, printer.id, printer_url, apikey, cancel, used_by_userid, system_status, printer.color, COALESCE(name, 'nicht verfügbar') AS real_color, COALESCE(username,'nicht verfügbar') FROM printer LEFT JOIN filament ON printer.color=internal_id LEFT JOIN users ON used_by_userid=users.id ORDER BY printer.id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $rotation, $is_free, $printer_id, $url, $apikey, $cancel, $userid, $system_status, $filament_color,$real_color,$used_by_user);
while (mysqli_stmt_fetch($stmt)) {
$used_by_user=explode("@",$used_by_user)[0];
$printer = [
"rotation" => $rotation,
"is_free" => $is_free,
"printer_id" => $printer_id,
"url" => $url,
"cancel" => $cancel,
"userid" => $userid,
"system_status" => $system_status,
"filament_color" => $real_color,
"username" => $used_by_user
];
if ($is_free == 0 && $system_status == 0 && $cancel==0) {
exec("curl --max-time 10 $url/api/job?apikey=$apikey > /var/www/html/user_files/" . $_SESSION["username"] . "/json.json");
$fg = file_get_contents("/var/www/html/user_files/" . $_SESSION["username"] . "/json.json");
$json = json_decode($fg, true);
$printer["progress"] = (int) $json['progress']['completion'];
$printer["file"] = short_path($json["job"]["file"]["name"], 10, 10);
$printer["full_file"]=$json["job"]["file"]["name"];
$printer["print_time_total"] = seconds_to_time(intval($json["job"]["estimatedPrintTime"]));
$printer["print_time_left"] = seconds_to_time(intval($json["progress"]["printTimeLeft"]));
$printer["print_time"] = seconds_to_time(intval($json["progress"]["printTime"]));
if($printer["progress"]==100){
$printer["print_status"]="Fertig";
$printer["view"]=0;
}else{
$printer["print_status"]="Drucken";
$printer["view"]=1;
}
$printer["progress"]=ceil(100*intval($json["progress"]["printTime"])/(intval($json["progress"]["printTime"])+intval($json["progress"]["printTimeLeft"])+1));
}else if($cancel==1 && ($system_status==0 or $system_status==99)){
exec("curl --max-time 10 $url/api/job?apikey=$apikey > /var/www/html/user_files/" . $_SESSION["username"] . "/json.json");
$fg = file_get_contents("/var/www/html/user_files/" . $_SESSION["username"] . "/json.json");
$json = json_decode($fg, true);
//$printer["progress"] = (int) $json['progress']['completion'];
$printer["progress"]=ceil(100*intval($json["progress"]["printTime"])/(intval($json["progress"]["printTime"])+intval($json["progress"]["printTimeLeft"])+1));
$printer["file"] = short_path($json["job"]["file"]["name"], 10, 10);
$printer["print_time_total"] = seconds_to_time(intval($json["job"]["estimatedPrintTime"]));
$printer["print_time_left"] = seconds_to_time(intval($json["progress"]["printTimeLeft"]));
$printer["print_time"] = seconds_to_time(intval($json["progress"]["printTime"]));
$printer["print_status"]="Abgebrochen";
$printer["full_file"]=$json["job"]["file"]["name"];
$printer["view"]=2;
}/*else if($system_status==0){
$printer["print_status"]="Bereit";
$printer["view"]=3;
}*/else if(($is_free == 1 && $system_status==0) or $system_status==99){ //check if a print has been started from another location
exec("curl --max-time 10 $url/api/job?apikey=$apikey > /var/www/html/user_files/" . $_SESSION["username"] . "/json.json");
$fg = file_get_contents("/var/www/html/user_files/" . $_SESSION["username"] . "/json.json");
$json = json_decode($fg, true);
if($json['state']=="Starting print from SD" or $json['state']=="Printing" or $json['state']=="Printing from SD" or $system_status==99){
$printer["print_status"]="Von anderer Quelle aus gestartet.";
//$printer["progress"] = (int) $json['progress']['completion'];
$printer["progress"]=ceil(100*intval($json["progress"]["printTime"])/(intval($json["progress"]["printTime"])+intval($json["progress"]["printTimeLeft"])+1));
$printer["file"] = short_path($json["job"]["file"]["name"], 10, 10);
$printer["full_file"]=$json["job"]["file"]["name"];
$printer["print_time_total"] = seconds_to_time(intval($json["job"]["estimatedPrintTime"]));
$printer["print_time_left"] = seconds_to_time(intval($json["progress"]["printTimeLeft"]));
$printer["print_time"] = seconds_to_time(intval($json["progress"]["printTime"]));
$printer["view"]=5;
//insert into db that this one is printing
$sql="UPDATE printer SET system_status=99 WHERE id = $printer_id";
$stmt2 = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}else{
$printer["print_status"]="Bereit";
$printer["view"]=3;
}
}else{
$printer["print_status"]="Problem / Nicht betriebsbereit";
$printer["view"]=4;
}
$printers[] = $printer;
}
mysqli_stmt_close($stmt);
echo json_encode($printers);
?>

View File

@@ -0,0 +1,54 @@
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"][3] !== "1") {
header("location: /login/login.php");
exit;
}
require_once "../config/config.php";
$username = isset($_GET['username']) ? '%' . htmlspecialchars($_GET['username']) . '%' : '%';
$sql = "SELECT users.id, users.username, users.role, users.class_id, users.banned, class.name
FROM users
LEFT JOIN class ON users.class_id = class.id
WHERE users.username LIKE ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>{$row['username']}</td>";
echo "<td>
<select class='form-select updateField' data-field='class_id' data-userid='{$row['id']}'>";
$classQuery = $link->query("SELECT id, name FROM class");
while ($class = $classQuery->fetch_assoc()) {
$selected = $class['id'] == $row['class_id'] ? 'selected' : '';
echo "<option value='{$class['id']}' $selected>{$class['name']}</option>";
}
if($row["class_id"]==0){
echo "<option value='0' selected>Lehrperson</option>";
}else{
echo "<option value='0'>Lehrperson</option>";
}
echo "</select>
</td>";
$role=substr($row['role'],0,11);
foreach (str_split($role) as $index => $perm) {
$checked = $perm === "1" ? "checked" : "";
echo "<td>
<input type='checkbox' class='form-check-input updateField' data-field='role[$index]' data-userid='{$row['id']}' $checked>
</td>";
}
if($row['banned']==1)
echo "<td><button class='btn btn-success verify_user' data-userid='{$row['id']}'>Manuell verifizieren</button></td>";
else
echo "<td>Bereits verifiziert</td>";
echo "<td><button class='btn btn-danger deleteUser' data-userid='{$row['id']}'>Löschen</button></td>";
echo "</tr>";
}
$stmt->close();
?>

View File

@@ -1,67 +1,64 @@
<?php
function test_queue($link)//function to check if any printer is free and if there are jobs in queue. If yes push jo to printer
{
$sql="select id, from_userid,filepath,print_on from queue order by id";
$qid=0;
$quserid=0;
$qfilepath="";
$print_on=0;
function test_queue($link) // Function to check if any printer is free and process all jobs in the queue
{
$sql = "SELECT id, from_userid, filepath, print_on FROM queue ORDER BY id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $qid,$quserid,$qfilepath,$print_on);
mysqli_stmt_fetch($stmt);
$num_of_printers=0;
if($print_on==-1)
$sql="select count(*) from printer";
else
$sql="select count(*) from printer where id=$print_on";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $num_of_printers);
mysqli_stmt_fetch($stmt);
$last_id=0;
$printers_av=0;
if($num_of_printers!=0)
{
$id=0;
$papikey="";
$userid=$_SESSION["id"];
$username=$_SESSION["username"];
$purl="";
if($print_on==-1)
$sql="Select id,apikey,printer_url from printer where id>$last_id and free=1 order by id";
else
$sql="Select id,apikey,printer_url from printer where id=$print_on and free=1";
//echo $sql;
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $id,$papikey,$purl);
mysqli_stmt_fetch($stmt);
if($id!=0)
{
exec('curl -k -H "X-Api-Key: '.$papikey.'" -F "select=true" -F "print=true" -F "file=@'.$qfilepath.'" "'.$purl.'/api/files/local" > /var/www/html/user_files/'.$username.'/json.json');
$fg=file_get_contents("/var/www/html/user_files/$username/json.json");
$json=json_decode($fg,true);
if($json['effectivePrint']==true and $json["effectiveSelect"]==true)
{
$sql="update printer set free=0, printing=1,mail_sent=0, used_by_userid=$quserid where id=$id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $qid, $quserid, $qfilepath, $print_on);
$sql="delete from queue where id=$qid";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
}
while (mysqli_stmt_fetch($stmt)) {
$num_of_printers = 0;
if ($print_on == -1)
$sql_printers = "SELECT COUNT(*) FROM printer";
else
{
}
}
}
}
$sql_printers = "SELECT COUNT(*) FROM printer WHERE id = $print_on";
$stmt_printers = mysqli_prepare($link, $sql_printers);
mysqli_stmt_execute($stmt_printers);
mysqli_stmt_store_result($stmt_printers);
mysqli_stmt_bind_result($stmt_printers, $num_of_printers);
mysqli_stmt_fetch($stmt_printers);
if ($num_of_printers > 0) {
$id = 0;
$papikey = "";
$purl = "";
if ($print_on == -1)
$sql_free_printers = "SELECT id, apikey, printer_url FROM printer WHERE free = 1 ORDER BY id";
else
$sql_free_printers = "SELECT id, apikey, printer_url FROM printer WHERE id = $print_on AND free = 1";
$stmt_free_printers = mysqli_prepare($link, $sql_free_printers);
mysqli_stmt_execute($stmt_free_printers);
mysqli_stmt_store_result($stmt_free_printers);
mysqli_stmt_bind_result($stmt_free_printers, $id, $papikey, $purl);
if (mysqli_stmt_fetch($stmt_free_printers)) { // Found a free printer
$username = $_SESSION["username"];
$curl_cmd = 'curl -k -H "X-Api-Key: ' . $papikey . '" -F "select=true" -F "print=true" -F "file=@' . $qfilepath . '" "' . $purl . '/api/files/local" > /var/www/html/user_files/' . $username . '/json.json';
exec($curl_cmd);
$fg = file_get_contents("/var/www/html/user_files/$username/json.json");
$json = json_decode($fg, true);
if ($json['effectivePrint'] == true && $json["effectiveSelect"] == true) {
$sql_update_printer = "UPDATE printer SET free = 0, printing = 1, mail_sent = 0, used_by_userid = $quserid WHERE id = $id";
$stmt_update_printer = mysqli_prepare($link, $sql_update_printer);
mysqli_stmt_execute($stmt_update_printer);
$sql_delete_queue = "DELETE FROM queue WHERE id = $qid";
$stmt_delete_queue = mysqli_prepare($link, $sql_delete_queue);
mysqli_stmt_execute($stmt_delete_queue);
} else {
//echo "Failed sending file to printer for queue ID $qid!<br>";
}
} else {
//echo "No free printer available for queue ID $qid!<br>";
}
} else {
//echo "No printers available for queue ID $qid!<br>";
}
}
}
?>

View File

@@ -69,7 +69,10 @@ function load_user()
mysqli_stmt_fetch($stmt);
if($id!=0 && $id!=$last_id)
{
echo("<option printer='$id' value='$id'>Printer $id</option>");
if($id==$_POST["printer"])
echo("<option printer='$id' value='$id' selected>Drucker $id</option>");
else
echo("<option printer='$id' value='$id'>Drucker $id</option>");
}
$last_id=$id;
$num_of_printers--;

View File

@@ -0,0 +1,34 @@
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"][3] !== "1") {
header("location: /login/login.php");
exit;
}
require_once "../config/config.php";
$userId = $_POST['userId'];
$field = $_POST['field'];
$value = $_POST['value'];
if (strpos($field, 'role') !== false) {
$index = (int)filter_var($field, FILTER_SANITIZE_NUMBER_INT);
$sql = "SELECT role FROM users WHERE id = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($role);
$stmt->fetch();
$stmt->close();
$role[$index] = $value;
$sql = "UPDATE users SET role = ? WHERE id = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("si", $role, $userId);
} else {
$sql = "UPDATE users SET $field = ? WHERE id = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("ii", $value, $userId);
}
$stmt->execute();
$stmt->close();
?>

View File

@@ -0,0 +1,52 @@
<?php
//this file returns a list of available printers, theyr status and theyr color
session_start();
$file_path=$_SESSION["current_file"];
include "../../config/config.php";
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
$class=$_SESSION["class_id"];
include "../../config/config.php";
//check if printers are reserved right now or will be while print is running
$is_unsafe=check_file($file_path);
echo(json_encode(["status"=>$is_unsafe]));
function extract_param($gcode) {
// Match the pattern S followed by digits, capturing the digits
$matches = [];
$pattern = '/[S|T]([0-9]+)/';
if (preg_match($pattern, $gcode, $matches)) {
return (int)$matches[1]; // Return the first capture group as an integer
} else {
return false; // No match found
}
}
function check_file($path){//check file for temperature which are to high
$file = fopen($path, 'r');
$cnt=0;
while (!feof($file)&&$cnt!=2) {
$line = fgets($file);
// Extract parameter from lines with specific commands
if (strpos($line, 'M104') !== false || strpos($line, 'M140') !== false) {
$cnt++;
$parameter = extract_param($line);
if(strpos($line, 'M104') !== false){ //extruder_temp
$ex_temp=$parameter;
}
if(strpos($line, 'M140') !== false){ //bed temp
$bed_temp=$parameter;
}
}
}
//echo("bed:$bed_temp;ex:$ex_temp");
if($bed_temp>75 or $ex_temp>225){
return 1;
}else{
return 0;
}
}
?>

View File

@@ -0,0 +1,150 @@
<?php
date_default_timezone_set('Europe/Zurich');
//this file returns a list of available printers, theyr status and theyr color
session_start();
$file_path=$_SESSION["current_file"];
include "../../config/config.php";
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
$class=$_SESSION["class_id"];
include "../../config/config.php";
//check if printers are reserved right now or will be while print is running
$is_reserved=check_reservation_conflict($link, $class);
if($is_reserved==0){
$is_reserved=check_print_reservation_conflict($link, $class, $file_path);
}
echo(json_encode(["status"=>$is_reserved]));
function find_print_time($file) {
$handle = fopen($file, "r");
$targetPhrase = "; estimated printing time (normal mode) = ";
$time = null;
while (($line = fgets($handle)) !== false) {
if (strpos($line, $targetPhrase) !== false) {
// Extract the time after the target phrase
$time = trim(str_replace($targetPhrase, "", $line));
break; // Stop once the desired line is found
}
}
fclose($handle);
return $time;
}
function check_reservation_conflict($link, $class) {
$reservation_conflict = false;
$today = date("Y-m-d");
$time_now = date("H:i");
$for_class = [];
// Query for reservations that start today or extend into today
$sql = "
SELECT day, time_from, time_to, for_class
FROM reservations
WHERE day <= '$today' AND
(day = '$today' AND time_from <= '$time_now' OR day < '$today');
";
$stmt = $link->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Calculate the actual end time of the reservation
$reservation_end = strtotime($row["day"] . " " . $row["time_to"]);
$current_time = strtotime("$today $time_now");
if ($current_time <= $reservation_end) {
$reservation_conflict = true;
$for_class[] = $row["for_class"];
}
}
// Default value for for_class if no conflicts are found
if (empty($for_class)) {
$for_class[] = 0;
}
// Determine the appropriate response based on the conflict status
$response = 0;
if ($reservation_conflict && !in_array($class, $for_class) && $class != 0) {
$response=1;
} elseif ($class == 0 && $reservation_conflict) {
$response=2;
}
return $response;
}
function check_print_reservation_conflict($link, $class, $path) {
$reservation_conflict = false;
$for_class = [];
$today = date("Y-m-d");
$time_now = date("H:i");
// Calculate the end time of the print
$print_time = find_print_time($path); // Assume this function is already defined
preg_match('/(\d+)h/', $print_time, $hours_match);
preg_match('/(\d+)m/', $print_time, $minutes_match);
$hours = isset($hours_match[1]) ? (int)$hours_match[1] : 0;
$minutes = isset($minutes_match[1]) ? (int)$minutes_match[1] : 0;
//echo("uses ".$minutes." Minutes and ".$hours." hours");
$start_time = DateTime::createFromFormat('H:i', $time_now);
$end_time = clone $start_time;
$end_time->modify("+{$hours} hour");
$end_time->modify("+{$minutes} minutes");
// Query to get all relevant reservations (today and future overlaps)
$sql = "
SELECT day, time_from, time_to, for_class
FROM reservations
WHERE day >= '$today';
";
$stmt = $link->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
// Check for conflicts with reservations
while ($row = $result->fetch_assoc()) {
$reservation_start = DateTime::createFromFormat('Y-m-d H:i', $row["day"] . ' ' . $row["time_from"]);
$reservation_end = DateTime::createFromFormat('Y-m-d H:i', $row["day"] . ' ' . $row["time_to"]);
// Adjust reservation end time for multi-day overlaps
if ($reservation_end < $reservation_start) {
$reservation_end->modify('+1 day');
}
// Check if the print overlaps with any reservation period
if ($start_time < $reservation_end && $end_time > $reservation_start) {
$reservation_conflict = true;
$for_class[] = $row["for_class"];
}
}
// Default value for for_class if no conflicts are found
if (empty($for_class)) {
$for_class[] = 0;
}
// Build response based on conflict and user access
$response = 0;
if ($reservation_conflict && !in_array($class, $for_class) && $class != 0) {
$response=1;
} elseif ($class == 0 && $reservation_conflict) {
$response=2;
}
return $response;
}
?>

View File

@@ -0,0 +1,14 @@
<?php
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
$username=$_SESSION["username"];
$path = "/var/www/html/user_files/$username/";
$public_path = "/var/www/html/user_files/public/";
if($_GET["pc"]=="1")
$_SESSION["current_file"]=$public_path.$_GET["file"];
else
$_SESSION["current_file"]=$path.$_GET["file"];
?>

View File

@@ -0,0 +1,29 @@
<?php
//this file returns a list of available printers, theyr status and theyr color
session_start();
include "../../config/config.php";
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
$sql = "SELECT p.id, f.name AS color, p.free, p.system_status
FROM printer p
LEFT JOIN filament f ON p.color = f.internal_id
ORDER BY p.id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$printers = [];
while ($row = mysqli_fetch_assoc($result)) {
$printers[] = [
'id' => $row['id'],
'free' => $row['free'],
'error_status' => $row['system_status'],
'color' => htmlspecialchars($row['color'], ENT_QUOTES, 'UTF-8')
];
}
echo json_encode($printers);
?>

View File

@@ -0,0 +1,32 @@
<?php
session_start();
$file_path=$_SESSION["current_file"];
include "../../config/config.php";
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
$username=$_SESSION["username"];
if($_GET["pc"]=="1")
echo(get_base64_preview("/var/www/html/user_files/public/".$_GET["file"]));
else
echo(get_base64_preview("/var/www/html/user_files/$username/".$_GET["file"]));
function get_base64_preview($filename){
$base64="";
$file=fopen($filename,"r");
$start=-1;
while(!feof($file)&&$start!=0){
$buf=fgets($file);
if(stripos($buf,"thumbnail end")!==false)
$start=0;
if($start==1)
$base64.=$buf;
if(stripos($buf,"thumbnail begin")!==false)
$start=1;
}
fclose($file);
$base64=str_replace(";","",$base64);
$base64=str_replace(" ","",$base64);
return $base64;
}
?>

View File

@@ -0,0 +1,385 @@
<?php
//auth stuff
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
header("location: /login/login.php");
exit;
}
$username=htmlspecialchars($_SESSION["username"]);
?>
<!DOCTYPE html>
<html lang="de" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>System0 - Print</title>
<?php include "../../assets/components.php"; ?>
</head>
<body>
<script src="/assets/js/load_page.js"></script>
<script>
function load_user()
{
$(document).ready(function(){
$('#content').load("/assets/php/user_page.php");
});
$(document).ready(function(){
$('#footer').load("/assets/html/footer.html");
});
}
</script>
<script type='text/javascript' >load_user()</script>
<?php
if(isset($_GET["cloudprint"])){
echo("<script>let cloudprint=1;</script>");
echo '<script>fetch("/api/uploader/image_preview.php?file='.$_GET["cloudprint"].'").then(res => res.text()).then(data => document.getElementById("preview").src = "data:image/png;base64," + data).catch(err => console.error("Error:", err));</script>';
}else{
echo("<script>let cloudprint=0;</script>");
}
?>
<!-- navbar -->
<div id="content"></div>
<!-- div where all our content goes -->
<div style="min-height:95vh">
<!-- we need to show a file upload thing and offer the selectnio of printers -->
<div class="container mt-5 d-flex justify-content-center">
<form>
<div class="mb-3">
<label for="fileUpload" class="form-label">3D-Druck Datei</label>
<?php
if(isset($_GET["cloudprint"])){
echo('<input type="text" value="'.$_GET["cloudprint"].'" class="form-control" disabled id="file_upload">');
}else{
echo('<input type="file" class="form-control" accept=".gcode" id="file_upload">');
}
?>
</div>
<?php
if(isset($_GET["cloudprint"])){
echo('<center><img style="display:block; width:100%" id="preview"/></center>');
}
?>
<div class="mb-3">
<label for="selectOption" class="form-label">Drucker</label>
<select class="form-select" id="selectOption">
<option selected value="not_set">Bitte wähle einen Drucker</option>
</select>
</div>
<a style="cursor: pointer" onclick="start_upload(1)" class="btn btn-secondary">Drucken</a>
</form>
</div>
</div>
<!-- footer -->
<div id="footer"></div>
<script>
let global_error="";
//js to handle backend requests
//load printers
document.addEventListener("DOMContentLoaded", function () {
const selectElement = document.getElementById("selectOption");
const apiUrl = "/api/uploader/fetch_printers.php"; // Replace with your actual API URL
function getUrlParam(name) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(name);
}
const preselectId = getUrlParam("preselect"); // Get "preselect" value from URL
fetch(apiUrl)
.then(response => response.json())
.then(data => {
data.forEach(item => {
const option = document.createElement("option");
option.value = item.id;
if(item.free==1){
option.textContent = `Drucker ${item.id} - ${item.color}`;
}else{
option.textContent = `Drucker ${item.id} - ${item.color} - Warteschlange`;
}
if (item.id == preselectId) {
option.selected = true;
}
selectElement.appendChild(option);
});
})
.catch(error => console.error("Error fetching data:", error));
});
async function start_upload(use_checks){
document.getElementById("close_progress_modal2").click();
//main function handles the steps from user pressing upload button via checking params to starting job via api
//we have a modal that shows progress to the user
document.getElementById("close_progress_modal").style.display = "none";
document.getElementById("close_progress_modal2").style.display = "none";
let steps = [
"Initialisierung",
"Datei auf System0 Hochladen",
"Nach Reservationskonflikten suchen",
"Nach Invaliden Druckeinstellungen suchen",
"Job an Drucker senden"
];
let progressContent = document.getElementById("progressContent");
progressContent.innerHTML = ""; // Clear previous content
let modal = new bootstrap.Modal(document.getElementById("progressModal"));
modal.show();
add_step(0,progressContent,steps);
//initialising => set all vars to 0 etc
finish_step(0,progressContent,steps);
if(cloudprint==0){
add_step(1,progressContent,steps);
//upload file to system0
if(await upload_file()==0){
finish_step(1,progressContent,steps);
}else{
add_error("Fehler beim Upload der Datei - "+global_error,progressContent);
cancel_step(1,progressContent,steps);
show_close_button();
return;
}
}else{
//just tell the server what the file is.
await fetch("/api/uploader/cloudprint.php?file=<?php echo($_GET['cloudprint']); ?>");
}
global_error="";
//check if there is a reservation ongoing during this print
add_step(2,progressContent,steps);
let status=await check_reservations();
if(status==0){
finish_step(2,progressContent,steps);
}else if(status==1){
//reserved and user is student
add_error("Die Drucker sind zurzeit reserviert. Bitte versuche es später erneut.", progressContent);
cancel_step(2,progressContent,steps);
show_close_button();
return;
}else if(status==2){
//reserved but user is admin
add_warning("Die Drucker sind Zurzeit reserviert. Als Lehrperson wird ihr Druck allerdings trozdem gedruckt. Bitte gehen Sie sicher, dass nicht eine Klasse beeinträchtigt wird.",progressContent);
finish_step(2,progressContent,steps);
}else{
add_error("Fehler beim überprüfen der Reservationen - "+global_error,progressContent);
cancel_step(2,progressContent,steps);
show_close_button();
return;
}
global_error="";
//search for invalid print settings.
add_step(3,progressContent,steps);
status=await check_illegal_settings(progressContent);
if(status==0){
finish_step(3,progressContent,steps);
}else if(use_checks==0){
add_warning("Warnung: Dieser Druck wird mit sehr hohen Temparaturen gedruckt. Dies kann zur zerstörung des Druckers führen!",progressContent);
finish_step(3,progressContent,steps);
}else if(status==1){
add_error("Achtung deine Drucktemparatur ist sehr hoch eingestellt. Dies kann zur zerstörung des Druckers führen! Bitte fahre nur fort, wenn du dir sicher bist, was du tust!",progressContent);
add_circumvent_link(progressContent);
cancel_step(3,progressContent,steps);
show_close_button();
return;
}else{
add_error("Fehler beim prüfen der Druckeinstellungen",progressContent);
cancel_step(3,progressContent,steps);
show_close_button();
return;
}
global_error="";
//send to printer
add_step(4,progressContent,steps);
status=await start_job();
if(status==0){
finish_step(4,progressContent,steps);
//add_step(5,progressContent,steps);
//finish_step(5,progressContent,steps);
add_success("Job erfolgreich gestartet",progressContent);
}else if(status==2){
finish_step(4,progressContent,steps);
//add_step(5,progressContent,steps);
//finish_step(5,progressContent,steps);
add_success("Job erfolgreich an Warteschlange gesendet",progressContent);
}else{
add_error("Fehler beim starten des Jobs. "+global_error, progressContent);
cancel_step(4,progressContent,steps);
show_close_button();
return;
}
show_close_button();
}
function add_circumvent_link(progressContent) {
let stepHtml = `
<div>
<a onclick="start_upload(0);" style="cursor:pointer" target="_blank" class="step-link">Drücke hier, um alle überprüfungen zu umgehen</a>
</div>
`;
progressContent.innerHTML += stepHtml;
}
function finish_step(index,progressContent,steps){
let stepId = "step-" + index;
let stepElement = document.getElementById(stepId);
if (stepElement) {
stepElement.innerHTML = `
<span class="text-success fw-bold">✔</span>
<span>${steps[index]}</span>
`;
}
if (index >= steps.length-1){
document.getElementById("close_progress_modal").style.display = "block";
document.getElementById("close_progress_modal2").style.display = "block";
}
}
function show_close_button(){
document.getElementById("close_progress_modal").style.display = "block";
document.getElementById("close_progress_modal2").style.display = "block";
}
function cancel_step(index,progressContent,steps){
let stepId = "step-" + index;
let stepElement = document.getElementById(stepId);
if (stepElement) {
stepElement.innerHTML = `
<span class="text-success fw-bold">❌</span>
<span>${steps[index]}</span>
`;
}
document.getElementById("close_progress_modal").style.display = "block";
document.getElementById("close_progress_modal2").style.display = "block";
}
function add_error(msg,progressContent){
let errorHtml = `
<br>
<div class='alert alert-danger' role='alert'>Fehler - ${msg}</div>
`;
progressContent.innerHTML += errorHtml;
}
function add_success(msg,progressContent){
let errorHtml = `
<br>
<div class='alert alert-success' role='alert'>Erfolg - ${msg}</div>
`;
progressContent.innerHTML += errorHtml;
}
function add_warning(msg,progressContent){
let errorHtml = `
<br>
<div class='alert alert-warning' role='alert'>Warnung - ${msg}</div>
`;
progressContent.innerHTML += errorHtml;
}
function add_step(index,progressContent,steps) {
let stepId = "step-" + index;
let stepHtml = `
<div class="step-container" id="${stepId}">
<span class="spinner-border text-primary" role="status"></span>
<span>${steps[index]}</span>
</div>
`;
progressContent.innerHTML += stepHtml;
}
async function check_illegal_settings(progressContent){
try {
const response = await fetch("/api/uploader/check_illegal_settings.php");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
if(data["status"]!=0){
global_error="Dieser Fehler ist auf dem Drucker. Warte einige Minuten und versuche es erneut.";
}
return data["status"];
} catch (error) {
return 4;
}
}
async function start_job(){
let printer_id=document.getElementById("selectOption").value;
if(printer_id=="not_set"){
global_error="Kein Drucker ausgewählt";
return 5;
}
try {
const response = await fetch("/api/uploader/start_job.php?printer="+printer_id);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data["status"];
} catch (error) {
return 5;
}
}
async function upload_file(){
const fileInput = document.getElementById('file_upload');
const file = fileInput.files[0];
if (!file) {
global_error="Keine Datei ausgewählt";
return 1;
}
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('/api/uploader/upload_file.php', {
method: 'POST',
body: formData,
});
if (response.ok) {
const result = await response.json();
if(result.status=="error"){
global_error=result.message;
return 1;
}
} else {
return 1;
}
} catch (error) {
return 1;
}
return 0;
}
async function check_reservations() {
try {
const response = await fetch("/api/uploader/check_reservations.php");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data["status"];
} catch (error) {
return 4;
}
}
</script>
<!-- progress modal -->
<div class="modal fade" id="progressModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" role="dialog" aria-labelledby="progressModalLabel" aria-hidden="false">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="progressModalLabel">Fortschritt</h5>
<button id="close_progress_modal" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schliessen"></button>
</div>
<div class="modal-body">
<div id="progressContent"></div>
</div>
<div class="modal-footer">
<button id="close_progress_modal2" type="button" class="btn btn-secondary" data-bs-dismiss="modal">Schliessen</button>
</div>
</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,58 @@
<?php
//this file returns a list of available printers, theyr status and theyr color
session_start();
$file_path=$_SESSION["current_file"];
include "../../config/config.php";
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
include "../../config/config.php";
//if printer is ready, upload to printer, else upload to queue
//return 0 if success, else return any int
$printer_id=intval($_GET["printer"]);
//check if printer is ready
$sql="select printer_url, free, system_status,apikey,printer_url from printer where id=$printer_id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $url,$free,$status,$apikey,$printer_url);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
$result=1;
$username=$_SESSION["username"];
$userid=$_SESSION["id"];
if($free==1 && $status==0){
//upload to printer
exec('curl -k -H "X-Api-Key: '.$apikey.'" -F "select=true" -F "print=true" -F "file=@'.$path.'" "'.$printer_url.'/api/files/local" > /var/www/html/user_files/'.$username.'/json.json');
$fg=file_get_contents("/var/www/html/user_files/$username/json.json");
$json=json_decode($fg,true);
if($json['effectivePrint']!=true or $json["effectiveSelect"]!=true)
{
$result=1;
}
else
{
$sql="update printer set free=0, printing=1,mail_sent=0, used_by_userid=$userid where id=$printer_id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$result=0;
}
}else if($free!=1 && $status==0){
//upload to queue
$path=$_SESSION["current_file"];
$sql="INSERT INTO queue (from_userid,filepath,print_on) VALUES (?,?,?)";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, "isi", $userid,$path,$printer_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$result=2;
}else{
//error
$result=1;
}
echo(json_encode(["status"=>$result]));
?>

View File

@@ -0,0 +1,33 @@
<?php
session_start();
include "../../config/config.php";
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
$username=$_SESSION["username"];
$path = "/var/www/html/user_files/$username/";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (isset($_FILES["file"]) && $_FILES["file"]["error"] === UPLOAD_ERR_OK) {
$fileTmpPath = $_FILES["file"]["tmp_name"];
$fileName = basename($_FILES["file"]["name"]);
$filePath = $path . $fileName;
$filetype = strtolower(pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION));
if($filetype==="gcode"){
if (move_uploaded_file($fileTmpPath, $filePath)) {
echo json_encode(["status" => "success", "message" => "Datei hochgeladen", "file" => $filePath]);
$_SESSION["current_file"]="$filePath";
} else {
echo json_encode(["status" => "error", "message" => "Konnte datei nicht in Benutzerordner verschieben"]);
}
}else{
echo json_encode(["status" => "error", "message" => "Dieser Dateityp wird nicht unterstützt"]);
}
} else {
echo json_encode(["status" => "error", "message" => "Unbekannter Fehler"]);
}
} else {
echo json_encode(["status" => "error", "message" => "Invalide Anfrage"]);
}
?>

View File

@@ -0,0 +1,18 @@
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"][3] !== "1") {
header("location: /login/login.php");
exit;
}
require_once "../config/config.php";
$userId = $_POST['userId'];
$sql = "UPDATE users SET banned = 0 WHERE id = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->close();
?>

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html>
<html data-bs-theme="dark">
<?php
// Initialize the session
session_start();
@@ -53,7 +53,7 @@ function load_user()
<label class="my-3" for="email">Deine Email für weitere Nachfragen (optional)</label>
<input type="text" class="form-control mx-auto" id="email" name="email" style="width:50%;" value="<?php echo($_SESSION["username"]); ?>">
</div>
<button type="submit" class="btn btn-dark my-5">abschicken</button>
<button type="submit" class="btn btn-secondary my-5">abschicken</button>
</form>
<?php
if(isset($_GET["sent"]))

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html>
<html data-bs-theme="dark">
<?php
// Initialize the session
session_start();
@@ -58,13 +58,18 @@ function load_user()
}
if(isset($_GET["delete"])){
$path="/var/www/html/user_files/$username/".str_replace("..","",htmlspecialchars($_GET["delete"]));
unlink($path);
if(unlink($path))
$success="Datei wurde gelöscht!";
else
$err="Datei konnte nicht gelöscht werden!";
}
if(isset($_GET["public"])){
$path="/var/www/html/user_files/$username/".str_replace("..","",htmlspecialchars($_GET["public"]));
$public_path="/var/www/html/user_files/public/".str_replace("..","",htmlspecialchars($_GET["public"]));
copy($path,$public_path);
if(copy($path,$public_path))
$success="Datei wurde veröffentlicht";
else
$err="Datei konnte nicht veröffentlicht werden.";
}
if(!empty($_FILES['file']))
{
@@ -77,16 +82,16 @@ function load_user()
$path = $path . $filename;
if(!in_array($filetype,$ok_ft))
{
$file_upload_err="Dieser Dateityp wird nicht unterstüzt.";
$err="Dieser Dateityp wird nicht unterstüzt.";
}
else
{
if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
$file_upload_err="ok";
$success="Datei wurde hochgeladen.";
}
else
{
$file_upload_err="Ein Fehler beim Uploaden der Datei ist aufgetreten! Versuche es erneut!";
$err="Ein Fehler beim Uploaden der Datei ist aufgetreten! Versuche es erneut!";
}
}
unset($_FILES['file']);
@@ -101,20 +106,19 @@ function load_user()
<body>
<div class="container mt-4" style="height: auto;min-height:100vh">
<div class="row justify-content-center">
<!--<div style="width: 90vh">-->
<?php
if(!empty($file_upload_err)&&$file_upload_err!="nan"&&$file_upload_err!="ok")
echo("<center><div style='width:50%' class='alert alert-danger' role='alert'>$file_upload_err</div></center>");
else if($file_upload_err!="nan")
echo("<center><div style='width:50%' class='alert alert-success' role='alert'>Datei wurde hochgeladen</div></center>");
?>
<h1>Eigene Dateien</h1>
<div class="container">
<button type="button" class="btn btn-link" data-bs-toggle="modal" data-bs-target="#upoload_file" id="lnk_1">Datei Hochladen</button>
<form action="cloud.php" method="POST">
<input type="text" name="search" placeholder="Suchbegriff">
<button type="submit" class="btn btn-dark my-5">Suchen</button>
<button type="submit" class="btn btn-secondary my-5">Suchen</button>
</form>
<?php
if(!empty($success))
echo("<center><div class='alert alert-success' role='alert'>$success</div></center>");
if(!empty($err))
echo("<center><div class='alert alert-danger' role='alert'>$err</div></center>");
?>
<div style="overflow-y:auto;overflow-x:auto">
<table class="table">
<thead>
@@ -129,11 +133,11 @@ function load_user()
</thead>
<tbody>
<?php
$directory = "/var/www/html/user_files/$username/"; // Replace with the actual path to your directory
$directory = "/var/www/html/user_files/$username/";
// Check if the directory exists
if (is_dir($directory)) {
$files = glob($directory . '/*.gcode');
$files = glob($directory . '/*.gcode'); //*/
// Iterate through the files and display them in the table
@@ -185,7 +189,7 @@ function load_user()
<label for="file" class="form-label">Datei wählen:</label>
<input type="file" class="form-control" id="file" name="file" required accept=".gcode">
</div>
<button type="submit" class="btn btn-dark">Upload</button> <br>
<button type="submit" class="btn btn-secondary">Upload</button> <br>
</form>
</div>

View File

@@ -136,7 +136,7 @@ if($_SERVER["REQUEST_METHOD"] == "POST"){
?>
<!DOCTYPE html>
<html lang="en">
<html lang="en" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
@@ -215,7 +215,7 @@ if($_SERVER["REQUEST_METHOD"] == "POST"){
</tbody>
</table>
</div>
<button type="submit" name="submit" class="btn btn-dark">Create Account</button><br><br>
<button type="submit" name="submit" class="btn btn-secondary">Create Account</button><br><br>
</form>
<?php
if(!empty($err)){

View File

@@ -10,7 +10,7 @@ if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION[
?>
<!DOCTYPE html>
<html>
<html data-bs-theme="dark">
<head>
<title>Account Einstellungen</title>
</head>
@@ -61,7 +61,7 @@ if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION[
Ein Druckschlüssel ist ein Code, welcher ein Benutzer benutzen kann, um einen Druckauftrag zu starten.
</p>
<form action="create_key.php?create=true" method="post">
<button type="submit" value="create_key" class="btn btn-dark">Neuen Druckschlüssel generieren</button>
<button type="submit" value="create_key" class="btn btn-secondary">Neuen Druckschlüssel generieren</button>
</form>
</div>
<?php

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html>
<html data-bs-theme="dark">
<?php
// Initialize the session
session_start();
@@ -151,9 +151,9 @@ async function delete_input(input,action,id,row){
mysqli_stmt_fetch($stmt);
if($system_status==0)
echo("<tr><td>$printer_id</td><td><form method='POST' action='?free=$printer_id&show=$tab'><button type='submit' value='free' name='free' class='btn btn-dark'>Free</button></form></td><td><a href='debug.php?update_status=$printer_id&status=1&show=$tab' class='btn btn-danger'>Status auf kaputt setzen</a></td></tr>");
echo("<tr><td>$printer_id</td><td><form method='POST' action='?free=$printer_id&show=$tab'><button type='submit' value='free' name='free' class='btn btn-secondary'>Free</button></form></td><td><a href='debug.php?update_status=$printer_id&status=1&show=$tab' class='btn btn-danger'>Status auf kaputt setzen</a></td></tr>");
else
echo("<tr><td>$printer_id</td><td><form method='POST' action='?free=$printer_id&show=$tab'><button type='submit' value='free' name='free' class='btn btn-dark'>Free</button></form></td><td><a href='debug.php?update_status=$printer_id&status=0&show=$tab' class='btn btn-success'>Status auf bereit setzen</a></td></tr>");
echo("<tr><td>$printer_id</td><td><form method='POST' action='?free=$printer_id&show=$tab'><button type='submit' value='free' name='free' class='btn btn-secondary'>Free</button></form></td><td><a href='debug.php?update_status=$printer_id&status=0&show=$tab' class='btn btn-success'>Status auf bereit setzen</a></td></tr>");
$cnt--;
}
echo("</tbody></table></div></div></div></div>");

View File

@@ -12,7 +12,7 @@ if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
?>
<!DOCTYPE html>
<html>
<html data-bs-theme="dark">
<head>
<title>Account settings</title>
<!-- <link rel="stylesheet" href="/system0/html/php/login/css/style.css"> -->

View File

@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Wartungsmodus</title>
<!-- Bootstrap CSS -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f8f9fa;
}
.maintenance-message {
text-align: center;
max-width: 600px;
padding: 20px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: #fff;
}
</style>
</head>
<body>
<div class="maintenance-message">
<h1 class="display-4">Wartungsmodus</h1>
<p class="lead">System0-2.0 wird derzeit gewartet. Wir sind bald wieder für Sie da.</p>
<hr class="my-4">
<p>Vielen Dank für Ihr Verständnis und Ihre Geduld.</p>
</div>
<!-- Bootstrap JS and dependencies (optional) -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.3.0/js/bootstrap.min.js"></script>
</body>
</html>

View File

@@ -1,22 +1,25 @@
<!DOCTYPE html>
<html>
<title>Manage user</title>
<html lang="de" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Benutzerverwaltung</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body style="background-color: <?php echo $_SESSION['color']; ?>;">
<?php
// Initialize the session
session_start();
require_once "../log/log.php";
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"][3]!== "1"){
require_once "../config/config.php";
include "../assets/components.php";
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"][3] !== "1") {
header("location: /login/login.php");
exit;
}
$_SESSION["rid"]++;
?>
<?php
$color=$_SESSION["color"];
include "../assets/components.php";
?>
<script src="/assets/js/load_page.js"></script>
<script>
function load_user()
@@ -26,271 +29,86 @@ function load_user()
});
}
</script>
<?php $color=$_SESSION["color"]; ?>
<?php echo("<body style='background-color:$color'> ");?>
<div id="content"></div>
<?php
function get_perm_string(){
$perm_str="";
if(isset($_POST["print"]))
$perm_str.="1";
else
$perm_str.="0";
if(isset($_POST["private_cloud"]))
$perm_str.="1";
else
$perm_str.="0";
if(isset($_POST["public_cloud"]))
$perm_str.="1";
else
$perm_str.="0";
if(isset($_POST["printer_ctrl_all"]))
$perm_str.="1";
else
$perm_str.="0";
if(isset($_POST["change_user_perm"]))
$perm_str.="1";
else
$perm_str.="0";
if(isset($_POST["create_admin"]))
$perm_str.="1";
else
$perm_str.="0";
if(isset($_POST["view_log"]))
$perm_str.="1";
else
$perm_str.="0";
if(isset($_POST["view_apikey"]))
$perm_str.="1";
else
$perm_str.="0";
if(isset($_POST["create_key"]))
$perm_str.="1";
else
$perm_str.="0";
if(isset($_POST["debug"]))
$perm_str.="1";
else
$perm_str.="0";
if(isset($_POST["delete_from_public_cloud"]))
$perm_str.="1";
else
$perm_str.="0";
return $perm_str;
}
function deleteDirectory($dir) {
if (!is_dir($dir)) {
return;
}
// Get list of files and directories inside the directory
$files = scandir($dir);
foreach ($files as $file) {
// Skip current and parent directory links
if ($file == '.' || $file == '..') {
continue;
}
$path = $dir . '/' . $file;
if (is_dir($path)) {
// Recursively delete sub-directory
deleteDirectory($path);
} else {
// Delete file
unlink($path);
}
}
// Delete the empty directory
rmdir($dir);
}
echo ("<script type='text/javascript' >load_user()</script>");
require_once "../config/config.php";
if(isset($_GET["update_id"]) && $_GET["rid"]==$_SESSION["rid"]-1){
$tid=$_GET["update_id"];
$perms=get_perm_string();
$sql="UPDATE users SET role = '$perms' WHERE id=$tid";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
}
if(isset($_GET['username']) && isset($_GET["delete"]))
{
$username_td=$_GET['username'];
$username_td=htmlspecialchars($username_td);
$sql="DELETE FROM users WHERE username = '$username_td';";
//echo($sql);
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
deleteDirectory("/var/www/html/user_files/$username_td/");
log_("Deleted $username_td","BAN:DELETION");
}
else if(isset($_GET["verify"]) && isset($_GET['username']))
{
$username_td=htmlspecialchars($_GET['username']);
$sql="UPDATE users SET banned = 0 WHERE username='$username_td'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
log_("Unanned $username_td","BAN:UNBAN");
}
//how many users do we have?
$cnt=0;
$sql="SELECT COUNT(*) FROM users";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $cnt);
if(mysqli_stmt_fetch($stmt)){
}
} else{
echo "<div class='alert alert-danger' role='alert'>Oops! Something went wrong. Please try again later.</div>";
}
// Close statement
mysqli_stmt_close($stmt);
}
?>
<div class="container" style="min-height:95vh; min-width:100%">
<div class="row">
<div class="col-mt-12" style="overflow-x:auto">
<div class="d-flex flex-column align-items-center">
<h4>Nach Benutzer suchen, um zu verwalten</h4>
<form action="manage_user.php" method="GET" >
<input type="text" class="form-control flex-grow-1 mr-2" name="username" placeholder="Benutzername eingeben" >
<div class="container mt-12" style="min-height:95vh">
<h4>Benutzer suchen und verwalten</h4>
<form id="userSearchForm">
<input type="text" class="form-control" name="username" placeholder="Benutzername eingeben">
<button type="submit" class="btn btn-primary">Suchen</button>
</form>
<div style="overflow-x: auto;">
<table class="table mt-5" id="userTable" >
<thead>
<tr>
<th>Nutzer</th>
<th>Klasse</th>
<th>Drucken</th>
<th>Private Cloud</th>
<th>Öffentliche Cloud</th>
<th>Alle Drucker freigeben</th>
<th>Benutzerrechte</th>
<th>Admin erstellen</th>
<th>Log ansehen</th>
<th>API-Key</th>
<th>Druckschlüssel</th>
<th>Debug</th>
<th>Öffentliche Dateien löschen</th>
<th>Manuell verifizieren</th>
<th>Löschen</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<!-- list users and their permissions -->
<?php
echo("<table class='table' style='overflow-x: auto'>");
echo("<thead>");
echo("<tr>");
echo("<td>Nutzer</td>");
echo("<td>Drucken</td>");
echo("<td>Cloud</td>");
echo("<td>Öffentliche Cloud</td>");
echo("<td>Alle Drucker abbrechen / freigeben</td>");
echo("<td>Benutzereinstellungen ändern</td>");
echo("<td>Administratoren erstellen</td>");
echo("<td>Log ansehen</td>");
echo("<td>APIkey ansehen</td>");
echo("<td>Druckschlüssel erstellen</td>");
echo("<td>Debug</td>");
echo("<td>Alle Dateien von Öffentlicher Cloud löschen</td>");
echo("<td>Aktualisieren</td>");
echo("<td>Benutzer löschen</td>");
echo("<td>Benutzer manuell verifizieren</td>");
echo("</tr>");
echo("</thead>");
echo("<tbody>");
echo("<tr>");
//how many users do we have?
$cnt=0;
if(isset($_GET["username"]))
$search=htmlspecialchars($_GET["username"]);
else
$search="user_not_found";
<div id="footer">
</div>
$sql="SELECT COUNT(*) FROM users WHERE username LIKE '%$search%'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
// Store result
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $cnt);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
//now we know how many users we have.
$last_id=0;
while($cnt!=0){
$tusername="";
$trole="";
$banned=0;
$tid=0;
$sql="select id,username,role,banned from users where id>$last_id AND username LIKE '%$search%' ORDER BY id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
// Store result
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $tid,$tusername,$trole,$banned);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
echo("<tr><form action='manage_user.php?update_id=$tid&rid=".$_SESSION["rid"]."&username=$search' method='post'>");
echo("<td>$tusername</td>");
if($trole[0]==="1")
echo('<td><input class="form-check-input" type="checkbox" value="" name="print" checked></td>');
else
echo('<td><input class="form-check-input" type="checkbox" value="" name="print" ></td>');
if($trole[1]==="1")
echo('<td><input class="form-check-input" type="checkbox" value="" name="private_cloud" checked></td>');
else
echo('<td><input class="form-check-input" type="checkbox" value="" name="private_cloud" ></td>');
if($trole[2]==="1")
echo('<td><input class="form-check-input" type="checkbox" value="" name="public_cloud" checked></td>');
else
echo('<td><input class="form-check-input" type="checkbox" value="" name="public_cloud" ></td>');
if($trole[3]==="1")
echo('<td><input class="form-check-input" type="checkbox" value="" name="printer_ctrl_all" checked></td>');
else
echo('<td><input class="form-check-input" type="checkbox" value="" name="printer_ctrl_all" ></td>');
if($trole[4]==="1")
echo('<td><input class="form-check-input" type="checkbox" value="" name="change_user_perm" checked></td>');
else
echo('<td><input class="form-check-input" type="checkbox" value="" name="change_user_perm" ></td>');
if($trole[5]==="1")
echo('<td><input class="form-check-input" type="checkbox" value="" name="create_admin" checked></td>');
else
echo('<td><input class="form-check-input" type="checkbox" value="" name="create_admin" ></td>');
if($trole[6]==="1")
echo('<td><input class="form-check-input" type="checkbox" value="" name="view_log" checked></td>');
else
echo('<td><input class="form-check-input" type="checkbox" value="" name="view_log" ></td>');
if($trole[7]==="1")
echo('<td><input class="form-check-input" type="checkbox" value="" name="view_apikey" checked></td>');
else
echo('<td><input class="form-check-input" type="checkbox" value="" name="view_apikey" ></td>');
if($trole[8]==="1")
echo('<td><input class="form-check-input" type="checkbox" value="" name="create_key" checked></td>');
else
echo('<td><input class="form-check-input" type="checkbox" value="" name="create_key" ></td>');
if($trole[9]==="1")
echo('<td><input class="form-check-input" type="checkbox" value="" name="debug" checked></td>');
else
echo('<td><input class="form-check-input" type="checkbox" value="" name="debug" ></td>');
if($trole[10]==="1")
echo('<td><input class="form-check-input" type="checkbox" value="" name="delete_from_public_cloud" checked></td>');
else
echo('<td><input class="form-check-input" type="checkbox" value="" name="delete_from_public_cloud" ></td>');
echo('<td><input type="submit" class="btn btn-dark mb-5" value="Aktualisieren" id="button"></td>');
echo('<td><a href="manage_user.php?username='.$tusername.'&delete" class="btn btn-danger" >Benutzer löschen</a></td>');
if($banned==1)
echo('<td><a href="manage_user.php?username='.$tusername.'&verify" class="btn btn-success" >Benutzer verifizieren</a></td>');
else
echo('<td>Benutzer bereits verifiziert</td>');
echo("</form></tr>");
$last_id=$tid;
$cnt--;
<script>
$(document).ready(function () {
function fetchUsers(username = '') {
$.get('/api/fetch_users.php', { username }, function (data) {
$('#userTable tbody').html(data);
});
}
// echo("</tr>");
echo("</tbody>");
echo("</table>");
mysqli_close($link);
?>
</div>
</div>
</div>
<div id="footer"></div>
$('#userSearchForm').on('submit', function (e) {
e.preventDefault();
const username = $(this).find('[name="username"]').val();
fetchUsers(username);
});
$(document).on('change', '.updateField', function () {
const field = $(this).data('field');
const userId = $(this).data('userid');
const value = $(this).is(':checkbox') ? ($(this).is(':checked') ? 1 : 0) : $(this).val();
$.post('/api/update_user.php', { userId, field, value }, function (response) {
console.log(response);
});
});
$(document).on('click', '.deleteUser', function () {
const userId = $(this).data('userid');
if (confirm('Sind Sie sicher, dass Sie diesen Benutzer löschen möchten?')) {
$.post('/api/delete_user.php', { userId }, function () {
fetchUsers();
});
}
});
$(document).on('click', '.verify_user', function () {
const userId = $(this).data('userid');
$.post('/api/verify_user.php', { userId }, function () {
fetchUsers();
});
});
fetchUsers(); // Initiale Benutzer laden
load_user();
});
</script>
</body>
</html>

View File

@@ -1,124 +1,25 @@
<!DOCTYPE html>
<html>
<html data-bs-theme="dark">
<head>
<title>System0 Übersicht</title>
<?php
// Initialize the session
session_start();
include "../config/config.php";
include "../api/queue.php";
$role=$_SESSION["role"];
$username=$_SESSION["username"];
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
// Initialize the session
session_start();
include "../config/config.php";
include "../api/queue.php";
include "../assets/components.php";
$role=$_SESSION["role"];
$username=$_SESSION["username"];
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: /login/login.php");
exit;
}
$username=htmlspecialchars($_SESSION["username"]);
$id=$_SESSION["id"];
?>
<script src="/assets/js/load_page.js"></script>
<script>
function load_user()
{
$(document).ready(function(){
$('#content').load("/assets/php/user_page.php");
});
}
</script>
<?php
echo "<script type='text/javascript' >load_user()</script>";
?>
<?php $color=$_SESSION["color"]; ?>
<?php
function seconds_to_time($seconds) {
// Convert seconds to hours
$hours = floor($seconds / 3600);
// Convert remaining seconds to minutes
$minutes = floor(($seconds % 3600) / 60);
if($hours!=0){
if($hours==1)
return sprintf("%d Stunde %d Minuten", $hours, $minutes);
else
return sprintf("%d Stunden %d Minuten", $hours, $minutes);
}
else
return sprintf("%d Minuten", $minutes);
}
function short_path($filePath, $firstCharsCount, $lastCharsCount) {
// Get the first few characters of the path
$filePath=str_replace(".gcode","",$filePath);
if(strlen($filePath)>=$firstCharsCount+$lastCharsCount+3){
$firstChars = substr($filePath, 0, $firstCharsCount);
// Get the last few characters of the path
$lastChars = substr($filePath, -$lastCharsCount);
// Return the shortened path
return $firstChars . "..." . $lastChars;
}
else{
return $filePath;
}
}
$color=$_SESSION["color"];
include "../assets/components.php";
if(!isset($_SESSION["rid"]))
$_SESSION["rid"]=0;
$username=htmlspecialchars($_SESSION["username"]);
$id=$_SESSION["id"];
$_SESSION["rid"]++;
if(isset($_GET["set_class"]) && isset($_POST["class"])){
$class_id=htmlspecialchars($_POST["class"]);
$sql="update users set class_id=$class_id where username='$username'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
$stmt->close();
$sql="select name from class where id=$class_id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
$class_name="";
mysqli_stmt_bind_result($stmt, $class_name);
$stmt->close();
$_SESSION["class"]=$class_name;
$_SESSION["class_id"]=$class_id;
}
?>
<title>Alle Drucker</title>
<style>
/* Style for the description */
.description {
display: none; /* Hide the description by default */
position: absolute;
background-color: rgba(0, 0, 0, 0.7);
color: #fff;
padding: 10px;
border-radius: 5px;
width: 200px;
}
/* Style for the element to trigger hover */
.hover-element {
position: relative;
/* Add some space below the element */
}
/* Style for the element to trigger hover when hovered */
.hover-element:hover .description {
display: block; /* Show the description on hover */
}
</style>
</head>
<body>
<div id="content"></div>
<div>
<div class="row justify-content-center">
<div style="width: 100%;min-height:95vh">
<?php
//echo("GOT RID: ".$_GET["rid"]." Expected RID: ".$_SESSION["rid"]-1);
if(isset($_GET['free'])&&$_GET["rid"]==($_SESSION["rid"]-1))
{
$cnt="";
@@ -129,7 +30,7 @@ function load_user()
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $cnt);
mysqli_stmt_fetch($stmt);
$sql="update printer set free=1,printing=0,cancel=0 ,used_by_userid=0 where id=$printer_id";
$sql="update printer set free=1,printing=0,cancel=0, used_by_userid=0 where id=$printer_id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
//try to find out how much filament was used
@@ -152,12 +53,9 @@ function load_user()
if(isset($json['job']['filament']['tool0']['volume'])){
$filament_usage=intval($json['job']['filament']['tool0']['volume']);
$sql="UPDATE users SET filament_usage = COALESCE(filament_usage,0) + $filament_usage WHERE id = $cnt";
//echo($sql);
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
}
//echo("used $filament_usage mm of filament");
}
if(isset($_GET['remove_queue'])&&$_GET["rid"]==($_SESSION["rid"]-1))
{
@@ -191,264 +89,91 @@ function load_user()
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
}
}
$cnt=0;
$url="";
$apikey="";
if(isset($_GET["private"]))
$sql="select count(*) from printer where used_by_userid=".$_SESSION["id"];
else
$sql="select count(*) from printer";
if(isset($_GET["set_class"]) && isset($_POST["class"])){
$class_id=htmlspecialchars($_POST["class"]);
$sql="update users set class_id=$class_id where username='$username'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $cnt);
mysqli_stmt_fetch($stmt);
//echo($cnt);
$is_free=0;
echo("<div><div class='row'>");
echo("<div class='d-flex flex-wrap justify-content-center align-items-stretch'>");
echo("<div style='width:100%;margin-left:5px'>");
if(isset($_GET["private"]))
echo("<br><a class='btn btn-dark' href='overview.php'>Alle Drucker anzeigen</a>");
else
echo("<br><a class='btn btn-dark' href='overview.php?private'>Nur eigene Aufträge anzeigen</a>");
echo("</div>");
$last_id=0;
$system_status=0;
$rotation=0;
while($cnt!=0)
$stmt->close();
$sql="select name from class where id=$class_id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
$class_name="";
mysqli_stmt_bind_result($stmt, $class_name);
$stmt->close();
$_SESSION["class"]=$class_name;
$_SESSION["class_id"]=$class_id;
}
?>
<script src="/assets/js/load_page.js"></script>
<script>
function load_user()
{
$userid=0;
if(isset($_GET["private"]))
$sql="select rotation,free,id,printer_url,apikey,cancel,used_by_userid,system_status,color from printer where id>$last_id and used_by_userid=".$_SESSION["id"]." ORDER BY id";
else
$sql="select rotation,free,id,printer_url,apikey,cancel,used_by_userid,system_status,color from printer where id>$last_id ORDER BY id";
$cancel=0;
$filament_color="";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $rotation,$is_free,$printer_id,$url,$apikey,$cancel,$userid,$system_status,$filament_color);
mysqli_stmt_fetch($stmt);
$last_id=$printer_id;
$filament_color=intval($filament_color);
//get the real color
$sql="select name from filament where internal_id=$filament_color";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt,$filament_color);
mysqli_stmt_fetch($stmt);
$(document).ready(function(){
$('#content').load("/assets/php/user_page.php");
});
}
load_user();
//check queue
fetch("/api/async_queue_check.php");
</script>
<style>
.description {
display: none; /* Hide the description by default */
position: absolute;
background-color: rgba(0, 0, 0, 0.7);
color: #fff;
padding: 10px;
border-radius: 5px;
width: 200px;
z-index: 10; /* Ensure it appears above other elements */
}
if($is_free==0 && $system_status==0){
//printer is printing
exec("curl --max-time 10 $url/api/job?apikey=$apikey > /var/www/html/user_files/$username/json.json");
$fg=file_get_contents("/var/www/html/user_files/$username/json.json");
$json=json_decode($fg,true);
/* Style for the element to trigger hover */
.hover-element {
position: relative;
/* Add some space below the element */
}
/* Style for the element to trigger hover when hovered */
.hover-element:hover .description {
display: block; /* Show the description on hover */
}
</style>
</head>
<body>
<div id="content"></div>
<!-- placeholder button to be activated to open cancel modal -->
<button style="display:none" type="button" class="btn btn-primary" data-bs-toggle="modal" id="open_cancel_modal" data-bs-target="#cancel_modal">
Launch cancel modal
</button>
<div id="printer-container"></div>
$used_by_user="";
$sql="select username from users where id=$userid";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $used_by_user);
mysqli_stmt_fetch($stmt);
$username2=explode("@",$used_by_user);
$progress=(int) $json['progress']['completion'];
if($progress<0)
$progress=-$progress;
$file=$json['job']['file']['name'];
if($progress==100){
$print_time=seconds_to_time(intval($json["progress"]["printTime"]));
$print_time_left=seconds_to_time(intval($json["progress"]["printTimeLeft"]));
$print_time_total=seconds_to_time(intval($json["job"]["estimatedPrintTime"]));
echo("<div class='card m-4 align-self-start'>");
echo("<div class='card-body'>");
echo("<h5 class='card-title'>Drucker $printer_id</h5>");
echo("</div>");
echo("<div class='card-body'>");
echo("<iframe height='230px' scrolling='no' width='100%' src='/app/webcam.php?printer_id=$printer_id&username=".$_SESSION["username"]."&url=$url&rotation=$rotation'></iframe>");
echo("<div class='progress'>");
echo("<div class='progress-bar' role='progressbar' style='width: $progress%' aria-valuenow='$progress' aria-valuemin='0' aria-valuemax='100'>$progress%</div>");
echo("</div>");
echo("<table class='table table-borderless'>");
echo("<thead>");
echo("<tr><td>Status</td><td style='color:green'>Fertig</td></tr>");
echo("<tr><td>Genutzt von</td><td>".$username2[0]."</td></tr>");
if(!empty($filament_color) && $filament_color!=NULL)
echo("<tr><td>Filamentfarbe</td><td >$filament_color</td></tr>");
echo("<tr><td>Erwartete Druckzeit</td><td>$print_time_total</td></tr>");
echo("<tr><td>Verbleibende Druckzeit</td><td>$print_time_left</td></tr>");
echo("<tr><td>Vergangene Druckzeit</td><td>$print_time</td></tr>");
echo("<tr><td>Datei</td><td><div class='hover-element'>".short_path($json["job"]["file"]["name"],10,10)."<div class='description'>".$json["job"]["file"]["name"]."</div></div></td></tr>");
echo("</div>");
if($userid==$_SESSION["id"] or $role[3]==="1"){
echo("<tr><td><a class='btn btn-success' href='overview.php?free=$printer_id&rid=".$_SESSION["rid"]."'>Freigeben</a></td></tr>");
}
echo("</thead>");
echo("</table>");
echo("</div>");
echo("</div>");
}
else if($cancel==1){
$print_time=seconds_to_time(intval($json["progress"]["printTime"]));
$print_time_left=seconds_to_time(intval($json["progress"]["printTimeLeft"]));
$print_time_total=seconds_to_time(intval($json["job"]["estimatedPrintTime"]));
echo("<div class='card m-4 align-self-start'>");
echo("<div class='card-body'>");
echo("<h5 class='card-title'>Drucker $printer_id</h5>");
echo("</div>");
echo("<div class='card-body'>");
echo("<iframe height='230px' scrolling='no' width='100%' src='/app/webcam.php?printer_id=$printer_id&username=".$_SESSION["username"]."&url=$url&rotation=$rotation'></iframe>");
echo("<div class='progress'>");
echo("<div class='progress-bar' role='progressbar' style='width: $progress%' aria-valuenow='$progress' aria-valuemin='0' aria-valuemax='100'>$progress%</div>");
echo("</div>");
echo("<table class='table table-borderless'>");
echo("<thead>");
echo("<tr><td>Status</td><td style='color:red'>Druck Abgebrochen</td></tr>");
echo("<tr><td>Genutzt von</td><td>".$username2[0]."</td></tr>");
if(!empty($filament_color) && $filament_color!=NULL)
echo("<tr><td>Filamentfarbe</td><td >$filament_color</td></tr>");
echo("<tr><td>Erwartete Druckzeit</td><td>$print_time_total</td></tr>");
echo("<tr><td>Verbleibende Druckzeit</td><td>$print_time_left</td></tr>");
echo("<tr><td>Vergangene Druckzeit</td><td>$print_time</td></tr>");
echo("<tr><td>Datei</td><td><div class='hover-element'>".short_path($json["job"]["file"]["name"],10,10)."<div class='description'>".$json["job"]["file"]["name"]."</div></div></td></tr>");
if($userid==$_SESSION["id"] or $role[3]=="1"){
echo("<tr><td><a class='btn btn-success' href='overview.php?free=$printer_id&rid=".$_SESSION["rid"]."'>Freigeben</a></td></tr>");
}
echo("</thead>");
echo("</table>");
echo("</div>");
echo("</div>");
}
else{
$print_time=seconds_to_time(intval($json["progress"]["printTime"]));
$print_time_left=seconds_to_time(intval($json["progress"]["printTimeLeft"]));
$print_time_total=seconds_to_time(intval($json["job"]["estimatedPrintTime"]));
echo("<div class='card m-4 align-self-start'>");
echo("<div class='card-body'>");
echo("<h5 class='card-title'>Drucker $printer_id</h5>");
echo("</div>");
echo("<div class='card-body'>");
echo("<iframe height='230px' scrolling='no' width='100%' src='/app/webcam.php?printer_id=$printer_id&username=".$_SESSION["username"]."&url=$url&rotation=$rotation'></iframe>");
echo("<div class='progress'>");
echo("<div class='progress-bar' role='progressbar' style='width: $progress%' aria-valuenow='$progress' aria-valuemin='0' aria-valuemax='100'>$progress%</div>");
echo("</div>");
echo("<table class='table table-borderless'>");
echo("<thead>");
echo("<tr><td>Status</td><td style='color:orange'>Drucken</td></tr>");
echo("<tr><td>Genutzt von</td><td>".$username2[0]."</td></tr>");
if(!empty($filament_color) && $filament_color!=NULL)
echo("<tr><td>Filamentfarbe</td><td >$filament_color</td></tr>");
echo("<tr><td>Erwartete Druckzeit</td><td>$print_time_total</td></tr>");
echo("<tr><td>Verbleibende Druckzeit</td><td>$print_time_left</td></tr>");
echo("<tr><td>Vergangene Druckzeit</td><td>$print_time</td></tr>");
echo("<tr><td>Datei</td><td><div class='hover-element'>".short_path($json["job"]["file"]["name"],10,10)."<div class='description'>".$json["job"]["file"]["name"]."</div></div></td></tr>");
if($userid==$_SESSION["id"] or $role[3]==="1"){
echo("<tr><td><a class='btn btn-danger' href='overview.php?cancel=$printer_id&rid=".$_SESSION["rid"]."'>Abbrechen</a></td></tr>");
}
echo("</thead>");
echo("</table>");
echo("</div>");
echo("</div>");
}
}else if($system_status==0){
//printer is free
echo("<div class='card m-4 align-self-start'>");
echo("<div class='card-body'>");
echo("<h5 class='card-title'>Drucker $printer_id</h5>");
echo("</div>");
echo("<div class='card-body'>");
echo("<iframe height='230px' scrolling='no' width='100%' src='/app/webcam.php?printer_id=$printer_id&username=".$_SESSION["username"]."&url=$url&rotation=$rotation'></iframe>");
echo("<table class='table table-borderless'>");
echo("<thead>");
echo("<tr><td>Status</td><td style='color:green'>Bereit</td></tr>");
if(!empty($filament_color) && $filament_color!=NULL)
echo("<tr><td>Filamentfarbe</td><td >$filament_color</td></tr>");
echo("<tr><td><a class='btn btn-dark' href='print.php?preselect=$printer_id'>Drucken</a></td></tr>");
echo("</thead>");
echo("</table>");
echo("</div>");
echo("</div>");
<!-- Modals -->
}else{
//printer is free but has a problem
echo("<div class='card m-4 align-self-start'>");
echo("<div class='card-body'>");
echo("<h5 class='card-title'>Drucker $printer_id</h5>");
echo("</div>");
echo("<div class='card-body'>");
echo("<iframe height='230px' scrolling='no' width='100%' src='/app/webcam.php?printer_id=$printer_id&username=".$_SESSION["username"]."&url=$url&rotation=$rotation'></iframe>");
echo("<table class='table table-borderless'>");
echo("<thead>");
echo("<tr><td>Status</td><td style='color:red'>Problem / nicht Betriebsbereit</td></tr>");
echo("</thead>");
echo("</table>");
echo("</div>");
echo("</div>");
}
$cnt--;
}
echo("</div></div>");
?>
<br><br>
<?php
test_queue($link);
?>
<!-- cancel modal -->
<div class="modal fade" id="cancel_modal" tabindex="1" role="dialog" aria-labelledby="cancel_modal" aria-hidden="false">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Druck abbrechen</h5>
</div>
<div class="modal-body">
Möchtest du den Druck wirklich abbrechen?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-bs-dismiss="modal">nicht abbrechen</button>
<a type="button" id="send_cancel_command" href="#" class="btn btn-danger">Druck abbrechen</a>
</div>
</div>
</div>
</div>
<!-- We currently do not show the queue -->
<div style="width: 100hh">
<center><h3>Warteschlange</h3></center>
<?php
$userid=$_SESSION["id"];
$cnt=0;
$filepath="";
$sql="select count(*) from queue";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $cnt);
mysqli_stmt_fetch($stmt);
//echo($cnt);
echo("<div class='container'><div class='row'><div class='col'><div class='overflow-auto'><table class='table'><thead><tr><th>Datei</th><th>Drucken auf Drucker</th><th>aus der Warteschlange entfernen</th></tr></thead><tbody>");
$last_id=0;
$form_userid=0;
$print_on=0;
while($cnt!=0)
{
$sql="select id,filepath,from_userid,print_on from queue where id>$last_id order by id";
$cancel=0;
$stmt = mysqli_prepare($link, $sql);
echo mysqli_error($link);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $queue_id,$filepath,$from_userid,$print_on);
mysqli_stmt_fetch($stmt);
$filepath=basename($filepath);
$last_id=$queue_id;
echo("<tr><td>$filepath</td>");
if($print_on==-1)
echo("<td>Erster verfügbarer Drucker</td>");
else
echo("<td>$print_on</td>");
if($_SESSION["role"][3]==="1" or $_SESSION["id"]==$from_userid)
echo("<td><form method='POST' action='?remove_queue=$queue_id&rid=".$_SESSION["rid"]."'><button type='submit' value='remove' name='remove' class='btn btn-danger'>Löschen</button></form></td></tr>");
$cnt--;
}
echo("</tbody></table></div></div></div></div>");
?>
<br><br>
</div>
<!-- class selector -->
<div class="modal fade" id="select_class" tabindex="1" role="dialog" aria-labelledby="class" aria-hidden="false">
<div class="modal-dialog" role="document">
@@ -458,7 +183,7 @@ function load_user()
</div>
<div class="modal-body">
<p>Hallo <?php echo(str_replace("."," ",str_replace("@kantiwattwil.ch","",$_SESSION["username"]))); ?> bitte wähle deine Klasse aus der Liste unten aus. <br>
Wenn deine Klasse nicht in der Liste ist, bitte deine Lehrperson deine Klasse in den Einstellungen hinzuzufügen.</p>
Wenn deine Klasse nicht in der Liste ist, bitte deine Lehrperson deine Klasse in den Einstellungen hinzuzufügen.</p>
<form action="overview.php?set_class" method="post">
<select name="class">
<?php
@@ -475,13 +200,340 @@ Wenn deine Klasse nicht in der Liste ist, bitte deine Lehrperson deine Klasse in
</select>
</div>
<div class="modal-footer">
<button type="submit" name="submit" class="btn btn-dark">Bestätigen</button>
<button type="submit" name="submit" class="btn btn-secondary">Bestätigen</button>
</div>
</div>
</form>
</div>
</div>
<script>
function update_cancel_modal(printer_id,rid){
const modal_=document.getElementById("cancel_modal");
const button=document.getElementById("send_cancel_command");
button.href="overview.php?cancel="+printer_id+"&rid="+rid;
document.getElementById("open_cancel_modal").click();
}
function fetchPrinterData() {
fetch('/api/fetch_printer_data.php')
.then(response => response.json())
.then(data => {
// Update the printer data on the page
updatePrinterData(data);
})
.catch(error => console.error('Error fetching printer data:', error));
}
function updatePrinterData(data) {
const own_id=<?php echo($_SESSION["id"]); ?>;
const cancel_all=<?php echo($_SESSION["role"][3]); ?>;
const printerContainer = document.getElementById('printer-container');
printerContainer.innerHTML = '';
const row = document.createElement('div');
row.className = 'row';
data.forEach(printer => {
const col = document.createElement('div');
col.className = 'col-md-4'; // Adjust the column size according to your needs
const printerCard = document.createElement('div');
printerCard.className = 'card m-4 align-self-start';
let printerStatus = '';
if (printer.view == 0) {
printerStatus = 'Fertig';
}else if(printer.view==1){
printerStatus = 'Drucken';
}else if(printer.view==2){
printerStatus = 'Abgebrochen';
}else if(printer.view==3){
printerStatus = 'Bereit';
}else if(printer.view==4){
printerStatus = 'Problem / Nicht betriebsbereit';
}else if(printer.view==5){
printerStatus = 'Von anderer Quelle aus gestartet';
}
if(printer.view==0 || printer.view==2){
if(own_id==printer.userid || cancel_all=="1"){
printerCard.innerHTML = `
<div class="card-body">
<h5 class="card-title">Drucker ${printer.printer_id}</h5>
</div>
<div class="card-body">
<iframe height="230px" scrolling="no" width="100%" src="/app/webcam.php?printer_id=${printer.printer_id}&username=<?php echo($username); ?>&url=${printer.url}"></iframe>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: ${printer.progress}%" aria-valuenow="${printer.progress}" aria-valuemin="0" aria-valuemax="100">${printer.progress}%</div>
</div>
<table class="table table-borderless">
<thead>
<tr><td>Status</td><td style="color: ${getColorByStatus(printer.view)}">${printerStatus}</td></tr>
<tr><td>Genutzt von</td><td>${printer.username}</td></tr>
<tr><td>Filamentfarbe</td><td>${printer.filament_color}</td></tr>
<tr><td>Erwartete Druckzeit</td><td>${printer.print_time_total}</td></tr>
<tr><td>Verbleibende Druckzeit</td><td>${printer.print_time_left}</td></tr>
<tr><td>Vergangene Druckzeit</td><td>${printer.print_time}</td></tr>
<tr><td>Datei</td><td><div class='hover-element'>${printer.file}<div class='description'>${printer.full_file}</div></div></td></tr>
</thead>
<tr><td><a class='btn btn-success' href='overview.php?free=${printer.printer_id}&rid=<?php echo($_SESSION["rid"]); ?>'>Freigeben</a></td></tr>
</table>
</div>
`;
}else{
printerCard.innerHTML = `
<div class="card-body">
<h5 class="card-title">Drucker ${printer.printer_id}</h5>
</div>
<div class="card-body">
<iframe height="230px" scrolling="no" width="100%" src="/app/webcam.php?printer_id=${printer.printer_id}&username=<?php echo($username); ?>&url=${printer.url}"></iframe>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: ${printer.progress}%" aria-valuenow="${printer.progress}" aria-valuemin="0" aria-valuemax="100">${printer.progress}%</div>
</div>
<table class="table table-borderless">
<thead>
<tr><td>Status</td><td style="color: ${getColorByStatus(printer.view)}">${printerStatus}</td></tr>
<tr><td>Genutzt von</td><td>${printer.username}</td></tr>
<tr><td>Filamentfarbe</td><td>${printer.filament_color}</td></tr>
<tr><td>Erwartete Druckzeit</td><td>${printer.print_time_total}</td></tr>
<tr><td>Verbleibende Druckzeit</td><td>${printer.print_time_left}</td></tr>
<tr><td>Vergangene Druckzeit</td><td>${printer.print_time}</td></tr>
<tr><td>Datei</td><td><div class='hover-element'>${printer.file}<div class='description'>${printer.full_file}</div></div></td></tr>
</thead>
</table>
</div>
`;
}
}else if(printer.view==1){
if(own_id==printer.userid || cancel_all=="1"){
printerCard.innerHTML = `
<div class="card-body">
<h5 class="card-title">Drucker ${printer.printer_id}</h5>
</div>
<div class="card-body">
<iframe height="230px" scrolling="no" width="100%" src="/app/webcam.php?printer_id=${printer.printer_id}&username=<?php echo($username); ?>&url=${printer.url}"></iframe>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: ${printer.progress}%" aria-valuenow="${printer.progress}" aria-valuemin="0" aria-valuemax="100">${printer.progress}%</div>
</div>
<table class="table table-borderless">
<thead>
<tr><td>Status</td><td style="color: ${getColorByStatus(printer.view)}">${printerStatus}</td></tr>
<tr><td>Genutzt von</td><td>${printer.username}</td></tr>
<tr><td>Filamentfarbe</td><td>${printer.filament_color}</td></tr>
<tr><td>Erwartete Druckzeit</td><td>${printer.print_time_total}</td></tr>
<tr><td>Verbleibende Druckzeit</td><td>${printer.print_time_left}</td></tr>
<tr><td>Vergangene Druckzeit</td><td>${printer.print_time}</td></tr>
<tr><td>Datei</td><td><div class='hover-element'>${printer.file}<div class='description'>${printer.full_file}</div></div></td></tr>
</thead>
<tr><td><button class='btn btn-danger' onclick='update_cancel_modal(${printer.printer_id},<?php echo($_SESSION["rid"]); ?>)'>Abbrechen</button></td></tr>
</table>
</div>
`;
}else{
printerCard.innerHTML = `
<div class="card-body">
<h5 class="card-title">Drucker ${printer.printer_id}</h5>
</div>
<div class="card-body">
<iframe height="230px" scrolling="no" width="100%" src="/app/webcam.php?printer_id=${printer.printer_id}&username=<?php echo($username); ?>&url=${printer.url}"></iframe>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: ${printer.progress}%" aria-valuenow="${printer.progress}" aria-valuemin="0" aria-valuemax="100">${printer.progress}%</div>
</div>
<table class="table table-borderless">
<thead>
<tr><td>Status</td><td style="color: ${getColorByStatus(printer.view)}">${printerStatus}</td></tr>
<tr><td>Genutzt von</td><td>${printer.username}</td></tr>
<tr><td>Filamentfarbe</td><td>${printer.filament_color}</td></tr>
<tr><td>Erwartete Druckzeit</td><td>${printer.print_time_total}</td></tr>
<tr><td>Verbleibende Druckzeit</td><td>${printer.print_time_left}</td></tr>
<tr><td>Vergangene Druckzeit</td><td>${printer.print_time}</td></tr>
<tr><td>Datei</td><td><div class='hover-element'>${printer.file}<div class='description'>${printer.full_file}</div></div></td></tr>
</thead>
</table>
</div>
`;
}
}else if(printer.view==3){
printerCard.innerHTML = `
<div class="card-body">
<h5 class="card-title">Drucker ${printer.printer_id}</h5>
</div>
<div class="card-body">
<iframe height="230px" scrolling="no" width="100%" src="/app/webcam.php?printer_id=${printer.printer_id}&username=<?php echo($username); ?>&url=${printer.url}"></iframe>
<table class="table table-borderless">
<thead>
<tr><td>Status</td><td style="color: ${getColorByStatus(printer.view)}">${printerStatus}</td></tr>
<tr><td>Filamentfarbe</td><td>${printer.filament_color}</td></tr>
</thead>
<tr><td><a class='btn btn-secondary' href='print.php?preselect=${printer.printer_id}'>Drucken</a></td></tr>
</table>
</div>
`;
}else if(printer.view==4){
printerCard.innerHTML = `
<div class="card-body">
<h5 class="card-title">Drucker ${printer.printer_id}</h5>
</div>
<div class="card-body">
<iframe height="230px" scrolling="no" width="100%" src="/app/webcam.php?printer_id=${printer.printer_id}&username=<?php echo($username); ?>&url=${printer.url}"></iframe>
<table class="table table-borderless">
<thead>
<tr><td>Status</td><td style="color: ${getColorByStatus(printer.view)}">${printerStatus}</td></tr>
</thead>
</table>
</div>
`;
}else if(printer.view==5){
if(cancel_all=="1"){
printerCard.innerHTML = `
<div class="card-body">
<h5 class="card-title">Drucker ${printer.printer_id}</h5>
</div>
<div class="card-body">
<iframe height="230px" scrolling="no" width="100%" src="/app/webcam.php?printer_id=${printer.printer_id}&username=<?php echo($username); ?>&url=${printer.url}"></iframe>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: ${printer.progress}%" aria-valuenow="${printer.progress}" aria-valuemin="0" aria-valuemax="100">${printer.progress}%</div>
</div>
<table class="table table-borderless">
<thead>
<tr><td>Status</td><td style="color: ${getColorByStatus(printer.view)}">${printerStatus}</td></tr>
<tr><td>Genutzt von</td><td>Externer Nutzer</td></tr>
<tr><td>Filamentfarbe</td><td>${printer.filament_color}</td></tr>
<tr><td>Erwartete Druckzeit</td><td>${printer.print_time_total}</td></tr>
<tr><td>Verbleibende Druckzeit</td><td>${printer.print_time_left}</td></tr>
<tr><td>Vergangene Druckzeit</td><td>${printer.print_time}</td></tr>
<tr><td>Datei</td><td><div class='hover-element'>${printer.file}<div class='description'>${printer.full_file}</div></div></td></tr>
</thead>
<tr><td><a class='btn btn-success' href='overview.php?free=${printer.printer_id}&rid=<?php echo($_SESSION["rid"]); ?>'>Freigeben</a></td></tr>
</table>
</div>
`;
}else{
printerCard.innerHTML = `
<div class="card-body">
<h5 class="card-title">Drucker ${printer.printer_id}</h5>
</div>
<div class="card-body">
<iframe height="230px" scrolling="no" width="100%" src="/app/webcam.php?printer_id=${printer.printer_id}&username=<?php echo($username); ?>&url=${printer.url}"></iframe>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: ${printer.progress}%" aria-valuenow="${printer.progress}" aria-valuemin="0" aria-valuemax="100">${printer.progress}%</div>
</div>
<table class="table table-borderless">
<thead>
<tr><td>Status</td><td style="color: ${getColorByStatus(printer.view)}">${printerStatus}</td></tr>
<tr><td>Genutzt von</td><td>Externer Nutzer</td></tr>
<tr><td>Filamentfarbe</td><td>${printer.filament_color}</td></tr>
<tr><td>Erwartete Druckzeit</td><td>${printer.print_time_total}</td></tr>
<tr><td>Verbleibende Druckzeit</td><td>${printer.print_time_left}</td></tr>
<tr><td>Vergangene Druckzeit</td><td>${printer.print_time}</td></tr>
<tr><td>Datei</td><td><div class='hover-element'>${printer.file}<div class='description'>${printer.full_file}</div></div></td></tr>
</thead>
</table>
</div>
`;
}
}
col.appendChild(printerCard);
row.appendChild(col);
});
printerContainer.appendChild(row);
}
function getColorByStatus(status) {
switch (status) {
case 0:
return 'green';
case 1:
return 'orange';
case 2:
return 'orange';
case 3:
return 'green';
case 4:
return 'red';
case 5:
return 'orange';
}
}
document.addEventListener('DOMContentLoaded', () => {
fetchPrinterData();
setInterval(fetchPrinterData, 60000); // Refresh every 6 seconds
});
</script>
<center><h3>Warteschlange</h3></center>
<?php
$userid = $_SESSION["id"];
$cnt = 0;
$sql = "SELECT COUNT(*) FROM queue";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $cnt);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
$last_id = 0;
echo "<div class='container'><div class='row'><div class='col'><div class='overflow-auto'>
<table class='table'>
<thead>
<tr>
<th>Datei</th>
<th>Drucken auf Drucker</th>
<th>Auftrag von</th>
<th>Aus der Warteschlange entfernen</th>
</tr>
</thead>
<tbody>";
while ($cnt > 0) {
$sql = "SELECT q.id, q.filepath, q.from_userid, q.print_on, u.username
FROM queue q
JOIN users u ON q.from_userid = u.id
WHERE q.id > ?
ORDER BY q.id LIMIT 1";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, "i", $last_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $queue_id, $filepath, $from_userid, $print_on, $from_user);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
if (!$queue_id) break; // Exit if no more entries
$filepath = basename($filepath);
$last_id = $queue_id;
echo "<tr>
<td>{$filepath}</td>
<td>" . ($print_on == -1 ? "Erster verfügbarer Drucker" : htmlspecialchars($print_on)) . "</td>
<td>{$from_user}</td>";
if ($_SESSION["role"][3] === "1" || $_SESSION["id"] == $from_userid) {
echo "<td>
<form method='POST' action='?remove_queue={$queue_id}&rid={$_SESSION["rid"]}'>
<button type='submit' name='remove' class='btn btn-danger'>Löschen</button>
</form>
</td>";
}
echo "</tr>";
$cnt--;
}
echo "</tbody></table></div></div></div></div>";
?>
<?php
if($_SESSION["class_id"]==""){
echo("<script>");
echo("var modal = document.getElementById('select_class');");
@@ -492,7 +544,6 @@ Wenn deine Klasse nicht in der Liste ist, bitte deine Lehrperson deine Klasse in
echo("</script>");
}
?>
<div id="footer"></div>
<div id="footer"></div>
</body>
</html>

View File

@@ -1,80 +1,21 @@
<?php
function extract_param($gcode) {
// Match the pattern S followed by digits, capturing the digits
$matches = [];
$pattern = '/[S|T]([0-9]+)/';
if (preg_match($pattern, $gcode, $matches)) {
return (int)$matches[1]; // Return the first capture group as an integer
} else {
return false; // No match found
}
}
function check_file($path){//check file for temperature which are to high
$file = fopen($path, 'r');
$cnt=0;
while (!feof($file)&&$cnt!=2) {
$line = fgets($file);
// Extract parameter from lines with specific commands
if (strpos($line, 'M104') !== false || strpos($line, 'M140') !== false) {
$cnt++;
$parameter = extract_param($line);
if(strpos($line, 'M104') !== false){ //extruder_temp
$ex_temp=$parameter;
}
if(strpos($line, 'M140') !== false){ //bed temp
$bed_temp=$parameter;
}
}
}
//echo("bed:$bed_temp;ex:$ex_temp");
if($bed_temp>75 or $ex_temp>225){
return 0;
}else{
return 1;
}
}
function is_time_between($startTime, $endTime, $checkTime) {
// Convert times to timestamps
$startTimestamp = strtotime($startTime);
$endTimestamp = strtotime($endTime);
$checkTimestamp = strtotime($checkTime);
// If end time is less than start time, it means the range crosses midnight
if ($endTimestamp < $startTimestamp) {
// Check if the time is between start time and midnight or between midnight and end time
return ($checkTimestamp >= $startTimestamp || $checkTimestamp <= $endTimestamp);
} else {
// Normal case: check if the time is between start and end time
return ($checkTimestamp >= $startTimestamp && $checkTimestamp <= $endTimestamp);
}
}
?>
<!DOCTYPE html>
<html>
<?php
// Initialize the session
$warning=false;
//auth stuff
session_start();
include "../config/config.php";
require_once "../log/log.php";
include "../api/queue.php";
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
header("location: /login/login.php");
exit;
}
$username=htmlspecialchars($_SESSION["username"]);
?>
<?php
$color=$_SESSION["color"];
$class=$_SESSION["class_id"];
include "../assets/components.php";
?>
?>
<!DOCTYPE html>
<html lang="de" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>System0 - Print</title>
<?php include "../assets/components.php"; ?>
</head>
<body>
<script src="/assets/js/load_page.js"></script>
<script>
function load_user()
@@ -87,459 +28,402 @@ function is_time_between($startTime, $endTime, $checkTime) {
});
}
</script>
<script type='text/javascript' >load_user()</script>
<?php
$role=$_SESSION["role"];
echo "<script type='text/javascript' >load_user()</script>";
test_queue($link);
if(isset($_GET["cloudprint"])){
echo("<script>let cloudprint=1;</script>");
echo '<script>fetch("/api/uploader/image_preview.php?file='.$_GET["cloudprint"].'&pc='.isset($_GET["pc"]).'").then(res => res.text()).then(data => document.getElementById("preview").src = "data:image/png;base64," + data).catch(err => console.error("Error:", err));</script>';
}else{
echo("<script>let cloudprint=0;</script>");
}
?>
<?php $userid=$_SESSION["id"]; ?>
<?php echo(" <body style='background-color:$color'> ");?>
<!-- navbar -->
<div id="content"></div>
<head>
<title>Datei drucken</title>
</head>
<body>
<br><br>
<!-- div where all our content goes -->
<div style="min-height:95vh">
<!-- we need to show a file upload thing and offer the selectnio of printers -->
<div class="container mt-5 d-flex justify-content-center">
<form>
<div class="mb-3">
<label for="fileUpload" class="form-label">3D-Druck Datei</label>
<?php
if(isset($_POST["printer"]))
{
$status=0;
$free=0;
$url="";
$apikey="";
$printer_url="";
$printer_id=htmlspecialchars($_POST["printer"]);
if($printer_id=="queue")
{
//send file to queue because no printer is ready!
if(!empty($_FILES['file_upload']))
{
$ok_ft=array("gcode","");
$unwanted_chr=[' ','(',')','/','\\','<','>',':',';','?','*','"','|','%'];
$filetype = strtolower(pathinfo($_FILES['file_upload']['name'],PATHINFO_EXTENSION));
$path = "/var/www/html/user_files/$username/";
$print_on=$_POST["queue_printer"];
$filename=basename( $_FILES['file_upload']['name']);
$filename=str_replace($unwanted_chr,"_",$filename);
$path = $path . $filename;
if(!in_array($filetype,$ok_ft))
{
echo("<center><div style='width:50%' class='alert alert-danger' role='alert'>Dieser Dateityp wird nicht unterstüzt.</div></center>");
sys0_log("Could not upload file for ".$_SESSION["username"]." because of unknown file extension",$_SESSION["username"],"PRINT::UPLOAD::FILE::FAILED");//notes,username,type
}
else
{
if(move_uploaded_file($_FILES['file_upload']['tmp_name'], $path)) {
$sql="INSERT INTO queue (from_userid,filepath,print_on) VALUES (?,?,?)";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, "isi", $userid,$path,$print_on);
mysqli_stmt_execute($stmt);
echo("<center><div style='width:50%' class='alert alert-success' role='alert'>Datei ". basename( $_FILES['file_upload']['name']). " wurde hochgeladen und an die Warteschlange gesendet</div></center>");
sys0_log("user ".$_SESSION["username"]." uploaded ".basename($path)." to the queue",$_SESSION["username"],"PRINT::UPLOAD::QUEUE");//notes,username,type
}
else
{
echo("<center><div style='width:50%' class='alert alert-danger' role='alert'>Datei ". basename( $_FILES['file_upload']['name']). " konnte hochgeladen werden</div></center>");
}
}
unset($_FILES['file']);
}
if(isset($_GET["cloudprint"])){
$print_on=$_POST["queue_printer"];
if(!isset($_GET["pc"]))
$path = "/var/www/html/user_files/$username/".$_GET["cloudprint"];
else
$path = "/var/www/html/user_files/public/".$_GET["cloudprint"];
$sql="INSERT INTO queue (from_userid,filepath,print_on) VALUES (?,?,?)";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, "isi", $userid,$path,$print_on);
mysqli_stmt_execute($stmt);
echo("<center><div style='width:50%' class='alert alert-success' role='alert'>Datei ". basename( $_FILES['file_upload']['name']). " wurde hochgeladen und an die Warteschlange gesendet</div></center>");
sys0_log("user ".$_SESSION["username"]." uploaded ".basename($path)." to the queue",$_SESSION["username"],"PRINT::UPLOAD::QUEUE");
}
}
else
{
$sql="select printer_url, free, system_status,apikey,printer_url from printer where id=$printer_id";
//echo $sql;
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $url,$free,$status,$apikey,$printer_url);
mysqli_stmt_fetch($stmt);
if($free!=1 or $status!=0)
{
echo("<center><div style='width:50%' class='alert alert-danger' role='alert'>Der Drucker ist zur Zeit nicht verfügbar. Warte einen Moment oder versuche es mit einem anderen Drucker erneut.</div></center>");
sys0_log("Could not start job for ".$_SESSION["username"]." with file ".basename($path)."",$_SESSION["username"],"PRINT::JOB::START::FAILED");//notes,username,type
exit;
}
if(!empty($_FILES['file_upload']))
{
$ok_ft=array("gcode","");
$unwanted_chr=[' ','(',')','/','\\','<','>',':',';','?','*','"','|','%'];
$filetype = strtolower(pathinfo($_FILES['file_upload']['name'],PATHINFO_EXTENSION));
$path = "/var/www/html/user_files/$username/";
$filename=basename( $_FILES['file_upload']['name']);
$filename=str_replace($unwanted_chr,"_",$filename);
$path = $path . $filename;
//if(in_array($filetype,$unwanted_ft))
if(!in_array($filetype,$ok_ft))
{
echo("<center><div style='width:50%' class='alert alert-danger' role='alert'>Dieser Dateityp wird nicht unterstüzt.</div></center>");
sys0_log("Could not upload file for ".$_SESSION["username"]." because of unknown file extension",$_SESSION["username"],"PRINT::UPLOAD::FILE::FAILED");//notes,username,type
}
else
{
//check if print key is valid:
$print_key=htmlspecialchars($_POST["print_key"]);
$sql="SELECT id from print_key where print_key='$print_key'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
//if(mysqli_stmt_num_rows($stmt) == 1){ turned off because user does not need to have a printer key
if(true){
mysqli_stmt_close($stmt);
if(move_uploaded_file($_FILES['file_upload']['tmp_name'], $path)) {
echo("<center><div style='width:50%' class='alert alert-success' role='alert'>Erfolg! Die Datei ". basename( $_FILES['file_upload']['name']). " wurde hochgeladen.</div></center>");
echo("<center><div style='width:50%' class='alert alert-success' role='alert'>Datei wird an den 3D-Drucker gesendet...</div></center>");
if(check_file($path) or isset($_POST["ignore_unsafe"])){
exec('curl -k -H "X-Api-Key: '.$apikey.'" -F "select=true" -F "print=true" -F "file=@'.$path.'" "'.$printer_url.'/api/files/local" > /var/www/html/user_files/'.$username.'/json.json');
//file is on printer and ready to be printed
$userid=$_SESSION["id"];
echo("<center><div style='width:50%' class='alert alert-success' role='alert'>Datei gesendet und Auftrag wurde gestartet.</div></center>");
sys0_log("user ".$_SESSION["username"]." uploaded ".basename($path)." to printer ".$_POST["printer"]."",$_SESSION["username"],"PRINT::UPLOAD::PRINTER");//notes,username,type
$fg=file_get_contents("/var/www/html/user_files/$username/json.json");
$json=json_decode($fg,true);
if($json['effectivePrint']==false or $json["effectiveSelect"]==false)
{
echo("<center><div style='width:50%' class='alert alert-danger' role='alert'>Ein Fehler ist aufgetreten und der Vorgang konnte nicht gestartet werden. Warte einen Moment und versuche es dann erneut.</div></center>");
sys0_log("Could not start job for ".$_SESSION["username"]."with file ".basename($path)."",$_SESSION["username"],"PRINT::JOB::START::FAILED");//notes,username,type
}
else
{
$sql="update printer set free=0, printing=1,mail_sent=0, used_by_userid=$userid where id=$printer_id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
//delete printer key:
$sql="DELETE from print_key where print_key='$print_key'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
echo('<input type="text" value="'.$_GET["cloudprint"].'" class="form-control" disabled id="file_upload">');
}else{
$warning=true;
echo("<center><div style='width:50%' class='alert alert-danger' role='alert'>Achtung, deine Bett oder Extruder Temperatur ist sehr hoch eingestellt. Dies wird zur zerstörung des Druckes und somit zu Müll führen. Bitte setze diese Temperaturen tiefer in den Einstellungen deines Slicers.</div></center>");
}
}
else
{
echo("<center><div style='width:50%' class='alert alert-danger' role='alert'>Ein Fehler beim Uploaden der Datei ist aufgetreten! Versuche es erneut! </div></center>");
}
}
else{
echo("<center><div style='width:50%' class='alert alert-danger' role='alert'>Der Druckschlüssel ist nicht gültig. Evtl. wurde er bereits benutzt. Versuche es erneut! </div></center>");
}
}
unset($_FILES['file']);
echo('<input type="file" class="form-control" accept=".gcode" id="file_upload">');
}
?>
</div>
<?php
if(isset($_GET["cloudprint"])){
if(!isset($_GET["pc"]))
$path = "/var/www/html/user_files/$username/".$_GET["cloudprint"];
else
$path = "/var/www/html/user_files/public/".$_GET["cloudprint"];
//check if print key is valid:
$print_key=htmlspecialchars($_POST["print_key"]);
$sql="SELECT id from print_key where print_key='$print_key'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
//if(mysqli_stmt_num_rows($stmt) == 1){ turned off because user does not need to have a printer key
if(true){
mysqli_stmt_close($stmt);
echo("<center><div style='width:50%' class='alert alert-success' role='alert'>Datei wird an den 3D-Drucker gesendet...</div></center>");
if(check_file($path) or isset($_POST["ignore_unsafe"])){
exec('curl -k -H "X-Api-Key: '.$apikey.'" -F "select=true" -F "print=true" -F "file=@'.$path.'" "'.$printer_url.'/api/files/local" > /var/www/html/user_files/'.$username.'/json.json');
//file is on printer and ready to be printed
$userid=$_SESSION["id"];
echo("<center><div style='width:50%' class='alert alert-success' role='alert'>Datei gesendet und Auftrag wurde gestartet.</div></center>");
sys0_log("user ".$_SESSION["username"]." uploaded ".basename($path)." to printer ".$_POST["printer"]."",$_SESSION["username"],"PRINT::UPLOAD::PRINTER");//notes,username,type
$fg=file_get_contents("/var/www/html/user_files/$username/json.json");
$json=json_decode($fg,true);
//echo('curl -k -H "X-Api-Key: '.$apikey.'" -F "select=true" -F "print=true" -F "file=@'.$path.'" "'.$printer_url.'/api/files/local" > /var/www/html/system0/html/user_files/'.$username.'/json.json');
//echo("<br><br><br>");
//var_dump($json);
if($json['effectivePrint']==false or $json["effectiveSelect"]==false)
{
echo("<center><div style='width:50%' class='alert alert-danger' role='alert'>Ein Fehler ist aufgetreten und der Vorgang konnte nicht gestartet werden. Warte einen Moment und versuche es dann erneut.</div></center>");
sys0_log("Could not start job for ".$_SESSION["username"]."with file ".basename($path)."",$_SESSION["username"],"PRINT::JOB::START::FAILED");//notes,username,type
}
else
{
$sql="update printer set free=0, printing=1,mail_sent=0, used_by_userid=$userid where id=$printer_id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
//delete printer key:
$sql="DELETE from print_key where print_key='$print_key'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
}else{
$warning=true;
echo("<center><div style='width:50%' class='alert alert-danger' role='alert'>Achtung, deinen Bett oder Extruder Temperatur ist sehr hoch eingestellt. Dies wird zur zerstörung des Druckes und somit zu Müll führen. Bitte setze diese Temperaturen tiefer in den Einstellungen deines Slicers.</div></center>");
}
}
else{
echo("<center><div style='width:50%' class='alert alert-danger' role='alert'>Der Druckschlüssel ist nicht gültig. Evtl. wurde er bereits benutzt. Versuche es erneut! </div></center>");
}
}
}
}
?>
<div class="text-center mt-5" style="min-height: 95vh">
<h1>Datei drucken</h1>
<!-- Reservations notice -->
<?php
date_default_timezone_set('Europe/Zurich');
$reservation_conflict=false;
$today=date("Y-m-d");
$sql="select time_from, time_to, for_class from reservations where day='$today';";
$stmt = $link->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
//$row = $result->fetch_assoc();
$time_now=date("H:i");
while ($row = $result->fetch_assoc()) {
if (is_time_between($row["time_from"], $row["time_to"], $time_now)) {
$reservation_conflict = true;
$for_class[]=$row["for_class"];
//break;
}
}
if(!isset($for_class))
$for_class[]=0;
if ($reservation_conflict && !in_array($class,$for_class) && $class!=0) {
echo "<center><div style='width:50%' class='alert alert-danger' role='alert'>Die Drucker sind zurzeit reserviert! Bitte versuche es später erneut!</div></center>";
$block=true;
}else{
$block=false;
}
?>
<div class="container d-flex align-items-center justify-content-center" >
<form class="mt-5" enctype="multipart/form-data" method="POST" action="">
<?php if(!isset($_GET["cloudprint"])){
echo ('<div class="form-group">');
echo('<div class="custom-file">');
echo('<label for="file_upload" class="form-label">Zu druckende Datei</label>');
echo('<input type="file" class="form-control" type="file" name="file_upload" required accept=".gcode"> ');
echo('</div>');
echo('</div>');
}
else{
echo ('<div class="form-group">');
echo('<div class="custom-file">');
echo("<p>Cloudfile: ".$_GET["cloudprint"]."</p>");
echo('</div>');
echo('</div>');
}
?>
<br><br>
<div class="form-group">
<label class="my-3" for="printer">Druckerauswahl</label>
<select class="form-control selector" name="printer" required>
<!-- PHP to retrieve printers -->
<?php
//get number of printers
$num_of_printers=0;
$sql="select count(*) from printer where free=1 and system_status=0";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $num_of_printers);
mysqli_stmt_fetch($stmt);
$last_id=0;
$printers_av=0;
if(isset($_GET["preselect"])){
$preselect=$_GET["preselect"];
}else{
$preselect=1;
}
if(!isset($_GET["send_to_queue"])){
while($num_of_printers!=0)
{
$id=0;
$sql="Select id,color from printer where id>$last_id and free=1 and system_status=0 order by id";
//echo $sql;
$color="";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $id,$color);
mysqli_stmt_fetch($stmt);
$color=intval($color);
//get the real color
$sql="select name from filament where internal_id=$color";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt,$color);
mysqli_stmt_fetch($stmt);
if($id!=0 && $id!=$last_id)
{
if($id==$preselect)
echo("<option printer='$id' value='$id' selected>Printer $id - $color</option>");
else
echo("<option printer='$id' value='$id'>Printer $id - $color</option>");
$printers_av++;
}
$last_id=$id;
$num_of_printers--;
}
}
if($printers_av==0 or isset($_GET["send_to_queue"])){
echo("<option printer='queue' value='queue'>an Warteschlange senden</option>");
echo('<center><img style="display:block; width:100%" id="preview"/></center>');
}
?>
<div class="mb-3">
<label for="selectOption" class="form-label">Drucker</label>
<select class="form-select" id="selectOption">
<option selected value="not_set">Bitte wähle einen Drucker</option>
</select>
</div>
<!-- if we send to queue, the user should be able to choose which printer prints it afterwards -->
<?php
if($printers_av==0 or isset($_GET["send_to_queue"])){
echo('<div class="form-group">');
echo('<label class="my-3" for="printer">Auf diesem Drucker wird deine Datei gedruckt, sobald er frei ist.</label>');
echo('<select class="form-control selector" name="queue_printer" required>');
//get number of printers
$num_of_printers=0;
$sql="select count(*) from printer where system_status=0";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $num_of_printers);
mysqli_stmt_fetch($stmt);
$last_id=0;
$printers_av=0;
if(isset($_GET["preselect"])){
$preselect=$_GET["preselect"];
}else{
$preselect=-1;
}
echo("<option printer='-1' value='-1' selected selected>erster verfügbarer Drucker</option>");
while($num_of_printers!=0)
{
$id=0;
$sql="Select id,color from printer where id>$last_id and system_status=0 order by id";
//echo $sql;
$color="";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $id,$color);
mysqli_stmt_fetch($stmt);
$color=intval($color);
//get the real color
$sql="select name from filament where internal_id=$color";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt,$color);
mysqli_stmt_fetch($stmt);
if($id!=0 && $id!=$last_id)
{
if($id==$preselect)
echo("<option printer='$id' value='$id' selected>Drucker $id - $color</option>");
else
echo("<option printer='$id' value='$id'>Drucker $id - $color</option>");
$printers_av++;
}
$last_id=$id;
$num_of_printers--;
}
echo('</select>');
echo('</div>');
}
?>
<br><br>
<!--<label class="my-3" for="print_key">Druckschlüssel (Kann im Sekretariat gekauft werden)</label>
<input type="text" class="form-control text" id="print_key" name="print_key" placeholder="z.B. A3Rg4Hujkief"><br>-->
<?php
if($warning==true){
echo("<input type='checkbox' id='ignore_unsafe' name='ignore_unsafe' value='true'>");
echo("<label for='ignore_unsafe'>Temperaturbeschränkungen Ignorieren und Drucken</label><br>");
}
?>
<?php
if($block==false){
echo('<input type="submit" class="btn btn-dark mb-5" value="Datei drucken" onclick="show_loader();" id="button">');
echo('<div class="d-flex align-items-center">');
echo('<strong role="status" style="display:none" id="spinner">Hochladen...</strong>');
echo('<div class="spinner-border ms-auto" aria-hidden="true" style="display:none" id="spinner2"></div>');
echo('</div>');
}else{
echo "<center><div style='width:50%' class='alert alert-danger' role='alert'>Die Drucker sind zurzeit reserviert! Bitte versuche es später erneut!</div></center>";
}
?>
<?php
if($block==false){
if(isset($_GET["send_to_queue"])){
echo('<center><a href="print.php">Nur freie Drucker anzeigen.</a></center>');
}else{
echo(' <center><a href="print.php?send_to_queue">Auf einem Drucker Drucken, welcher besetzt ist.</a></center>');
}
}
?>
<a style="cursor: pointer" onclick="start_upload(1)" class="btn btn-secondary">Drucken</a>
</form>
</div>
</div>
<br>
<!-- footer -->
<div id="footer"></div>
<script>
function show_loader(){
var spinner=document.getElementById("spinner");
spinner.style.display="block";
var spinner=document.getElementById("spinner2");
spinner.style.display="block";
var spinner=document.getElementById("button");
spinner.style.display="none";
<script>
let global_error="";
//js to handle backend requests
//load printers
document.addEventListener("DOMContentLoaded", function () {
const selectElement = document.getElementById("selectOption");
const apiUrl = "/api/uploader/fetch_printers.php"; // Replace with your actual API URL
function getUrlParam(name) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(name);
}
</script>
</body>
const preselectId = getUrlParam("preselect"); // Get "preselect" value from URL
fetch(apiUrl)
.then(response => response.json())
.then(data => {
data.forEach(item => {
const option = document.createElement("option");
option.value = item.id;
if(item.error_status==0){
if(item.free==1){
option.textContent = `Drucker ${item.id} - ${item.color}`;
if(preselectId==null){
option.selected="true";
}
}else{
option.textContent = `Drucker ${item.id} - ${item.color} - Warteschlange`;
}
if (item.id == preselectId) {
option.selected = true;
}
selectElement.appendChild(option);
}
});
})
.catch(error => console.error("Error fetching data:", error));
});
async function reload_printer_selection(){
document.getElementById("selectOption").innerHTML = "";
const selectElement = document.getElementById("selectOption");
const apiUrl = "/api/uploader/fetch_printers.php"; // Replace with your actual API URL
function getUrlParam(name) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(name);
}
const preselectId = getUrlParam("preselect"); // Get "preselect" value from URL
const option_1 = document.createElement("option");
option_1.value = "not_set";
option_1.textContent = "Bitte wähle einen Drucker";
selectElement.appendChild(option_1);
fetch(apiUrl)
.then(response => response.json())
.then(data => {
data.forEach(item => {
const option = document.createElement("option");
option.value = item.id;
if(item.error_status==0){
if(item.free==1){
option.textContent = `Drucker ${item.id} - ${item.color}`;
if(preselectId==null){
option.selected="true";
}
}else{
option.textContent = `Drucker ${item.id} - ${item.color} - Warteschlange`;
}
if (item.id == preselectId) {
option.selected = true;
}
selectElement.appendChild(option);
}
});
})
.catch(error => console.error("Error fetching data:", error));
}
async function start_upload(use_checks){
document.getElementById("close_progress_modal2").click();
//main function handles the steps from user pressing upload button via checking params to starting job via api
//we have a modal that shows progress to the user
document.getElementById("close_progress_modal").style.display = "none";
document.getElementById("close_progress_modal2").style.display = "none";
let steps = [
"Initialisierung",
"Datei auf System0 Hochladen",
"Nach Reservationskonflikten suchen",
"Nach Invaliden Druckeinstellungen suchen",
"Job an Drucker senden"
];
let progressContent = document.getElementById("progressContent");
progressContent.innerHTML = ""; // Clear previous content
let modal = new bootstrap.Modal(document.getElementById("progressModal"));
modal.show();
add_step(0,progressContent,steps);
//initialising => set all vars to 0 etc
finish_step(0,progressContent,steps);
if(cloudprint==0){
add_step(1,progressContent,steps);
//upload file to system0
if(await upload_file()==0){
finish_step(1,progressContent,steps);
}else{
add_error("Fehler beim Upload der Datei - "+global_error,progressContent);
cancel_step(1,progressContent,steps);
show_close_button();
return;
}
}else{
//just tell the server what the file is.
await fetch("/api/uploader/cloudprint.php?file=<?php echo($_GET['cloudprint']); ?>&pc=<?php echo(isset($_GET['pc'])); ?>");
}
global_error="";
//check if there is a reservation ongoing during this print
add_step(2,progressContent,steps);
let status=await check_reservations();
if(status==0){
finish_step(2,progressContent,steps);
}else if(status==1){
//reserved and user is student
add_error("Die Drucker sind zurzeit reserviert. Bitte versuche es später erneut.", progressContent);
cancel_step(2,progressContent,steps);
show_close_button();
return;
}else if(status==2){
//reserved but user is admin
add_warning("Die Drucker sind Zurzeit reserviert. Als Lehrperson wird ihr Druck allerdings trozdem gedruckt. Bitte gehen Sie sicher, dass nicht eine Klasse beeinträchtigt wird.",progressContent);
finish_step(2,progressContent,steps);
}else{
add_error("Fehler beim überprüfen der Reservationen - "+global_error,progressContent);
cancel_step(2,progressContent,steps);
show_close_button();
return;
}
global_error="";
//search for invalid print settings.
add_step(3,progressContent,steps);
status=await check_illegal_settings(progressContent);
if(status==0){
finish_step(3,progressContent,steps);
}else if(use_checks==0){
add_warning("Warnung: Dieser Druck wird mit sehr hohen Temparaturen gedruckt. Dies kann zur zerstörung des Druckers führen!",progressContent);
finish_step(3,progressContent,steps);
}else if(status==1){
add_error("Achtung deine Drucktemparatur ist sehr hoch eingestellt. Dies kann zur zerstörung des Druckers führen! Bitte fahre nur fort, wenn du dir sicher bist, was du tust!",progressContent);
add_circumvent_link(progressContent);
cancel_step(3,progressContent,steps);
show_close_button();
return;
}else{
add_error("Fehler beim prüfen der Druckeinstellungen",progressContent);
cancel_step(3,progressContent,steps);
show_close_button();
return;
}
global_error="";
//send to printer
add_step(4,progressContent,steps);
status=await start_job();
if(status==0){
finish_step(4,progressContent,steps);
//add_step(5,progressContent,steps);
//finish_step(5,progressContent,steps);
add_success("Job erfolgreich gestartet",progressContent);
}else if(status==2){
finish_step(4,progressContent,steps);
//add_step(5,progressContent,steps);
//finish_step(5,progressContent,steps);
add_success("Job erfolgreich an Warteschlange gesendet",progressContent);
}else{
add_error("Fehler beim starten des Jobs. "+global_error, progressContent);
cancel_step(4,progressContent,steps);
show_close_button();
return;
}
show_close_button();
reload_printer_selection();
}
function add_circumvent_link(progressContent) {
let stepHtml = `
<div>
<a onclick="start_upload(0);" style="cursor:pointer" target="_blank" class="step-link">Drücke hier, um alle überprüfungen zu umgehen</a>
</div>
`;
progressContent.innerHTML += stepHtml;
}
function finish_step(index,progressContent,steps){
let stepId = "step-" + index;
let stepElement = document.getElementById(stepId);
if (stepElement) {
stepElement.innerHTML = `
<span class="text-success fw-bold">✅</span>
<span>${steps[index]}</span>
`;
}
if (index >= steps.length-1){
document.getElementById("close_progress_modal").style.display = "block";
document.getElementById("close_progress_modal2").style.display = "block";
}
}
function show_close_button(){
document.getElementById("close_progress_modal").style.display = "block";
document.getElementById("close_progress_modal2").style.display = "block";
}
function cancel_step(index,progressContent,steps){
let stepId = "step-" + index;
let stepElement = document.getElementById(stepId);
if (stepElement) {
stepElement.innerHTML = `
<span class="text-success fw-bold">🆘</span>
<span>${steps[index]}</span>
`;
}
document.getElementById("close_progress_modal").style.display = "block";
document.getElementById("close_progress_modal2").style.display = "block";
}
function add_error(msg,progressContent){
let errorHtml = `
<br>
<div class='alert alert-danger' role='alert'>Fehler - ${msg}</div>
`;
progressContent.innerHTML += errorHtml;
}
function add_success(msg,progressContent){
let errorHtml = `
<br>
<div class='alert alert-success' role='alert'>Erfolg - ${msg}</div>
`;
progressContent.innerHTML += errorHtml;
}
function add_warning(msg,progressContent){
let errorHtml = `
<br>
<div class='alert alert-warning' role='alert'>Warnung - ${msg}</div>
`;
progressContent.innerHTML += errorHtml;
}
function add_step(index,progressContent,steps) {
let stepId = "step-" + index;
let stepHtml = `
<div class="step-container" id="${stepId}">
<span class="spinner-border text-primary" role="status"></span>
<span>${steps[index]}</span>
</div>
`;
progressContent.innerHTML += stepHtml;
}
async function check_illegal_settings(progressContent){
try {
const response = await fetch("/api/uploader/check_illegal_settings.php");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
if(data["status"]!=0){
global_error="Dieser Fehler ist auf dem Drucker. Warte einige Minuten und versuche es erneut.";
}
return data["status"];
} catch (error) {
return 4;
}
}
async function start_job(){
let printer_id=document.getElementById("selectOption").value;
if(printer_id=="not_set"){
global_error="Kein Drucker ausgewählt";
return 5;
}
try {
const response = await fetch("/api/uploader/start_job.php?printer="+printer_id);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data["status"];
} catch (error) {
return 5;
}
}
async function upload_file(){
const fileInput = document.getElementById('file_upload');
const file = fileInput.files[0];
if (!file) {
global_error="Keine Datei ausgewählt";
return 1;
}
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('/api/uploader/upload_file.php', {
method: 'POST',
body: formData,
});
if (response.ok) {
const result = await response.json();
if(result.status=="error"){
global_error=result.message;
return 1;
}
} else {
return 1;
}
} catch (error) {
return 1;
}
return 0;
}
async function check_reservations() {
try {
const response = await fetch("/api/uploader/check_reservations.php");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data["status"];
} catch (error) {
return 4;
}
}
</script>
<!-- progress modal -->
<div class="modal fade" id="progressModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" role="dialog" aria-labelledby="progressModalLabel" aria-hidden="false">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="progressModalLabel">Fortschritt</h5>
<button id="close_progress_modal" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schliessen"></button>
</div>
<div class="modal-body">
<div id="progressContent"></div>
</div>
<div class="modal-footer">
<button id="close_progress_modal2" type="button" class="btn btn-secondary" data-bs-dismiss="modal">Schliessen</button>
</div>
</div>
</div>
</div>
</body>
</html>

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html>
<html data-bs-theme="dark">
<?php
// Initialize the session
session_start();
@@ -76,7 +76,7 @@ function load_user()
<div class="container">
<form action="public_cloud.php" method="POST">
<input type="text" name="search" placeholder="Suchbegriff">
<button type="submit" class="btn btn-dark my-5">Suchen</button>
<button type="submit" class="btn btn-secondary my-5">Suchen</button>
</form>
<div style="overflow-y:auto;overflow-x:auto">
<table class="table">

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html>
<html data-bs-theme="dark">
<?php
// Initialize the session
session_start();

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html>
<html data-bs-theme="dark">
<?php
// Initialize the session
session_start();

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="en">
<html lang="en" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html>
<html data-bs-theme="dark">
<?php
$username = htmlspecialchars($_GET["username"]);
$printer_url = $_GET["url"];
@@ -7,6 +7,9 @@
?>
<head>
<title>Webcam</title>
<?php
include "../assets/webcam_components.php";
?>
</head>
<body>
<!-- Display the first image -->
@@ -34,7 +37,8 @@
};
xhr.send(); // Execute the request
}
//do first load
loadAndSwapImage();
// Reload the image every 5 seconds
setInterval(loadAndSwapImage, 5000);
</script>

View File

@@ -1,10 +1,10 @@
<?php
echo('<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" >
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" ></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/8ab5a73cf2.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/c4deda69dc.js" crossorigin="anonymous"></script>
');
?>

View File

@@ -72,7 +72,7 @@
<hr>
<div class="text-center p-3">
<p class="text-white">&copy; 2024 Copyright: <a href="https://jakach.duckdns.org" class="text-white">Jakach</a></p>
<p class="text-white">&copy; 2024 Copyright: <a href="https://www.jakach.ch" class="text-white">Jakach</a></p>
</div>
</footer>
</body>

View File

@@ -113,25 +113,37 @@
session_start();
echo('
<div class="card m-2" style="width: 14em;" href="#">
<br>
<div class="d-flex justify-content-center align-items-center card-img-top" style="height:auto;margin-top:20px">
<i class="fa-solid fa-lock fa-6x justify-content-center"></i>
<i class="fa-solid fa-lock fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<h5 class="card-title">Passwort zurücksetzen</h5>
<h5 class="card-title">Jakach account verknüpfen / Passwort zurücksetzen</h5>
<p class="card-text">Hier kannst du dein Passwort ändern</p>
<a href="/login/reset-password.php" class="stretched-link"></a>
</div>
</div>
');
echo('
<div class="card m-2" style="width: 14em;" href="#">
<div class="d-flex justify-content-center align-items-center card-img-top" style="height:auto;margin-top:20px">
<i class="fa-solid fa-server fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<h5 class="card-title">Systemstatus</h5>
<p class="card-text">Hier kannst du den Systemstatus unserer Server einsehen</p>
<a href="https://stats.uptimerobot.com/4nr4WTYQVy" class="stretched-link"></a>
</div>
</div>
');
if($_SESSION["role"][5]==="1")
echo('
<div class="card m-2" style="width: 14em;" href="#">
<div class="d-flex justify-content-center align-items-center card-img-top" style="height: auto;margin-top:20px">
<i class="fa-solid fa-user-plus fa-6x justify-content-center"></i>
<i class="fa-solid fa-user-plus fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<h5 class="card-title">Neuer Admin erstellen</h5>
@@ -147,7 +159,7 @@
<div class="card m-2" style="width: 14em;" href="#">
<div class="d-flex justify-content-center align-items-center card-img-top" style="height: auto;margin-top:20px">
<i class="fa-solid fa-users fa-6x justify-content-center"></i>
<i class="fa-solid fa-users fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<h5 class="card-title">Benutzer verwalten</h5>
@@ -160,7 +172,7 @@
echo('
<div class="card m-2" style="width: 14em;" href="#">
<div class="d-flex justify-content-center align-items-center card-img-top" style="height: auto;margin-top:20px">
<i class="fa-solid fa-trash fa-6x justify-content-center"></i>
<i class="fa-solid fa-trash fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<h5 class="card-title">Account löschen</h5>
@@ -174,7 +186,7 @@
echo('
<div class="card m-2" style="width: 14em;" href="#">
<div class="d-flex justify-content-center align-items-center card-img-top" style="height: auto;margin-top:20px">
<i class="fa-solid fa-shield-halved fa-6x justify-content-center"></i>
<i class="fa-solid fa-shield-halved fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<h5 class="card-title">Datenschutzrichtlinie</h5>
@@ -188,7 +200,7 @@
echo('
<div class="card m-2" style="width: 14em;" href="#">
<div class="d-flex justify-content-center align-items-center card-img-top" style="height: auto;margin-top:20px">
<i class="fa-solid fa-circle-info fa-6x justify-content-center"></i>
<i class="fa-solid fa-circle-info fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<h5 class="card-title">Disclaimer</h5>
@@ -204,7 +216,7 @@
echo('
<div class="card m-2" style="width: 14em;" href="#">
<div class="d-flex justify-content-center align-items-center card-img-top" style="height: auto;margin-top:20px">
<i class="fa-solid fa-file fa-6x justify-content-center"></i>
<i class="fa-solid fa-file fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<h5 class="card-title">System0 Protokoll ansehen</h5>
@@ -219,7 +231,7 @@
echo('
<div class="card m-2" style="width: 14em;" href="#">
<div class="d-flex justify-content-center align-items-center card-img-top" style="height: auto;margin-top:20px">
<i class="fa-solid fa-key fa-6x justify-content-center"></i>
<i class="fa-solid fa-key fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<h5 class="card-title">System0 APIkey ansehen</h5>
@@ -234,7 +246,7 @@
echo('
<div class="card m-2" style="width: 14em;" href="#">
<div class="d-flex justify-content-center align-items-center card-img-top" style="height: auto;margin-top:20px">
<i class="fa-solid fa-print fa-6x justify-content-center"></i>
<i class="fa-solid fa-print fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<h5 class="card-title">Einstellungen & Statistiken</h5>
@@ -249,7 +261,7 @@
echo('
<div class="card m-2" style="width: 14em;" href="#">
<div class="d-flex justify-content-center align-items-center card-img-top" style="height: auto;margin-top:20px">
<i class="fa-solid fa-calendar-days fa-6x justify-content-center"></i>
<i class="fa-solid fa-calendar-days fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<h5 class="card-title">Drucker Reservieren</h5>
@@ -263,7 +275,7 @@
echo('
<div class="card m-2" style="width: 14em;" href="#">
<div class="d-flex justify-content-center align-items-center card-img-top" style="height: auto;margin-top:20px">
<i class="fa-solid fa-key fa-6x justify-content-center"></i>
<i class="fa-solid fa-key fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<h5 class="card-title">Druckschlüssel erstellen</h5>
@@ -276,7 +288,7 @@
?>
<div class="card m-2" style="width: 14em;" href="#">
<div class="d-flex justify-content-center align-items-center card-img-top" style="height: auto;margin-top:20px">
<i class="fa-solid fa-message fa-6x justify-content-center"></i>
<i class="fa-solid fa-message fa-3x justify-content-center"></i>
</div>
<div class="card-body">
<input id="telegram_id" type="text" class="form-control mb-2" placeholder="Telegram Chat Id" value="<?php echo($_SESSION["telegram_id"]); ?>" oninput="update_telegram_id();">
@@ -307,6 +319,5 @@ echo('<input class="form-check-input" type="checkbox" id="notification_telegram"
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,7 @@
<?php
echo('<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" >
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
');
?>

View File

@@ -19,6 +19,7 @@ $sql = "CREATE TABLE IF NOT EXISTS users (
username VARCHAR(255) NOT NULL,
password VARCHAR(255),
role VARCHAR(255),
user_token VARCHAR(128),
created_at DATETIME,
keepmeloggedin VARCHAR(255),
color VARCHAR(50),

View File

@@ -46,7 +46,7 @@ curl --request POST \
--url https://api.sendgrid.com/v3/mail/send \
--header "Authorization: Bearer $SENDGRID_API_KEY" \
--header 'Content-Type: application/json' \
--data '{"personalizations": [{"to": [{"email": "$username"}]}],"from": {"email": "$sendgrid_email"},"subject": "System0 Account Validation","content": [{"type": "text/html", "value": "Hallo $username<br>Hier ist dein System0 Account verifikations Link. Bitte klicke drauf. Sollte dies nicht funktionieren, kopiere bitte den Link und öffne Ihn in deinem Browser.<br><a href='https://app.ksw3d.ch/login/verify_account.php?token=$token'>https://app.ksw3d.ch/login/verify_account.php?token=$token</a><br>Achtung: der Link funktioniert nur in dem gleichen Browser und Gerät, auf dem du deinen Account erstellt hast.<br><br>Vielen dank für dein Vertrauen in uns!<br>Code Camp 2024<br>"}]}'
--data '{"personalizations": [{"to": [{"email": "$username"}]}],"from": {"email": "$sendgrid_email"},"subject": "System0 Account Validation","content": [{"type": "text/html", "value": "Hallo $username<br>Hier ist dein System0 Account verifikations Link. Bitte klicke drauf. Sollte dies nicht funktionieren, kopiere bitte den Link und öffne Ihn in deinem Browser.<br><a href='https://app.ksw3d.ch/login/verify_account.php?token=$token'>https://app.ksw3d.ch/login/verify_account.php?token=$token</a><br>Achtung: der Link funktioniert nur in dem gleichen Browser und Gerät, auf dem du deinen Account erstellt hast.<br><br>Vielen dank für dein Vertrauen in uns!<br><a href=\"https://www.jakach.ch\">Jakach.ch</a><br>"}]}'
EOF;
exec($mail);
@@ -227,6 +227,7 @@ if($_SERVER["REQUEST_METHOD"] == "POST" and $_GET["action"]=="create_user"){
}
}
// Validate kantimail
//if(1) //put this to disable ksw only mail
if(strpos($_POST["username"],"@kantiwattwil.ch")===false){
$err = "Only members of KSW can access this site. (prename.name@kantiwattwil.ch).";
}
@@ -239,6 +240,7 @@ if($_SERVER["REQUEST_METHOD"] == "POST" and $_GET["action"]=="create_user"){
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
$banned=1;
//$banned=0; //put this to disable email verification enforcment
$banned_reason="Account muss zuerst verifiziert werden (Link in Mail)";
$tel=0;
$mail=1;
@@ -269,7 +271,7 @@ curl --request POST \
--url https://api.sendgrid.com/v3/mail/send \
--header "Authorization: Bearer $SENDGRID_API_KEY" \
--header 'Content-Type: application/json' \
--data '{"personalizations": [{"to": [{"email": "$username"}]}],"from": {"email": "$sendgrid_email"},"subject": "System0 Account Validation","content": [{"type": "text/html", "value": "Hallo $username<br>Hier ist dein System0 Account verifikations Link. Bitte klicke drauf. Sollte dies nicht funktionieren, kopiere bitte den Link und öffne Ihn in deinem Browser.<br><a href='https://app.ksw3d.ch/login/verify_account.php?token=$token'>https://app.ksw3d.ch/login/verify_account.php?token=$token</a><br>Achtung: der Link funktioniert nur in dem gleichen Browser und Gerät, auf dem du deinen Account erstellt hast.<br><br>Vielen dank für dein Vertrauen in uns!<br>Code Camp 2024<br>"}]}'
--data '{"personalizations": [{"to": [{"email": "$username"}]}],"from": {"email": "$sendgrid_email"},"subject": "System0 Account Validation","content": [{"type": "text/html", "value": "Hallo $username<br>Hier ist dein System0 Account verifikations Link. Bitte klicke drauf. Sollte dies nicht funktionieren, kopiere bitte den Link und öffne Ihn in deinem Browser.<br><a href='https://app.ksw3d.ch/login/verify_account.php?token=$token'>https://app.ksw3d.ch/login/verify_account.php?token=$token</a><br>Achtung: der Link funktioniert nur in dem gleichen Browser und Gerät, auf dem du deinen Account erstellt hast.<br><br>Vielen dank für dein Vertrauen in uns!<br><a href=\"https://www.jakach.ch\">Jakach.ch</a><br>"}]}'
EOF;
@@ -302,7 +304,7 @@ curl --request POST \
--url https://api.sendgrid.com/v3/mail/send \
--header "Authorization: Bearer $SENDGRID_API_KEY" \
--header 'Content-Type: application/json' \
--data '{"personalizations": [{"to": [{"email": "$email"}]}],"from": {"email": "$sendgrid_email"},"subject": "System0 Password reset","content": [{"type": "text/html", "value": "Hallo $email<br>Hier ist dein System0 Passwort Zurücksetzungs Link. Bitte klicke drauf. Sollte dies nicht funktionieren, kopiere bitte den Link und öffne Ihn in deinem Browser.<br><a href='https://app.ksw3d.ch/login/reset_pw.php?token=$token'>https://app.ksw3d.ch/login/reset_pw.php?token=$token</a><br>Achtung: der Link funktioniert nur in dem gleichen Browser und Gerät, auf dem du deinen Account erstellt hast.<br><br>Vielen dank für dein Vertrauen in uns!<br>Code Camp 2024<br>"}]}'
--data '{"personalizations": [{"to": [{"email": "$email"}]}],"from": {"email": "$sendgrid_email"},"subject": "System0 Password reset","content": [{"type": "text/html", "value": "Hallo $email<br>Hier ist dein System0 Passwort Zurücksetzungs Link. Bitte klicke drauf. Sollte dies nicht funktionieren, kopiere bitte den Link und öffne Ihn in deinem Browser.<br><a href='https://app.ksw3d.ch/login/reset_pw.php?token=$token'>https://app.ksw3d.ch/login/reset_pw.php?token=$token</a><br>Achtung: der Link funktioniert nur in dem gleichen Browser und Gerät, auf dem du deinen Account erstellt hast.<br><br>Vielen dank für dein Vertrauen in uns!<br><a href=\"https://www.jakach.ch\">Jakach.ch</a><br>"}]}'
EOF;
exec($mail);
@@ -320,7 +322,7 @@ EOF;
<!DOCTYPE html>
<html lang="en">
<html lang="en" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<?php include "../assets/components.php";?>
@@ -373,7 +375,12 @@ EOF;
<input type="checkbox" class="form-check-input" id="keepmeloggedin" name="keepmeloggedin" value="keepmeloggedin">
<label class="form-check-label" for="keepmeloggedin">Angemeldet bleiben</label>
</div>
<button type="submit" name="submit" class="btn btn-dark">Login</button>
<div class="d-flex align-items-center">
<button type="submit" name="submit" class="btn btn-secondary">Login</button>
<p class="mx-3 mb-0">Oder</p>
<a href="https://auth.jakach.ch/?send_to=https://app.ksw3d.ch/login/oauth.php" class="btn btn-secondary">mit Jakach account einloggen</a>
</div>
</form>
<div class="text-center mt-3">
<button type="button" class="btn btn-link" data-bs-toggle="modal" data-bs-target="#noaccount" id="lnk_1">Noch kein Account? Erstelle einen!</button>
@@ -390,7 +397,7 @@ EOF;
if(isset($_GET["acc_verify_ok"]))
echo '<div class="alert alert-success">Email erfolgreich Verifiziert.</div>';
if(isset($_GET["mail_sent3"]))
echo '<div class="alert alert-danger">Eine Mail mit einem Passwort zurücksetzungslink konnte nich gesendet werden. Bitte melde dich beim Support <a href="mailto:info.jakach@gmail.com">hier.</a></div>';
echo '<div class="alert alert-danger">Eine Mail mit einem Passwort zurücksetzungslink konnte nich gesendet werden. Bitte melde dich beim Support <a href="mailto:info@jakach.ch">hier.</a></div>';
?>
</div>
</div>
@@ -436,7 +443,7 @@ EOF;
<!--<label class="form-check-label" for="keepmeloggedin">Login speichern</label>-->
</div>
<!--<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>-->
<button type="submit" name="submit" class="btn btn-dark">Account erstellen</button>
<button type="submit" name="submit" class="btn btn-secondary">Account erstellen</button>
<div class="text-center mt-3">
<p class="mt-3">Durch erstellen des Accounts stimmst du unseren <a href="/app/privacy-policy.php">Datenschutzrichtlinien</a> zu</p>
</div>
@@ -461,7 +468,7 @@ EOF;
</div>
</div>
<div class="modal-footer">
<button type="submit" name="submit" class="btn btn-dark">Passwort zurücksetzlink senden</button>
<button type="submit" name="submit" class="btn btn-secondary">Passwort zurücksetzlink senden</button>
</div>
</div>
</form>

104
sys0-code/login/oauth.php Normal file
View File

@@ -0,0 +1,104 @@
<?php
// Initialize the session
session_start();
//include "/var/www/html/system0/html/php/login/v3/waf/waf_no_anti_xss.php";
$username = $password = $confirm_password = "";
$role="user";
$username_err = $password_err = $confirm_password_err = "";
$err="";
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: /app/overview.php");
exit;
}
require_once "../config/config.php";
require_once "../log/log.php";
require_once "../waf/salt.php";
require_once "keepmeloggedin.php";
include "../assets/components.php";
$error=logmein($link);
if($error==="success")
{
header("LOCATION: /app/overview.php");
}
$auth_token = $_GET["auth"];
// Check the auth token against Jakach login API
$check_url = "https://auth.jakach.ch/api/auth/check_auth_key.php?auth_token=" . $auth_token;
// Initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $check_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute cURL and get the response
$response = curl_exec($ch);
// Check for cURL errors
if(curl_errno($ch)) {
die("cURL Error: " . curl_error($ch));
}
// Close cURL
curl_close($ch);
// Decode the JSON response
$data = json_decode($response, true);
// Check if the response contains a valid status
if (isset($data['status'])) {
if ($data['status'] == "success") {
// Successful authentication: login the user
$_SESSION["username"] = $data["username"];
$_SESSION["id"] = $data["id"];
$_SESSION["email"] = $data["email"];
$_SESSION["telegram_id"] = $data["telegram_id"];
$_SESSION["user_token"] = $data["user_token"];
//load user data
$sql = "SELECT id, username, password, role, color,banned,banned_reason ,telegram_id,notification_telegram,notification_mail, class_id FROM users WHERE user_token = ?";
$stmt = mysqli_prepare($link, $sql);
$user_token=$_SESSION["user_token"];
mysqli_stmt_bind_param($stmt, "s", $user_token);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username = $password = "";
$username_err = $password_err = $login_err = "";
$color="";
$banned=0;
$banned_reason="";
$telegram_id="";
$notification_telegram=0;
$notification_mail=0;
$class_id=0;
$id=0;
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password, $role,$color,$banned,$banned_reason,$telegram_id,$notification_telegram,$notification_mail,$class_id);
mysqli_stmt_fetch($stmt);
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["role"] = $role;
$_SESSION["token"]=bin2hex(random_bytes(32));
$_SESSION["color"]=$color;
$_SESSION["creation_token"]= urlencode(bin2hex(random_bytes(24/2)));
$_SESSION["telegram_id"]=$telegram_id;
$_SESSION["notification_telegram"]=$notification_telegram;
$_SESSION["notification_mail"]=$notification_mail;
$_SESSION["class_id"]=$class_id;
mysqli_stmt_close($stmt);
echo("<script>location.href='/app/overview.php';</script>");
}else{
echo("<div class='alert alert-danger'>Dein System0 Account wurde noch nicht mit deinem Jakach account verknüpft!<br>Um deinen Jakach account zu verknüpfen, folge bitte <a href='https://github.com/jakani24/system0-2.0/blob/main/connect_jac.pdf'>dieser</a> Anleitung</div>");
}
// Return a success response
} else {
// Authentication failed
echo '<div class="alert alert-danger">Invalid auth token</div>';
}
} else {
// Invalid response format or missing status
echo '<div class="alert alert-danger">Server error</div>';
}
?>

View File

@@ -15,7 +15,7 @@ $new_password_err = $confirm_password_err = "";
$old_password="";
$old_passwort_err="";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["old_password"])){
$login_err="";
//first: validate old password
if(empty(trim($_POST["old_password"]))){
@@ -45,6 +45,7 @@ if($_SERVER["REQUEST_METHOD"] == "POST"){
// Redirect user to welcome page
$auth=true;
$change=true;
} else{
// Password is not valid, display a generic error message
$login_err = "Invalid password.";
@@ -61,7 +62,7 @@ if($_SERVER["REQUEST_METHOD"] == "POST"){
}
}
}
if($auth===true)
if($auth===true && $change===true)
{
//end of old_password validation
// Validate new password
@@ -115,12 +116,23 @@ if($_SERVER["REQUEST_METHOD"] == "POST"){
}
}
}
if(isset($_POST["user_token"])){
$sql="update users set user_token = ? where id = ?";
$stmt = mysqli_prepare($link, $sql);
$user_token=$_POST["user_token"];
$id=$_SESSION["id"];
mysqli_stmt_bind_param($stmt, "si", $user_token, $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$msg="User Token wurde hinzugefügt.";
}
// Close connection
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="en">
<html lang="en" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<title>Passwort zurücksetzen</title>
@@ -178,6 +190,21 @@ echo("<div id='content'></div>");?>
echo '<div class="alert alert-danger">' . $login_err . '</div>';
}
?>
<p>Hier kannst du deinen Jakach-Account verknüpfen, um dich leichter einzuloggen.</p>
<p>Du findest dein User-Token in bei deinem Jakach Account (<a href="https://auth.jakach.ch/?send_to=/account/">hier</a>)
<div class="m-3">
<form action="" method="post">
<div class="form-group m-2">
<label for="pwd">User Token:</label>
<input type="text" class="form-control" id="user_token" name="user_token" required>
</div>
<button type="submit" name="submit" class="btn btn-dark m-2">Bestätigen</button>
</form>
</div>
<?php
if(isset($msg))
echo '<div class="alert alert-success">' . $msg . '</div>';
?>
</div>
</div>
<div id="footer"></div>

View File

@@ -12,7 +12,7 @@ $old_passwort_err="";
$username=$_SESSION["verify"];
echo("<div id='content'></div>");
if($_GET["token"]!=$_SESSION["pw_reset_token"]){
$login_err = "Dein Link ist entweder abgelaufen oder ungültig. Erzeuge einen neuen, in dem du auf <a href='/app/login.php?resend_pw_reset'>diesen Link</a> klickst.";
$login_err = "Dein Link ist entweder abgelaufen oder ungültig. Erzeuge einen neuen, in dem du auf <a href='/login/login.php?resend_pw_reset'>diesen Link</a> klickst.";
echo '<div class="alert alert-danger">' . $login_err . '</div>';
//die();