Currently we have some license issues. We are working on it.

Commit d892450a authored by noplanman's avatar noplanman Committed by dmorley
Browse files

Improved config and boot script

parent ac3b6a00
......@@ -3,6 +3,9 @@ The format is based on [Keep a Changelog] and this project adheres to [Semantic
## [Unreleased]
### Added
- Added bootstrapping to simplify initialisation of config and database
- Config syntax has changed to array style (#155)
- Added `pghost` config to set database port
### Changed
- Introduce proper changelog format (#189)
- Moved DB migration scripts into `db` folder
......
......@@ -15,15 +15,7 @@ $_format = $_GET['format'] ?? '';
$_method = $_GET['method'] ?? '';
$_callback = $_GET['callback'] ?? '';
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/config.php';
define('PODUPTIME', microtime(true));
// Set up global DB connection.
R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
R::testConnection() || die('Error in DB connection');
R::usePartialBeans(true);
require_once __DIR__ . '/boot.php';
if ($_format === 'georss') {
echo <<<EOF
......
<?php
/**
* Boot the application, loading config and database connection.
*/
declare(strict_types=1);
use RedBeanPHP\R;
/**
* Helper to get config values.
*
* @param null|string $param
* @param null|mixed $default
*
* @return mixed|null
*/
function c(string $param = null, $default = null)
{
static $config;
if ($config === null) {
$config = require __DIR__ . '/config.php';
is_array($config) || die('Invalid config format.');
}
if ($param === null) {
return $config;
}
if (array_key_exists($param, $config)) {
return $config[$param];
}
return $default;
}
define('PODUPTIME', microtime(true));
require_once __DIR__ . '/vendor/autoload.php';
// Set up global DB connection.
R::setup(
sprintf(
'pgsql:host=%s;port=%d;dbname=%s',
c('pghost'),
c('pgport', 5432),
c('pgdb')
),
c('pguser'),
c('pgpass'),
true
);
R::testConnection() || die('Error in DB connection');
R::usePartialBeans(true);
......@@ -4,38 +4,43 @@
* Config for Poduptime.
*/
//backup directory - full dir path
$backup_dir = __DIR__ . '/backup';
return [
//backup directory - full dir path
'backup_dir' => __DIR__ . '/backup',
//log directory - full dir path
$log_dir = __DIR__ . '/log';
//log directory - full dir path
'log_dir' => __DIR__ . '/log',
//location of pg dump - full dir path
$pg_dump_dir = '/usr/bin';
//location of pg dump - full dir path
'pg_dump_dir' => '/usr/bin',
//db host
$pghost = 'localhost';
//db host
'pghost' => 'localhost',
//db username
$pguser = '';
//db port
'pgport' => 5432,
//db password
$pgpass = '';
//db username
'pguser' => '',
//db name
$pgdb = '';
//db password
'pgpass' => '',
//admin email for forms
$adminemail = '';
//db name
'pgdb' => '',
//DNS server for dnssec testing. 1.1.1.1 tests the best
$dnsserver = '';
//admin email for forms
'adminemail' => '',
//CA for curl to use - full file path (pull.sh will update this monthly)
$cafullpath = '';
//DNS server for dnssec testing. 1.1.1.1 tests the best
'dnsserver' => '',
//Mapbox.com API key. https://www.mapbox.com/help/how-access-tokens-work/
$mapboxkey = '';
//CA for curl to use - full file path (pull.sh will update this monthly)
'cafullpath' => '',
//Geolite2-city database file in mmdb format - full file path (pull.sh will update this monthly)
$geoip2db = '';
//Mapbox.com API key. https://www.mapbox.com/help/how-access-tokens-work/
'mapboxkey' => '',
//Geolite2-city database file in mmdb format - full file path (pull.sh will update this monthly)
'geoip2db' => '',
];
......@@ -8,21 +8,9 @@ declare(strict_types=1);
use RedBeanPHP\R;
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../boot.php';
define('PODUPTIME', microtime(true));
// Set up global DB connection.
R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
R::testConnection() || die('Error in DB connection');
R::usePartialBeans(true);
if (!($_domain = $_GET['domain'] ?? null)) {
die('no pod domain given');
}
($_domain = $_GET['domain'] ?? null) || die('no pod domain given');
// Other parameters.
$_email = $_GET['email'] ?? '';
......@@ -43,6 +31,7 @@ try {
die('Error in SQL query: ' . $e->getMessage());
}
$stop = false;
foreach ($pods as $pod) {
if ($pod['domain'] === $_domain) {
if ($pod['email']) {
......@@ -85,12 +74,11 @@ foreach ($pods as $pod) {
</form>
EOF;
$stop = 1;
$stop = true;
}
}
if (!$stop) {
$link = 'https://' . $_domain . '/nodeinfo/1.0';
if ($infos = file_get_contents('https://' . $_domain . '/.well-known/nodeinfo')) {
$info = json_decode($infos, true);
......@@ -113,12 +101,12 @@ if (!$stop) {
$publickey = md5(uniqid($_domain, true));
try {
$p = R::dispense('pods');
$p['domain'] = $_domain;
$p['email'] = $_email;
$p = R::dispense('pods');
$p['domain'] = $_domain;
$p['email'] = $_email;
$p['podmin_statement'] = $_podmin_statement;
$p['podmin_notify'] = $_podmin_notify;
$p['publickey'] = $publickey;
$p['podmin_notify'] = $_podmin_notify;
$p['publickey'] = $publickey;
R::store($p);
} catch (\RedBeanPHP\RedException $e) {
......@@ -126,7 +114,7 @@ if (!$stop) {
}
if ($_email) {
$to = $adminemail;
$to = c('adminemail');
$subject = 'New pod added to ' . $_SERVER['HTTP_HOST'];
$headers = ['From: ' . $_email, 'Reply-To: ' . $_email, 'Cc: ' . $_email];
......@@ -144,4 +132,4 @@ if (!$stop) {
} else {
echo 'Could not validate your pod, check your setup!<br>Take a look at <a href="' . $link . '">your /nodeinfo</a>';
}
}
\ No newline at end of file
}
......@@ -15,15 +15,7 @@ use RedBeanPHP\R;
// Other parameters.
$_format = $_GET['format'] ?? '';
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php';
define('PODUPTIME', microtime(true));
// Set up global DB connection.
R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
R::testConnection() || die('Error in DB connection');
R::usePartialBeans(true);
require_once __DIR__ . '/../boot.php';
try {
$pod = R::getRow('
......
......@@ -11,19 +11,19 @@ if (PHP_SAPI !== 'cli') {
exit;
}
require_once __DIR__ . '/../config.php';
$c = require __DIR__ . '/../config.php';
$keep = (60 * 60 * 6) * 1;
$dump_date = date('Ymd_Hs');
$file_name = $backup_dir . '/dump_' . $dump_date . '.sql';
system("export PGPASSWORD=$pgpass && $pg_dump_dir/pg_dump --clean --format=tar --username=$pguser $pgdb >> $file_name");
echo "pg backup of $pgdb made";
$dirh = dir($backup_dir);
$file_name = "{$c['backup_dir']}/dump_{$dump_date}.sql";
system("export PGPASSWORD={$c['pgpass']} && {$c['pg_dump_dir']}/pg_dump --clean --format=tar --username={$c['pguser']} {$c['pgdb']} >> {$file_name}");
echo "pg backup of {$c['pgdb']} made";
$dirh = dir($c['backup_dir']);
while ($entry = $dirh->read()) {
$old_file_time = (date('U') - $keep);
$file_created = filectime("$backup_dir/$entry");
$old_file_time = date('U') - $keep;
$file_created = filectime("{$c['backup_dir']}/{$entry}");
if ($file_created < $old_file_time && !is_dir($entry)) {
if (unlink("$backup_dir/$entry")) {
if (unlink("{$c['backup_dir']}/{$entry}")) {
echo 'Cleaned up old backups';
}
}
......
......@@ -22,13 +22,7 @@ $_email = $_GET['email'] ?? '';
$_podmin_statement = $_GET['podmin_statement'] ?? '';
$_podmin_notify = $_GET['podmin_notify'] ?? 0;
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php';
// Set up global DB connection.
R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
R::testConnection() || die('Error in DB connection');
R::usePartialBeans(true);
require_once __DIR__ . '/../boot.php';
try {
$pod = R::findOne('pods', 'domain = ?', [$_domain]);
......@@ -89,7 +83,7 @@ if ('save' === $_action) {
}
$to = $_email;
$headers = ['From: ' . $adminemail, 'Cc: ' . $pod['email'], 'Bcc: ' . $adminemail];
$headers = ['From: ' . c('adminemail'), 'Cc: ' . $pod['email'], 'Bcc: ' . c('adminemail')];
$subject = 'Edit notice from poduptime';
$message = 'Data for ' . $_domain . ' updated. If it was not you reply and let me know!';
@mail($to, $subject, $message, implode("\r\n", $headers));
......@@ -149,4 +143,4 @@ Authorized to edit <b><?php echo $_domain; ?></b> for <?php echo (new Carbon($po
<input value="debug" type="button" aria-describedby="debug" data-featherlight="/db/pull.php?debug=1&nowrite=1&domain=<?php echo $_domain; ?>"/>
<small id="debug" class="form-text text-muted">
Do a debug pull of your pod. Won't update the database just show what it would look like on a pass.
</small>
\ No newline at end of file
</small>
......@@ -14,14 +14,7 @@ use RedBeanPHP\R;
// Other parameters.
$_email = $_GET['email'] ?? '';
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php';
// Set up global DB connection.
R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
R::testConnection() || die('Error in DB connection');
R::usePartialBeans(true);
require_once __DIR__ . '/../boot.php';
try {
$pod = R::findOne('pods', 'domain = ?', [$_domain]);
......@@ -33,7 +26,7 @@ try {
// Set up common variables.
$uuid = md5(uniqid($_domain, true));
$link = sprintf('https://%1$s/?edit&domain=%2$s&token=%3$s', $_SERVER['HTTP_HOST'], $_domain, $uuid);
$headers = ['From: ' . $adminemail];
$headers = ['From: ' . c('adminemail')];
$message_lines = [];
if ($_email) {
......@@ -41,7 +34,7 @@ if ($_email) {
$to = $_email;
$subject = 'Temporary edit key for ' . $_SERVER['HTTP_HOST'];
$headers[] = 'Bcc: ' . $adminemail;
$headers[] = 'Bcc: ' . c('adminemail');
$expire = time() + 8700;
$output = 'Link sent to your email.';
} elseif (!$pod['email']) {
......@@ -49,7 +42,7 @@ if ($_email) {
} else {
$to = $pod['email'];
$subject = 'Temporary edit key for ' . $_SERVER['HTTP_HOST'];
$headers[] = 'Bcc: ' . $adminemail;
$headers[] = 'Bcc: ' . c('adminemail');
$message_lines[] = 'Looks like you did not enter your email address, be sure to update it if you forgot the one we have for you.';
$message_lines[] = 'Email found: ' . $pod['email'];
$expire = time() + 8700;
......
......@@ -13,15 +13,7 @@ if (PHP_SAPI !== 'cli') {
use RedBeanPHP\R;
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php';
define('PODUPTIME', microtime(true));
// Set up global DB connection.
R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
R::testConnection() || die('Error in DB connection');
R::usePartialBeans(true);
require_once __DIR__ . '/../boot.php';
try {
$monthly_totals = R::getAll("
......@@ -39,8 +31,8 @@ try {
} catch (\RedBeanPHP\RedException $e) {
die('Error in SQL query: ' . $e->getMessage());
}
foreach ($monthly_totals as $monthly) {
foreach ($monthly_totals as $monthly) {
// Format date to timestamp.
$timestamp = $monthly['yymm'] . '-01 01:01:01-01';
......
......@@ -13,15 +13,7 @@ if (PHP_SAPI !== 'cli') {
use RedBeanPHP\R;
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php';
define('PODUPTIME', microtime(true));
// Set up global DB connection.
R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
R::testConnection() || die('Error in DB connection');
R::usePartialBeans(true);
require_once __DIR__ . '/../boot.php';
try {
$sql = '
......
......@@ -13,15 +13,7 @@ if (PHP_SAPI !== 'cli') {
use RedBeanPHP\R;
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php';
define('PODUPTIME', microtime(true));
// Set up global DB connection.
R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
R::testConnection() || die('Error in DB connection');
R::usePartialBeans(true);
require_once __DIR__ . '/../boot.php';
$softwares = [
'diaspora' => ['repo' => 'diaspora/diaspora', 'gitsite' => 'api.github.com', 'gittype' => 'github', 'devbranch' => 'develop'],
......@@ -39,11 +31,11 @@ $opts = [
];
foreach ($softwares as $software => $details) {
if ($details['gittype'] == 'github') {
if ($details['gittype'] === 'github') {
$context = stream_context_create($opts);
$releasejson = json_decode(file_get_contents('https://' . $details["gitsite"] . '/repos/' . $details["repo"] . '/releases/latest', false, $context));
if ($details["devbranch"]) {
$commitjson = json_decode(file_get_contents('https://' . $details["gitsite"] . '/repos/' . $details["repo"] . '/commits/' . $details["devbranch"], false, $context));
$releasejson = json_decode(file_get_contents('https://' . $details['gitsite'] . '/repos/' . $details['repo'] . '/releases/latest', false, $context));
if ($details['devbranch']) {
$commitjson = json_decode(file_get_contents('https://' . $details['gitsite'] . '/repos/' . $details['repo'] . '/commits/' . $details['devbranch'], false, $context));
} else {
$commitjson = '';
}
......@@ -63,11 +55,11 @@ foreach ($softwares as $software => $details) {
die('Error in SQL query: ' . $e->getMessage());
}
}
} elseif ($details['gittype'] == 'gitlab') {
} elseif ($details['gittype'] === 'gitlab') {
$context = stream_context_create($opts);
$releasejson = json_decode(file_get_contents('https://' . $details["gitsite"] . '/api/v4/projects/' . $details["repo"] . '/repository/tags', false, $context));
if ($details["devbranch"]) {
$commitjson = json_decode(file_get_contents('https://' . $details["gitsite"] . '/api/v4/projects/' . $details["repo"] . '/repository/commits/' . $details["devbranch"], false, $context));
$releasejson = json_decode(file_get_contents('https://' . $details['gitsite'] . '/api/v4/projects/' . $details['repo'] . '/repository/tags', false, $context));
if ($details['devbranch']) {
$commitjson = json_decode(file_get_contents('https://' . $details['gitsite'] . '/api/v4/projects/' . $details['repo'] . '/repository/commits/' . $details['devbranch'], false, $context));
} else {
$commitjson = '';
}
......@@ -89,6 +81,5 @@ foreach ($softwares as $software => $details) {
}
}
printf('%s:%s:%s ', $software, $masterversion, $devlastcommit ?: 'n/a');
}
......@@ -30,20 +30,13 @@ $_domain = $_GET['domain'] ?? null;
// Must have a domain, except if called from CLI.
$_domain || PHP_SAPI === 'cli' || die('No valid input');
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../boot.php';
define('PODUPTIME', microtime(true));
// Set up global DB connection.
R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
$sqldebug && R::debug(true);
R::testConnection() || die('Error in DB connection');
R::usePartialBeans(true);
$sqldebug && R::fancyDebug(true);
try {
// Setup GeoIP Database
$reader = new Reader($geoip2db);
$reader = new Reader(c('geoip2db'));
$sql = '
SELECT domain, score, date_created, weight, podmin_notify, email, masterversion, shortversion, status
......@@ -114,7 +107,7 @@ foreach ($pods as $pod) {
curl_setopt($chss, CURLOPT_TIMEOUT, 30);
curl_setopt($chss, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($chss, CURLOPT_CERTINFO, 1);
curl_setopt($chss, CURLOPT_CAINFO, $cafullpath);
curl_setopt($chss, CURLOPT_CAINFO, c('cafullpath'));
$outputssl = curl_exec($chss);
$outputsslerror = curl_error($chss);
$info = curl_getinfo($chss, CURLINFO_CERTINFO);
......@@ -297,7 +290,7 @@ foreach ($pods as $pod) {
_debug('Signup Open', $signup);
$dnsserver = !empty($dnsserver) ? $dnsserver : '1.1.1.1';
$dnsserver = c('dnsserver') ?: '1.1.1.1';
$delv = new NPM\Xec\Command("delv @{$dnsserver} {$domain}");
$delv->throwExceptionOnError(false);
......@@ -355,7 +348,7 @@ foreach ($pods as $pod) {
if ($score == 49 && $notify && !$develop && $dbscore == 50) {
$to = $email;
$headers = ['From: ' . $adminemail, 'Bcc: ' . $adminemail];
$headers = ['From: ' . c('adminemail'), 'Bcc: ' . c('adminemail')];
$subject = 'Monitoring notice from poduptime';
$message = 'Notice for ' . $domain . '. Your score is ' . $score . ' and your pod will fall off the list soon.';
@mail($to, $subject, $message, implode("\r\n", $headers));
......
......@@ -46,14 +46,14 @@ if [ "$HOUR" = 23 ] || [ "$1" = 'init' ]; then
fi
if [ "$DAY" = 23 ] || [ "$1" = 'init' ]; then
printf "%s" "Updating CA..."
CACERT_FILE="$(php -r "include __DIR__ . '/../config.php'; echo \$cafullpath;")"
CACERT_FILE="$(php -r "echo (require __DIR__ . '/../config.php')['cafullpath'];")"
if curl -Lss https://curl.haxx.se/ca/cacert.pem -o "$CACERT_FILE"; then
echo "$HAPPY"
else
echo "$SAD"
fi
printf "%s" "Updating GeoIP2 DB..."
GEODB_FILE="$(php -r "include __DIR__ . '/../config.php'; echo \$geoip2db;")"
GEODB_FILE="$(php -r "echo (require __DIR__ . '/../config.php')['geoip2db'];")"
if funzip <(curl -Lss http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz) > "$GEODB_FILE"; then
echo "$HAPPY"
else
......
......@@ -15,15 +15,7 @@ use RedBeanPHP\R;
($_comment = $_POST['comment'] ?? null) || die('A comment is required');
($_rating = $_POST['rating'] ?? null) || die('A rating is required');
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php';
define('PODUPTIME', microtime(true));
// Set up global DB connection.
R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
R::testConnection() || die('Error in DB connection');
R::usePartialBeans(true);
require_once __DIR__ . '/../boot.php';
try {
$r = R::dispense('ratingcomments');
......
......@@ -6,7 +6,7 @@
declare(strict_types=1);
$dur = (time() - filemtime('last.data'));
$dur = time() - filemtime('last.data');
echo $dur;
if ($dur > 4500) {
http_response_code(500);
......
......@@ -13,15 +13,7 @@ use RedBeanPHP\R;
// Other parameters.
$_domain = $_GET['domain'] ?? '';
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/config.php';
define('PODUPTIME', microtime(true));
// Set up global DB connection.
R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
R::testConnection() || die('Error in DB connection');
R::usePartialBeans(true);
require_once __DIR__ . '/boot.php';
try {
if ($_domain) {
......
......@@ -5,21 +5,22 @@
*/
declare(strict_types=1);
use Carbon\Carbon;
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/boot.php';
$lastfile = 'db/last.data';
$input = isset($_GET['input']) ? substr($_GET['input'], 1) : null;
$mapview = isset($_GET['mapview']) || $input == 'map';
$statsview = isset($_GET['statsview']) || $input == 'stats';
$podmin = isset($_GET['podmin']) || $input == 'podmin';
$podminedit = isset($_GET['podminedit']) || $input == 'podminedit';
$edit = isset($_GET['edit']) || $input == 'edit';
$add = isset($_GET['add']) || $input == 'add';
$gettoken = isset($_GET['gettoken']) || $input == 'gettoken';
$simpleview = !($mapview || $podmin || $podminedit || $statsview);
$lastfile = 'db/last.data';
$input = isset($_GET['input']) ? substr($_GET['input'], 1) : null;
$mapview = isset($_GET['mapview']) || $input === 'map';
$statsview = isset($_GET['statsview']) || $input === 'stats';
$podmin = isset($_GET['podmin']) || $input === 'podmin';
$podminedit = isset($_GET['podminedit']) || $input === 'podminedit';
$edit = isset($_GET['edit']) || $input === 'edit';
$add = isset($_GET['add']) || $input === 'add';
$gettoken = isset($_GET['gettoken']) || $input === 'gettoken';
$simpleview = !($mapview || $podmin || $podminedit || $statsview);
$fullview = false;
?>
<!doctype html>
<html lang="en">
......@@ -68,16 +69,16 @@ $navs = [
<h4 class="text-white">About</h4>
<p class="text-muted">Poduptime helps you find a diaspora, friendica, hubzilla or socialhome pod to use and join the federated social network.</p>
<ul class="navbar-nav">
<?php
foreach ($navs['links'] as $nav_item) {
printf(
'<li class="nav-item"><a href="%1$s">%2$s%3$s</a></li>',
$nav_item['href'],
$nav_item['text'],