federator/maintenance.php

90 lines
2.6 KiB
PHP
Raw Normal View History

<?php
/**
* SPDX-FileCopyrightText: 2024 Sascha Nitsch (grumpydeveloper) https://contentnation.net/@grumpydevelop
* SPDX-License-Identifier: GPL-3.0-or-later
*
* @author Sascha Nitsch (grumpydeveloper)
**/
function dbupgrade(\Federator\Main $main)
{
$config = $main->getConfig();
$maintenance = $config['maintenance'];
$main->openDatabase($maintenance['username'], $maintenance['password']);
$dbh = $main->getDatabase();
$sql = 'select `value` from settings where `key`="database_version"';
try {
$sth = $dbh->query($sql);
} catch (mysqli_sql_exception) {
$sth = false;
}
$version = '0';
if ($sth !== false) {
$row = $sth->fetch_row();
if ($row) {
$version = $row[0];
}
}
echo "current version: $version\n";
$updateFolder = opendir("sql");
$updates = [];
while (($file = readdir($updateFolder))) {
$matches = [];
if (preg_match('/^(\d{4}-\d{2}-\d{2}).sql$/', $file, $matches) === 1) {
if (strcmp($matches[1], $version) > 0) { // file is newer than our version
$updates[] = $file;
}
}
}
closedir($updateFolder);
sort($updates);
foreach ($updates as $update) {
echo "applying update $update\n";
$u = fopen('sql/' . $update, 'r');
if ($u) {
try {
$dbh->begin_transaction();
// apply updates line by line
while (($line = fgets($u)) !== false) {
$line = trim($line);
$dbh->query($line);
}
$dbh->commit();
} catch (mysqli_sql_exception $e) {
//print_r($e);
echo "error while applying update $update: " . $e->getMessage() . "\n";
}
fclose($u);
}
}
}
function printUsage()
{
echo "usage php maintenance.php <command>\n";
echo "command can be one of:\n";
echo " dbupgrade - this upgrades the db to the most recent version. Run this after you updated the program files\n";
exit();
}
date_default_timezone_set("Europe/Berlin");
spl_autoload_register(static function (string $className) {
$root = array_key_exists('DOCUMENT_ROOT', $_SERVER) ? $_SERVER['DOCUMENT_ROOT'] : '';
// strip Federator from class path
$className = str_replace('Federator\\', '', $className);
include $root . 'php/' . str_replace("\\", "/", strtolower($className)) . '.php';
});
if ($argc < 2) {
printUsage();
}
$main = new \Federator\Main('');
switch ($argv[1]) {
case 'dbupgrade':
dbupgrade($main);
break;
default:
printUsage();
}