ENHANCEMENT: Cleanup of old files

This commit is contained in:
Jeroen De Meerleer 2021-08-02 13:56:12 +02:00
parent 621fadd7c2
commit 877ec75e90
Signed by: JeroenED
GPG Key ID: 28CCCB8F62BFADD6
17 changed files with 0 additions and 979 deletions

View File

@ -1,3 +0,0 @@
tr.norun td {
color: #c00000;
}

View File

@ -1,37 +0,0 @@
$(document).ready(function() {
$("body").on("click", "#patternDropdown li", function() {
if(this.value != "custom") { $("input#delay").val($(this).data("val")); }
});
$('#nextrunselector').datetimepicker({format: 'L LTS'});
$('#lastrunselector').datetimepicker({format: 'L LTS'});
$("body").on("click", ".runcron", function() {
$("#ajax_loader").show();
fullurl = "/runnow.php?jobID=" + $(this).data("id");
$.ajax(fullurl).done(function(data) {
results = JSON.parse(data);
if(results["error"] !== undefined) {
$("#resulttitle").html("Error");
$("#resultbody").text(results["error"]);
} else {
$("#resulttitle").html("Success");
$("#resultbody").text(results["message"]);
}
$("#ajax_loader").hide();
$('#resultmodal').modal('show');
});
});
$("body").on("input", "input[name=url]", function() {
if($("input[name=url]").val().startsWith("reboot")) {
$("#url-description").html("This job triggers a reboot. Please use <pre>reboot cmd={{command}}&services={{command}}</pre> to modify the reboot and get services commands. You can use {s}+ or {m}+ in the reboot command to use the Reboot wait configuration value ({s}+ will convert to seconds, {m}+ to minutes)");
$("label[for=expected]").html("Capture services after reboot? (1: yes; 0: no)");
$("input[name=expected]").attr("placeholder", "1");
} else {
$("#url-description").html("");
$("label[for=expected]").html("Expected exit code");
$("input[name=expected]").attr("placeholder", "200");
}
});
$("input[name=url]").trigger("input");
});

View File

@ -1,30 +0,0 @@
{% extends "base.html.twig" %}
{% block title %}configuration{% endblock %}
{% block content %}
<h2>Webcron configuration</h2>
{% if not message == "" %}
<div class="alert alert-success fade in">
<a href="#" class="close" data-dismiss="alert">&times;</a>
{{ message }}
</div>
{% endif %}
{% if not error == "" %}
<div class="alert alert-danger fade in">
<a href="#" class="close" data-dismiss="alert">&times;</a>
<strong>Error!</strong> {{ error }}
</div>
{% endif %}
<form method="post" action="config.php">
{% for cat in config %}
<h3>{{ cat.name }}</h3>
{% for confval in cat.conf %}
<div class="form-group">
<p><label for="{{ confval.conf }}">{{ confval.label }}</label><p>
<p><input class="form-control" id="{{ confval.conf }}" name="{{ confval.conf }}" type="{{ confval.type.type }}"{% for args in confval.type.args %} {{ args | raw }}{% endfor %}value="{{ confval.value }}">
<p class="description">{{ confval.description }}</p>
</div>
{% endfor %}
{% endfor %}
<button type="submit" class="btn btn-default">Submit</button>
</form>
{% endblock %}

View File

@ -1,74 +0,0 @@
{% extends "base.html.twig" %}
{% block title %}Edit job {{ name }}{% endblock %}
{% block content %}
<form method="post" action="/webcron.old/editjob.php?jobID={{ jobID }}">
{% if not error == "" %}
<div class="alert alert-danger fade in">
<a href="#" class="close" data-dismiss="alert">&times;</a>
<strong>Error!</strong> {{ error }}
</div>
{% endif %}
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" id="name" placeholder="System update" value="{{ name }}">
</div>
<div class="form-group">
<label for="url">url</label>
<input type="text" name="url" class="form-control" id="url" placeholder="http://example.com/ or 'sudo yum update -y'" value="{{ url }}">
<p class="url-description"></p>
</div>
<div class="form-group">
<label for="host">host</label>
<input type="text" name="host" class="form-control" id="host" placeholder="localhost" value="{{ host }}">
</div>
<div class="form-group">
<label for="name">Delay (in seconds)</label>
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Pattern <span class="caret"></span></button>
<ul class="dropdown-menu" id="patternDropdown">
<li data-val="60"><a href="#">Every minute</a></li>
<li data-val="3600"><a href="#">Every hour</a></li>
<li data-val="86400"><a href="#">Every day</a></li>
<li data-val="604800"><a href="#">Every week</a></li>
<li data-val="2419200"><a href="#">Every 4 weeks</a></li>
<li data-val="custom"><a href="#">Custom</a></li>
</ul>
</div><!-- /btn-group -->
<input type="number" class="form-control" id="delay" name="delay" value="{{ delay }}">
</div>
</div>
<div class="form-group">
<label for="nextrun">Next run</label>
<div class="input-group date" id="nextrunselector">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
<input type="text" class="form-control" name="nextrun" value="{{ nextrun }}">
</div>
</div>
<div class="form-group">
<label for="lastrun">Last run</label>
<div class="input-group date" id="lastrunselector">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
<input type="text" class="form-control" name="lastrun" value="{{ lastrun }}">
<span class="input-group-addon">
<input type="checkbox" name="eternal" value="true"{% if (lastrun == -1) %} checked{% endif %}>&nbsp;Eternal
</span>
</div>
</div>
<div class="form-group">
<label for="expected">Expected exit code</label>
<input type="text" name="expected" class="form-control" id="host" value="{{ expected }}">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
{% endblock %}

View File

@ -1,28 +0,0 @@
{% extends "base.html.twig" %}
{% block title %}Overview of run for {{ title }}{% endblock %}
{% block content %}
<h2>Overview of runs for {{ title }}</h2>
<p>
<a href="editjob.php?jobID={{ jobID }}">Edit job</a>
{% if rebootjob %}
{% elseif allruns %} | <a href="runs.php?jobID={{ jobID }}&allruns=0">Only show failed runs</a>
{% elseif not allruns %} | <a href="runs.php?jobID={{ jobID }}&allruns=1">Show all runs</a>
{% endif %}
</p>
<div id="accordion" class="panel-group">
{% for run in runs %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ loop.index }}">{% if not rebootjob %}({{ run.statuscode }}){% endif %} {{ run.timestamp }}</a>
</h4>
</div>
<div id="collapse{{ loop.index }}" class="panel-collapse collapse">
<div class="panel-body">
<pre>{{ run.result }}</pre>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}

View File

@ -1,75 +0,0 @@
<?php
require_once "include/initialize.inc.php";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array('cache' => 'cache', "debug" => true));
$error = "";
if (isset($_GET["error"])) {
switch ($_GET["error"]) {
case "emptyfields":
$error = "Some fields were empty"; break;
case "invalidurl":
$error = "The URL is invalid"; break;
case "invaliddelay":
$error = "The delay is invalid"; break;
}
}
$message = "";
if (isset($_GET["message"])) {
switch ($_GET["message"]) {
case "added":
$message = "The cronjob has been added"; break;
}
}
echo $twig->render('add.html.twig', array("message" => $message, "error" => $error));
}
elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['name']) || empty($_POST['url'] || empty($_POST['delay']))) {
header("location:addjob.php?error=emptyfields");
exit;
}
$url = $_POST['url'];
$host = $_POST['host'];
$name = $_POST['name'];
$delay = $_POST['delay'];
$expected = $_POST['expected'];
$eternal = (isset($_POST['eternal']) && $_POST['eternal'] == true) ? true : false;
$nextrunObj = DateTime::createFromFormat("d/m/Y H:i:s", $_POST['nextrun']);
$nextrun = $nextrunObj->getTimestamp();
if (!$eternal) {
$lastrunObj = DateTime::createFromFormat("d/m/Y H:i:s", $_POST['lastrun']);
$lastrun = $lastrunObj->getTimestamp();
} else {
$lastrun = -1;
}
if(!is_numeric($delay)) {
header("location:addjob.php?error=invaliddelay");
exit;
}
if(!is_numeric($nextrun)) {
header("location:addjob.php?error=invalidnextrun");
exit;
}
if(!is_numeric($lastrun)) {
header("location:addjob.php?error=invalidlastrun");
exit;
}
$stmt = $db->prepare("INSERT INTO jobs(user, name, url, host, delay, nextrun, expected) VALUES(?, ?, ?, ?, ?, ?, ?)");
$stmt->execute(array($_SESSION["userID"], $name, $url, $host, $delay, $nextrun, $expected));
header("location:addjob.php?message=added");
exit;
}
require_once 'include/finalize.inc.php';

View File

@ -1,6 +0,0 @@
<?php
define("DBHOST", "localhost");
define("DBUSER", "jeroened_admin");
define("DBPASS", "letmein");
define("DBNAME", "jeroened_webcron");

View File

@ -1,49 +0,0 @@
<?php
require_once "include/initialize.inc.php";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$message = "";
if (isset($_GET["message"])) {
switch ($_GET["message"]) {
case "edited":
$message = "The config has been edited"; break;
}
}
$error = "";
if (isset($_GET["error"])) {
switch ($_GET["error"]) {
case "emptyfields":
$error = "Some fields were empty"; break;
}
}
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array('cache' => 'cache', "debug" => true));
$configs = load_config_categorized();
$twig_vars = array('config' => $configs, "error" => $error, "message" => $message);
echo $twig->render('config.html.twig', $twig_vars);
}
elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST as $key => $value) {
if (empty($value)) {
header("location:config.php?error=emptyfields"); exit;
}
$keydb = str_replace('_', '.', $key);
$stmt = $db->prepare("UPDATE config SET value = ? WHERE conf = ?");
$stmt->execute(array($value, $keydb));
}
header("location:config.php?message=edited");
exit;
}
require_once 'include/finalize.inc.php';

View File

@ -1,97 +0,0 @@
-- phpMyAdmin SQL Dump
-- version 4.6.6deb5
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Sep 12, 2018 at 12:23 PM
-- Server version: 10.1.34-MariaDB-0ubuntu0.18.04.1
-- PHP Version: 5.6.37-1+ubuntu18.04.1+deb.sury.org+1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `jeroened_webcron`
--
-- --------------------------------------------------------
--
-- Table structure for table `config`
--
DROP TABLE IF EXISTS `config`;
CREATE TABLE IF NOT EXISTS `config` (
`conf` varchar(100) NOT NULL,
`category` varchar(50) NOT NULL,
`type` varchar(50) NOT NULL,
`label` text NOT NULL,
`description` text NOT NULL,
`value` varchar(100) NOT NULL,
PRIMARY KEY (`conf`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `config`
--
INSERT INTO `config` (`conf`, `category`, `type`, `label`, `description`, `value`) VALUES
('dbclean.delay', 'Database Cleanup', 'number(0)', 'Cleanup Delay', 'How many days until the database cleanup is triggered', '7'),
('dbclean.expireruns', 'Database Cleanup', 'number(0)', 'Retention', 'How many days does the database keep the runs', '30'),
('dbclean.enabled', 'Database Cleanup', 'text', 'Enabled', 'Database cleanup enabled? (true: yes; false: no)', 'false'),
('dbclean.lastrun', 'Database Cleanup', 'hidden', 'Last run', 'Last run of database cleanup', UNIX_TIMESTAMP()),
('jobs.reboottime', 'Jobs', 'number(0)', 'Reboot time', 'The amount of time in seconds for the systems to perform a reboot', '300'),
('jobs.rebootwait', 'Jobs', 'number(0)', 'Reboot wait', 'The amount of time in seconds between scheduling a reboot and the actual reboot', '300'),
('master.crashtimeout', 'Master script', 'number()', 'Master script crash timeout', 'The amount of time in seconds after we can assume the master script is crashed', '3600');
-- --------------------------------------------------------
--
-- Table structure for table `jobs`
--
DROP TABLE IF EXISTS `jobs`;
CREATE TABLE IF NOT EXISTS `jobs` (
`jobID` int(11) NOT NULL AUTO_INCREMENT,
`user` int(11) NOT NULL,
`name` text NOT NULL,
`url` text NOT NULL,
`host` varchar(50) NOT NULL DEFAULT 'localhost',
`delay` int(11) NOT NULL,
`nextrun` int(11) NOT NULL,
`lastrun` int(11) NOT NULL DEFAULT '-1',
`expected` int(11) NOT NULL DEFAULT '200',
PRIMARY KEY (`jobID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `runs`
--
DROP TABLE IF EXISTS `runs`;
CREATE TABLE IF NOT EXISTS `runs` (
`runID` bigint(20) NOT NULL AUTO_INCREMENT,
`job` int(11) NOT NULL,
`statuscode` char(3) NOT NULL,
`result` longtext NOT NULL,
`timestamp` int(11) NOT NULL,
PRIMARY KEY (`runID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`password` char(60) NOT NULL,
`email` varchar(100) NOT NULL,
`autologin` text NOT NULL,
PRIMARY KEY (`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

View File

@ -1,86 +0,0 @@
<?php
require_once "include/initialize.inc.php";
$jobID = $_GET['jobID'];
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$jobnameqry = $db->prepare("SELECT * FROM jobs WHERE jobID = ?");
$jobnameqry->execute(array($_GET['jobID']));
$jobnameResult = $jobnameqry->fetchAll(PDO::FETCH_ASSOC);
if ($jobnameResult[0]["user"] != $_SESSION["userID"]) {
header("location:/overview.php");
exit;
}
$name = $jobnameResult[0]['name'];
$url = $jobnameResult[0]['url'];
$host = $jobnameResult[0]['host'];
$delay = $jobnameResult[0]['delay'];
$expected = $jobnameResult[0]['expected'];
$nextrun = date("d/m/Y H:i:s", $jobnameResult[0]['nextrun']);
$lastrun = ($jobnameResult[0]['lastrun'] == -1) ? -1 : date("d/m/Y H:i:s", $jobnameResult[0]['lastrun']);
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array('cache' => 'cache', "debug" => true));
$error = "";
if (isset($_GET["error"])) {
switch ($_GET["error"]) {
case "emptyfields":
$error = "Some fields were empty"; break;
case "invalidurl":
$error = "The URL is invalid"; break;
case "invaliddelay":
$error = "The delay is invalid"; break;
}
}
echo $twig->render('editjob.html.twig', array("name" => $name, "url" => $url, "host" => $host, "delay" => $delay, "expected" => $expected, 'nextrun' => $nextrun, 'lastrun' => $lastrun, "jobID" => $jobID, "error" => $error));
}
elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['name']) || empty($_POST['url'] || empty($_POST['delay']))) {
header("location:editjob.php?error=emptyfields");
exit;
}
$url = $_POST['url'];
$name = $_POST['name'];
$delay = $_POST['delay'];
$host = $_POST['host'];
$expected = $_POST['expected'];
$eternal = (isset($_POST['eternal']) && $_POST['eternal'] == true) ? true : false;
$nextrunObj = DateTime::createFromFormat("d/m/Y H:i:s", $_POST['nextrun']);
$nextrun = $nextrunObj->getTimestamp();
if (!$eternal) {
$lastrunObj = DateTime::createFromFormat("d/m/Y H:i:s", $_POST['lastrun']);
$lastrun = $lastrunObj->getTimestamp();
} else {
$lastrun = -1;
}
if(!is_numeric($delay)) {
header("location:editjob.php?jobID=" . $jobID . "&error=invaliddelay");
exit;
}
if(!is_numeric($nextrun)) {
header("location:editjob.php?jobID=" . $jobID . "&error=invalidnextrun");
exit;
}
if(!is_numeric($lastrun)) {
header("location:editjob.php?jobID=" . $jobID . "&error=invalidlastrun");
exit;
}
$stmt = $db->prepare("UPDATE jobs SET name = ?, url = ?, host = ?, delay = ?, nextrun = ?, expected = ?, lastrun = ? WHERE jobID = ?");
$stmt->execute(array($name, $url, $host, $delay, $nextrun, $expected, $lastrun, $jobID));
header("location:overview.php?message=edited");
exit;
}
require_once 'include/finalize.inc.php';

View File

@ -1,2 +0,0 @@
<?php

View File

@ -1,76 +0,0 @@
<?php
function job_in_array($id, $jobs) {
foreach ($jobs as $job) {
if ($job['jobID'] == $id) return true;
}
return false;
}
function load_config_categorized() {
global $db;
$allConfig = $db->prepare("SELECT * FROM config ORDER BY category ASC")->execute()->fetchAllAssociative();
// Separate lines into categories
$configCategorized = array();
$count = 0;
foreach($allConfig as $key=>$value) {
if ($value['type'] != "hidden") {
$configCategorized[$value['category']][$count]['conf'] = $value['conf'];
$configCategorized[$value['category']][$count]['value'] = $value['value'];
$configCategorized[$value['category']][$count]['label'] = $value['label'];
$configCategorized[$value['category']][$count]['description'] = $value['description'];
$configCategorized[$value['category']][$count]['type'] = parse_config_type($value['type']);
}
$count++;
}
// into a easy twig array
$catcount = 0;
foreach ($configCategorized as $key => $value) {
$twigarray[$catcount]['name'] = $key;
$twigarray[$catcount]['conf'] = $value;
$catcount++;
}
return $twigarray;
}
function get_configvalue($conf) {
global $db;
$config = $db->prepare("SELECT value FROM config WHERE conf = :conf")->execute([':conf' => $conf])->fetchAssociative();
return $config['value'];
}
function parse_config_type($type) {
$splittype = explode('(', explode(')', $type)[0]);
$r_var['type'] = $splittype[0];
if (isset($splittype[1])) {
$splitargs = explode(',', $splittype[1]);
switch($r_var['type'])
{
case 'number':
$r_var['args'][] = isset($splitargs[0]) ? 'min="' . $splitargs[0] . '"' : '';
$r_var['args'][] = isset($splitargs[1]) ? 'max="' . $splitargs[1] . '"' : '';
break;
}
}
return $r_var;
}
function clean_database() {
global $db;
$oldestrun = time() - (get_configvalue('dbclean.expireruns') * 60 * 60 * 24);
$db->prepare("DELETE FROM runs WHERE timestamp < :oldestrun")->execute([':oldestrun' => $oldestrun]);
$db->prepare("UPDATE config SET value = :value WHERE conf = :conf")->execute([':value' => time(), ':conf' => 'dbclean.lastrun']);
}

View File

@ -1,80 +0,0 @@
<?php
require_once "include/initialize.inc.php";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
if(isset($_COOKIE["secure_auth"]) && isset($_COOKIE["secure_auth_name"])) {
$userQry = $db->prepare("SELECT * FROM users WHERE name = ?");
$userQry->execute(array($_COOKIE["secure_auth_name"]));
$user = $userQry->fetchAll(PDO::FETCH_ASSOC);
if (in_array($_COOKIE["secure_auth"], unserialize($user[0]["autologin"]))) {
$_SESSION['userID'] = $user[0]['userID'];
header("location:overview.php");
exit;
}
}
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array('cache' => 'cache', "debug" => true));
$error = "";
if (isset($_GET["error"])) {
switch ($_GET["error"]) {
case "emptyfields":
$error = "Some fields were empty"; break;
case "invalidcredentials":
$error = "The credentials were invalid"; break;
}
}
echo $twig->render('index.html.twig', array("error" => $error));
}
elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['name']) || empty($_POST['passwd'])) {
header("location:index.php?error=emptyfields");
exit;
}
$passwd = $_POST['passwd'];
$name = $_POST['name'];
$autologin = $_POST["autologin"];
$userQry = $db->prepare("SELECT * FROM users WHERE name = ?");
$userQry->execute(array($name));
$user = $userQry->fetchAll(PDO::FETCH_ASSOC);
if ( password_verify($passwd, $user[0]['password']) ) {
$_SESSION['userID'] = $user[0]['userID'];
if ($autologin = "autologin") {
$autologin = hash("sha512", time() . $user[0]["name"] . $user[0]["password"] . session_id());
setcookie("secure_auth", $autologin, time() + (60 * 60 * 24 * 365));
setcookie("secure_auth_name", $user[0]["name"] , time() + (60 * 60 * 24 * 365));
$autologin_array = array();
if (!empty($user[0]["autologin"])) $autologin_array = unserialize($user[0]["autologin"]);
$autologin_array[] = $autologin;
/*var_dump($autologin_array);
exit;*/
$loginQry = $db->prepare("UPDATE users SET autologin = ? WHERE userID = ?");
$loginQry->execute(array(serialize($autologin_array), $_SESSION["userID"]));
}
header("location:overview.php");
exit;
} else {
header("location:index.php?error=invalidcredentials");
exit;
}
}
require_once 'include/finalize.inc.php';

View File

@ -1,68 +0,0 @@
<?php
require_once "include/initialize.inc.php";
$message = "";
if (isset($_GET['action'])) {
$jobID = $_GET['jobID'];
if ($_GET['action'] == "delete") {
$deletestmt = $db->prepare("DELETE FROM jobs WHERE jobID = ? ");
$deletestmt->execute(array($jobID));
$delete2stmt = $db->prepare("DELETE FROM runs WHERE job = ? ");
$delete2stmt->execute(array($jobID));
$message = "Job was sucessfully deleted";
}
}
if (isset($_GET["message"])) {
$message = "";
switch ($_GET["message"]) {
case "edited":
$message = "The cronjob has been edited"; break;
}
}
$allJobs = $db->prepare("SELECT * FROM jobs WHERE user = ? ORDER BY name ASC");
$allJobs->execute(array($_SESSION["userID"]));
$allJobsResult = $allJobs->fetchAll(PDO::FETCH_ASSOC);
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array('cache' => 'cache', "debug" => true));
//var_dump($alljobsResult);
//exit;
$allJobsRendered = array();$count = 0;
foreach($allJobsResult as $key=>$value) {
$allJobsRendered[$count]["jobID"] = $value["jobID"];
$allJobsRendered[$count]["name"] = $value["name"];
$allJobsRendered[$count]["host"] = $value["host"];
$allJobsRendered[$count]["nextrun"] = date("d/m/Y H:i:s", $value["nextrun"]);
$allJobsRendered[$count]["norun"] = ($value['nextrun'] > $value['lastrun'] && $value['lastrun'] > 0) ? true : false;
$allJobsRendered[$count]["delay"] = secondsToInterval($value["delay"]);
$count++;
}
$twig_vars = array('jobs' => $allJobsRendered, 'message' => $message);
echo $twig->render('overview.html.twig', $twig_vars);
require_once 'include/finalize.inc.php';
function secondsToInterval($time) {
$days = floor($time / (60 * 60 * 24));
$time -= $days * (60 * 60 * 24);
$hours = floor($time / (60 * 60));
$time -= $hours * (60 * 60);
$minutes = floor($time / 60);
$time -= $minutes * 60;
$seconds = floor($time);
$time -= $seconds;
return "{$days}d {$hours}h {$minutes}m {$seconds}s";
}

View File

@ -1,85 +0,0 @@
<?php
/*
* The MIT License
*
* Copyright 2017 Jeroen De Meerleer <me@jeroened.be>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
require_once "include/initialize.inc.php";
if(!isset($_GET['jobID'])) {
header("location:/overview.php");
exit;
}
$jobID = $_GET['jobID'];
$jobnameqry = $db->prepare("SELECT * FROM jobs WHERE jobID = ?");
$jobnameqry->execute(array($_GET['jobID']));
$jobnameResult = $jobnameqry->fetchAll(PDO::FETCH_ASSOC);
if ($jobnameResult[0]["user"] != $_SESSION["userID"]) {
die(json_encode(array("error" => "You dirty hacker!")));
}
$nosave = false;
if (filter_var($jobnameResult[0]["url"], FILTER_VALIDATE_URL)) {
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', $jobnameResult[0]['url'], ['http_errors' => false]);
$statuscode = $res->getStatusCode();
$body = $res->getBody();
$timestamp = time();
} else {
if(strpos($jobnameResult[0]["url"],"reboot") !== 0) {
$body = '';
$statuscode = 0;
$url = "ssh " . $jobnameResult[0]['host'] . " '" . $jobnameResult[0]['url'] . "' 2>&1";
exec($url, $body, $statuscode);
$body = implode("\n", $body);
$timestamp = time();
} else {
$rebootjobs = array();
if (file_exists('cache/get-services.trigger')) {
$rebootjobs = unserialize(file_get_contents('cache/get-services.trigger'));
}
if (!job_in_array($jobnameResult[0]['jobID'], $rebootjobs)) {
$rebootjobs[] = $jobnameResult[0];
touch("cache/reboot.trigger");
$nosave = true;
}
}
}
if($nosave !== true) {
$stmt = $db->prepare("INSERT INTO runs(job, statuscode, result, timestamp) VALUES(?, ?, ?, ?)");
$stmt->execute(array($jobID, $statuscode, $body, $timestamp));
}
if(file_exists("cache/reboot.trigger")) {
$rebootser = serialize($rebootjobs);
file_put_contents("cache/get-services.trigger", $rebootser);
echo json_encode(array("message" => "Reboot is scheduled. Programmer's fuel is awaiting"));
} else {
echo json_encode(array("message" => "Cronjob succesfully ran"));
}
require_once 'include/finalize.inc.php';

View File

@ -1,44 +0,0 @@
<?php
require_once "include/initialize.inc.php";
$jobnameqry = $db->prepare("SELECT name, user, url FROM jobs WHERE jobID = ?");
$jobnameqry->execute(array($_GET['jobID']));
$jobnameResult = $jobnameqry->fetchAll(PDO::FETCH_ASSOC);
if ($jobnameResult[0]["user"] != $_SESSION["userID"]) {
header("location:/overview.php");
exit;
}
$jobName = $jobnameResult[0]['name'];
$rebootjob = strpos($jobnameResult[0]["url"],"reboot") === 0 ? true : false;
$runsForJobQry = "SELECT runs.*, jobs.jobID FROM runs, jobs WHERE runs.job = jobs.jobID AND runs.job = ?";
$allruns = true;
if(!(isset($_GET['allruns']) && $_GET['allruns'] == 1)) {
$runsForJobQry .= " AND runs.statuscode <> jobs.expected";
$allruns = false;
}
$runsForJob = $db->prepare($runsForJobQry);
$runsForJob->execute(array($_GET['jobID']));
$runsForJobResult = $runsForJob->fetchAll(PDO::FETCH_ASSOC);
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array('cache' => 'cache', "debug" => true));
$runsForJobRendered = array();$count = 0;
foreach($runsForJobResult as $key=>$value) {
$runsForJobRendered[$count]["runID"] = $value["runID"];
$runsForJobRendered[$count]["statuscode"] = $value["statuscode"];
$runsForJobRendered[$count]["result"] = $value["result"];
$runsForJobRendered[$count]["timestamp"] = date("d/m/Y H:i:s", $value["timestamp"]);
$count++;
}
$twig_vars = array('jobID' => $_GET['jobID'], 'rebootjob' => $rebootjob, 'runs' => $runsForJobRendered, 'allruns' => $allruns, "title" => $jobName);
//echo $twig->render('overview.html.twig', array('the' => 'variables', 'go' => 'here'));
echo $twig->render('runs.html.twig', $twig_vars);
require_once 'include/finalize.inc.php';

View File

@ -1,139 +0,0 @@
<?php
require_once "include/initialize.inc.php";
if(file_exists('/tmp/webcron.lock') && file_get_contents('/tmp/webcron.lock') + get_configvalue('master.crashtimeout') > time() )
{
die('Script is already running');
}
if(file_exists('/tmp/webcron.lock')) unlink('/tmp/webcron.lock');
file_put_contents('/tmp/webcron.lock', time());
/**
* Reboot finalize
*/
if (file_exists(__DIR__ . "/cache/get-services.trigger")) {
if (file_exists(__DIR__ . "/cache/reboot-time.trigger") && file_get_contents(__DIR__ . "/cache/reboot-time.trigger") < time()) {
$rebootjobs = json_decode(file_get_contents(__DIR__ . "/cache/get-services.trigger"), true);
foreach($rebootjobs as $job) {
$services = array();
$rebooter = preg_replace("/reboot /", "", $job['url'], 1);
$rebooter = urlencode($rebooter);
$rebooter = str_replace("cmd%3D", "cmd=", $rebooter);
$rebooter = str_replace("services%3D", "services=", $rebooter);
$rebooter = str_replace("%26", "&", $rebooter);
parse_str($rebooter, $rebootcommands);
$cmd = $rebootcommands['services'];
if ($cmd == '') {
$cmd = "sudo systemctl list-units | cat";
}
$url = "ssh " . $job['host'] . " '" . $cmd . "' 2>&1";
exec($url, $services);
$cmd = '';
$services = implode("\n", $services);
$stmt = $db->prepare("INSERT INTO runs(job, statuscode, result, timestamp) VALUES(?, ?, ?, ?)");
$stmt->execute(array($job['jobID'], '0', $services, time()));
}
unlink(__DIR__ . "/cache/get-services.trigger");
unlink(__DIR__ . "/cache/reboot-time.trigger");
}
}
$stmt = $db->prepare('SELECT * FROM jobs WHERE nextrun <= ? and (nextrun <= lastrun OR lastrun = -1)');
$stmt->execute(array(time()));
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$client = new \GuzzleHttp\Client();
$rebootjobs = array();
if (file_exists(__DIR__ . "/cache/get-services.trigger")) {
$rebootjobs = json_decode(file_get_contents(__DIR__ . "/cache/get-services.trigger"), true);
}
foreach ($results as $result) {
if (filter_var($result["url"], FILTER_VALIDATE_URL)) {
$res = $client->request('GET', $result['url'], ['http_errors' => false]);
$statuscode = $res->getStatusCode();
$body = $res->getBody();
} else {
if(strpos($result["url"],"reboot") !== 0) {
$nosave = false;
$body = '';
$statuscode = 0;
$url = "ssh " . $result['host'] . " '" . $result['url'] . "' 2>&1";
exec($url, $body, $statuscode);
$body = implode("\n", $body);
} else {
$rebootjobs = array();
if (file_exists(__DIR__ . '/cache/get-services.trigger')) {
$rebootjobs = json_decode(file_get_contents(__DIR__ . '/cache/get-services.trigger'), true);
}
if (!job_in_array($result['jobID'], $rebootjobs)) {
echo "no hope";
$rebootjobs[] = $result;
$rebootser = json_encode($rebootjobs);
file_put_contents(__DIR__ . "/cache/get-services.trigger", $rebootser);
touch(__DIR__ . "/cache/reboot.trigger");
$nosave = true;
}
}
}
if(!$nosave) {
$stmt = $db->prepare("INSERT INTO runs(job, statuscode, result, timestamp) VALUES(?, ?, ?, ?)");
$stmt->execute(array($result['jobID'], $statuscode, $body, time()));
}
$nextrun = $result['nextrun'];
do {
$nextrun = $nextrun + $result['delay'];
} while ($nextrun < time());
$nexttime = $db->prepare("UPDATE jobs SET nextrun = ? WHERE jobID = ?");
$nexttime->execute(array($nextrun, $result["jobID"]));
$nosave = false;
}
if ((get_configvalue('dbclean.enabled') == 'true') && (get_configvalue('dbclean.lastrun') + (60 * 60 * 24 * get_configvalue('dbclean.delay')) < time())) clean_database();
unlink('/tmp/webcron.lock');
if(file_exists(__DIR__ . "/cache/reboot.trigger")) {
unlink(__DIR__ . "/cache/reboot.trigger");
$count=0;
foreach($rebootjobs as $job) {
print_r($job);
if (!(isset($job['done']) && $job['done'] == true)) {
$rebooter = preg_replace("/reboot /", "", $job['url'], 1);
$rebooter = urlencode($rebooter);
$rebooter = str_replace("cmd%3D", "cmd=", $rebooter);
$rebooter = str_replace("services%3D", "services=", $rebooter);
$rebooter = str_replace("%26", "&", $rebooter);
parse_str($rebooter, $rebootcommands);
$cmd = $rebootcommands['cmd'];
if ($cmd == '') {
$cmd = 'sudo shutdown -r +{m}+ "A reboot has been scheduled. Please save your work."';
}
$cmd = str_replace("{m}+", intdiv(get_configvalue('jobs.rebootwait'), 60), $cmd);
$cmd = str_replace("{s}+", get_configvalue('jobs.rebootwait'), $cmd);
$url = "ssh " . $job['host'] . " '" . $cmd . " &'";
echo $url;
exec($url);
$cmd = '';
$rebootjobs[$count]['done'] = true;
}
$count++;
}
$rebootser = json_encode($rebootjobs);
file_put_contents(__DIR__ . "/cache/get-services.trigger", $rebootser);
file_put_contents(__DIR__ . "/cache/reboot-time.trigger", time() + (get_configvalue('jobs.reboottime') + get_configvalue('jobs.rebootwait')));
}
require_once 'include/finalize.inc.php';