Commit 7abdd377 authored by noplanman's avatar noplanman Committed by David Morley

Use Redbean as DBAL (#118)

* Add doctrine/dbal to the mix.

* Change main pages to use new DB connection with doctrine DBAL.
Rename some variables to improve readability.

* Use function arguments instead of array.

* Use doctrine DBAL for db scripts.

* Use DBAL for pull.php.

* Use DBAL for go.php.

* Use DBAL for rate.php.

* Use DBAL for podstat.php.

* Use DBAL for api.php and api-more.php.

* Convert all pod fields to string.

* Move from Doctrine DBAL to RedBeans.

* Add temporary fix for boolean property in pull.php

* Add dedicated migration script for adding id column as unique primary key.
parent 39349068
<?php <?php
//Copyright (c) 2011, David Morley. This file is licensed under the Affero General Public License version 3 or later. See the COPYRIGHT file. //Copyright (c) 2011, David Morley. This file is licensed under the Affero General Public License version 3 or later. See the COPYRIGHT file.
use RedBeanPHP\R;
($_GET['key'] ?? null) === '4r45tg' || die; ($_GET['key'] ?? null) === '4r45tg' || die;
// Other parameters. // Other parameters.
...@@ -7,10 +10,14 @@ $_format = $_GET['format'] ?? ''; ...@@ -7,10 +10,14 @@ $_format = $_GET['format'] ?? '';
$_method = $_GET['method'] ?? ''; $_method = $_GET['method'] ?? '';
$_callback = $_GET['callback'] ?? ''; $_callback = $_GET['callback'] ?? '';
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/config.php'; require_once __DIR__ . '/config.php';
$dbh = pg_connect("dbname=$pgdb user=$pguser password=$pgpass"); define('PODUPTIME', microtime(true));
$dbh || die('Error in connection: ' . pg_last_error());
// Set up global DB connection.
R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
R::testConnection() || die('Error in DB connection');
if ($_format === 'georss') { if ($_format === 'georss') {
echo <<<EOF echo <<<EOF
...@@ -21,50 +28,58 @@ if ($_format === 'georss') { ...@@ -21,50 +28,58 @@ if ($_format === 'georss') {
<link href="https://{$_SERVER['HTTP_HOST']}/"/> <link href="https://{$_SERVER['HTTP_HOST']}/"/>
EOF; EOF;
$sql = "SELECT name,monthsmonitored,responsetimelast7,uptimelast7,dateupdated,score,domain,country,lat,long FROM pods_apiv1";
$result = pg_query($dbh, $sql); try {
$result || die('Error in SQL query: ' . pg_last_error()); $pods = R::getAll('
SELECT name, monthsmonitored, responsetimelast7, uptimelast7, dateupdated, score, domain, country, lat, long
$numrows = pg_num_rows($result); FROM pods_apiv1
while ($row = pg_fetch_array($result)) { ');
$pod_name = htmlentities($row['name'], ENT_QUOTES); } catch (\RedBeanPHP\RedException $e) {
$summary = sprintf( die('Error in SQL query: ' . $e->getMessage());
}
foreach ($pods as $pod) {
$summary = sprintf(
'This pod %1$s has been watched for %2$s months and its average ping time is %3$s with uptime of %4$s%% this month and was last checked on %5$s. On a score of 100 this pod is a %6$s right now', 'This pod %1$s has been watched for %2$s months and its average ping time is %3$s with uptime of %4$s%% this month and was last checked on %5$s. On a score of 100 this pod is a %6$s right now',
$pod_name, htmlentities($pod['name'], ENT_QUOTES),
$row['monthsmonitored'], $pod['monthsmonitored'],
$row['responsetimelast7'], $pod['responsetimelast7'],
$row['uptimelast7'], $pod['uptimelast7'],
$row['dateupdated'], $pod['dateupdated'],
$row['score'] $pod['score']
); );
echo <<<EOF echo <<<EOF
<entry> <entry>
<title>https://{$row['domain']}</title> <title>https://{$pod['domain']}</title>
<link href="{$scheme}{$row['domain']}"/> <link href="https://{$pod['domain']}"/>
<id>urn:{$row['domain']}</id> <id>urn:{$pod['domain']}</id>
<summary>Pod Location is: {$row['country']} <summary>Pod Location is: {$pod['country']}
&#xA; &#xA;
{$summary}</summary> {$summary}</summary>
<georss:point>{$row['lat']} {$row['long']}</georss:point> <georss:point>{$pod['lat']} {$pod['long']}</georss:point>
<georss:featureName>{$row['domain']}</georss:featureName> <georss:featureName>{$pod['domain']}</georss:featureName>
</entry> </entry>
EOF; EOF;
} }
echo '</feed>'; echo '</feed>';
} elseif ($_format === 'json') { } elseif ($_format === 'json') {
$sql = 'SELECT id,domain,status,secure,score,userrating,adminrating,city,state,country,lat,long,ip,ipv6,pingdomurl,monthsmonitored,uptimelast7,responsetimelast7,local_posts,comment_counts,dateCreated,dateUpdated,dateLaststats,hidden FROM pods_apiv1';
$result = pg_query($dbh, $sql); try {
$result || die('Error in SQL query: ' . pg_last_error()); $pods = R::getAll('
SELECT id, domain, status, secure, score, userrating, adminrating, city, state, country, lat, long, ip, ipv6, pingdomurl, monthsmonitored, uptimelast7, responsetimelast7, local_posts, comment_counts, dateCreated, dateUpdated, dateLaststats, hidden
FROM pods_apiv1
');
} catch (\RedBeanPHP\RedException $e) {
die('Error in SQL query: ' . $e->getMessage());
}
//json output, thx Vipul A M for fixing this //json output, thx Vipul A M for fixing this
header('Content-type: application/json'); header('Content-type: application/json');
$numrows = pg_num_rows($result); $obj = [
$rows = array_values(pg_fetch_all($result)); 'podcount' => count($pods),
$obj = [ 'pods' => allToString($pods),
'podcount' => $numrows,
'pods' => $rows,
]; ];
if ($_method === 'jsonp') { if ($_method === 'jsonp') {
print $_callback . '(' . json_encode($obj) . ')'; print $_callback . '(' . json_encode($obj) . ')';
...@@ -72,20 +87,51 @@ EOF; ...@@ -72,20 +87,51 @@ EOF;
print json_encode($obj); print json_encode($obj);
} }
} else { } else {
$i = 0; try {
$sql = "SELECT domain,uptimelast7,country FROM pods_apiv1"; $pods = R::getAll('
$result = pg_query($dbh, $sql); SELECT domain, uptimelast7, country
$result || die('Error in SQL query: ' . pg_last_error()); FROM pods_apiv1
');
$numrows = pg_num_rows($result); } catch (\RedBeanPHP\RedException $e) {
while ($row = pg_fetch_array($result)) { die('Error in SQL query: ' . $e->getMessage());
}
$i = 0;
foreach ($pods as $pod) {
$i++ > 0 && print ','; $i++ > 0 && print ',';
printf( printf(
'%1$s Up %2$s%% This Month - Located in: %3$s', '%1$s Up %2$s%% This Month - Located in: %3$s',
$row['domain'], $pod['domain'],
$row['uptimelast7'], $pod['uptimelast7'],
$row['country'] $pod['country']
); );
} }
} }
/**
* Convert all passed items to strings.
*
* This method is for backwards compatibility of APIv1 only!
* After v2 is released and stable, this can safely be removed.
*
* @param array $arr List of all elements to stringify.
*
* @return array
*/
function allToString(array $arr)
{
$ret = $arr;
foreach ($ret as &$item) {
if (is_array($item)) {
/** @var array $item */
foreach ($item as &$field) {
$field !== null && $field = (string) $field;
}
} else {
$item !== null && $item = (string) $item;
}
unset($field, $item);
}
return $ret;
}
<?php <?php
require_once __DIR__ . '/config.php';
$dbh = pg_connect("dbname=$pgdb user=$pguser password=$pgpass"); use RedBeanPHP\R;
$dbh || die('Error in connection: ' . pg_last_error());
$sql = "SELECT domain,masterversion,shortversion,softwarename,monthsmonitored,score,signup,secure,name,country,city,state,lat,long,uptime_alltime,active_users_halfyear,active_users_monthly,service_facebook,service_twitter,service_tumblr,service_wordpress,service_xmpp,latency,date_updated,ipv6,total_users,local_posts,comment_counts,stats_apikey,userrating,sslvalid FROM pods WHERE score < 50 ORDER BY weightedscore"; defined('PODUPTIME') || die();
$result = pg_query($dbh, $sql);
$result || die('Error in SQL query: ' . pg_last_error()); try {
$numrows = pg_num_rows($result); $pods = R::getAll('
SELECT domain, masterversion, shortversion, monthsmonitored, score, signup, name, uptime_alltime, active_users_halfyear, active_users_monthly, latency, date_updated, total_users, local_posts, comment_counts, stats_apikey, sslvalid
FROM pods
WHERE score < 50
ORDER BY weightedscore ASC
');
} catch (\RedBeanPHP\RedException $e) {
die('Error in SQL query: ' . $e->getMessage());
}
?> ?>
<meta property="og:title" content="<?php echo $numrows; ?> #Diaspora Pods listed, Come see the privacy aware social network."/><?php echo $numrows; ?> pods that are open for signup now. <meta property="og:title" content="<?php echo count($pods); ?> #Diaspora Pods listed, Come see the privacy aware social network."/><?php echo count($pods); ?> pods that are open for signup now.
<meta charset="utf-8"> <meta charset="utf-8">
<!-- /* Copyright (c) 2011, David Morley. This file is licensed under the Affero General Public License version 3 or later. See the COPYRIGHT file. */ --> <!-- /* Copyright (c) 2011, David Morley. This file is licensed under the Affero General Public License version 3 or later. See the COPYRIGHT file. */ -->
<div class="table-responsive"> <div class="table-responsive">
...@@ -36,59 +42,60 @@ $numrows = pg_num_rows($result); ...@@ -36,59 +42,60 @@ $numrows = pg_num_rows($result);
<tbody> <tbody>
<?php <?php
$tt = 0; $tt = 0;
while ($row = pg_fetch_array($result)) {
foreach ($pods as $pod) {
$tt++; $tt++;
$verdiff = str_replace('.', '', $row['masterversion']) - str_replace('.', '', $row['shortversion']); $verdiff = (int) str_replace('.', '', $pod['masterversion']) - (int) str_replace('.', '', $pod['shortversion']);
$pod_name = htmlentities($row['name'], ENT_QUOTES); $pod_name = htmlentities($pod['name'], ENT_QUOTES);
$tip = sprintf( $tip = sprintf(
'This pod %1$s has been watched for %2$s months and its average ping time is %3$s with uptime of %4$s%% this month and was last checked on %5$s. On a score of -20 to +20 this pod is a %6$s right now', 'This pod %1$s has been watched for %2$s months and its average ping time is %3$s with uptime of %4$s%% this month and was last checked on %5$s. On a score of -20 to +20 this pod is a %6$s right now',
$pod_name, $pod_name,
$row['monthsmonitored'], $pod['monthsmonitored'],
$row['latency'], $pod['latency'],
$row['uptime_alltime'], $pod['uptime_alltime'],
$row['date_updated'], $pod['date_updated'],
$row['score'] $pod['score']
); );
echo '<tr><td><a class="text-success" target="_self" href="https://' . $row['domain'] . '">' . $row['domain'] . '<div title="' . $tip . '" class="tipsy" style="display: inline-block">?</div></a></td>'; echo '<tr><td><a class="text-success" target="_self" href="https://' . $pod['domain'] . '">' . $pod['domain'] . '<div title="' . $tip . '" class="tipsy" style="display: inline-block">?</div></a></td>';
if (stristr($row['shortversion'], 'head')) { if (stristr($pod['shortversion'], 'head')) {
$version = '.dev'; $version = '.dev';
$pre = 'This pod runs pre release development code'; $pre = 'This pod runs pre release development code';
} elseif (!$row['shortversion']) { } elseif (!$pod['shortversion']) {
$version = '0'; $version = '0';
$pre = 'This pod runs unknown code'; $pre = 'This pod runs unknown code';
} else { } else {
$version = $row['shortversion']; $version = $pod['shortversion'];
$pre = 'This pod runs production code'; $pre = 'This pod runs production code';
} }
if ($row['shortversion'] === $row['masterversion'] && $row['shortversion'] !== '') { if ($pod['shortversion'] === $pod['masterversion'] && $pod['shortversion'] !== '') {
$classver = 'text-success'; $classver = 'text-success';
} elseif ($verdiff > 6) { } elseif ($verdiff > 6) {
$classver = 'text-warning'; $classver = 'text-warning';
} else { } else {
$classver = 'black'; $classver = 'black';
} }
echo '<td class="' . $classver . '"><div title="' . $pre . ' codename: ' . $row['shortversion'] . ' master version is: ' . $row['masterversion'] . '" class="tipsy">' . $version . '</div></td>'; echo '<td class="' . $classver . '"><div title="' . $pre . ' codename: ' . $pod['shortversion'] . ' master version is: ' . $pod['masterversion'] . '" class="tipsy">' . $version . '</div></td>';
echo '<td>' . $row['uptime_alltime'] . '</td>'; echo '<td>' . $pod['uptime_alltime'] . '</td>';
echo '<td>' . $row['latency'] . '</td>'; echo '<td>' . $pod['latency'] . '</td>';
echo '<td>' . ($row['signup'] === 't' ? 'Open' : 'Closed') . '</td>'; echo '<td>' . ($pod['signup'] ? 'Open' : 'Closed') . '</td>';
echo '<td>' . $row['total_users'] . '</td>'; echo '<td>' . $pod['total_users'] . '</td>';
echo '<td>' . $row['active_users_halfyear'] . '</td>'; echo '<td>' . $pod['active_users_halfyear'] . '</td>';
echo '<td>' . $row['active_users_monthly'] . '</td>'; echo '<td>' . $pod['active_users_monthly'] . '</td>';
echo '<td>' . $row['local_posts'] . '</td>'; echo '<td>' . $pod['local_posts'] . '</td>';
echo '<td>' . $row['comment_counts'] . '</td>'; echo '<td>' . $pod['comment_counts'] . '</td>';
$moreurl = 'https://api.uptimerobot.com/getMonitors?format=json&noJsonCallback=1&customUptimeRatio=7-30-60-90&apiKey=' . $row['stats_apikey']; $moreurl = 'https://api.uptimerobot.com/getMonitors?format=json&noJsonCallback=1&customUptimeRatio=7-30-60-90&apiKey=' . $pod['stats_apikey'];
echo '<td><div title="Last Check ' . $row['date_updated'] . '" class="tipsy"><a target="_self" href="' . $moreurl . '">' . $row['monthsmonitored'] . '</a></div></td>'; echo '<td><div title="Last Check ' . $pod['date_updated'] . '" class="tipsy"><a target="_self" href="' . $moreurl . '">' . $pod['monthsmonitored'] . '</a></div></td>';
echo '<td>' . $row['score'] . '</td>'; echo '<td>' . $pod['score'] . '</td>';
echo '<td><div class="tipsy" title="' . $row['sslvalid'] . '">con info</td>'; echo '<td><div class="tipsy" title="' . $pod['sslvalid'] . '">con info</td>';
?> ?>
<td> <td>
<form method="post" action="db/kill.php" target="_blank"> <form method="post" action="db/kill.php" target="_blank">
<input type="hidden" name="domain" value="<?php echo $row['domain']; ?>"> <input type="hidden" name="domain" value="<?php echo $pod['domain']; ?>">
<input type="hidden" name="adminkey" value="<?php echo $_COOKIE['adminkey']; ?>"> <input type="hidden" name="adminkey" value="<?php echo $_COOKIE['adminkey']; ?>">
<label>Comments<input name="comments" value="<?php echo $row['sslvalid']; ?>" size="10"></label> <label>Comments<input name="comments" value="<?php echo $pod['sslvalid']; ?>" size="10"></label>
<label><input type="radio" name="action" value="warn">warn</label> <label><input type="radio" name="action" value="warn">warn</label>
<label><input type="radio" name="action" value="delete">delete</label> <label><input type="radio" name="action" value="delete">delete</label>
<input type="submit" value="Process"> <input type="submit" value="Process">
......
...@@ -4,8 +4,49 @@ ...@@ -4,8 +4,49 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "ebe2243c0fd188ec12ddf7a9f99980ad", "content-hash": "8e8b0627248a269ae9d624bef32e61d6",
"packages": [ "packages": [
{
"name": "gabordemooij/redbean",
"version": "v4.3.3",
"source": {
"type": "git",
"url": "https://github.com/gabordemooij/redbean.git",
"reference": "1c7ec69850e9f7966ff7feb87b01d8f43a9753d3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/gabordemooij/redbean/zipball/1c7ec69850e9f7966ff7feb87b01d8f43a9753d3",
"reference": "1c7ec69850e9f7966ff7feb87b01d8f43a9753d3",
"shasum": ""
},
"require": {
"php": ">=5.3.4"
},
"type": "library",
"autoload": {
"psr-4": {
"RedBeanPHP\\": "RedBeanPHP"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"New BSD and GPLv2"
],
"authors": [
{
"name": "Gabor de Mooij",
"email": "gabor@redbeanphp.com",
"homepage": "http://redbeanphp.com"
}
],
"description": "RedBeanPHP ORM",
"homepage": "http://redbeanphp.com/",
"keywords": [
"orm"
],
"time": "2016-10-03T21:25:17+00:00"
},
{ {
"name": "noplanman/xec", "name": "noplanman/xec",
"version": "v0.1.0", "version": "v0.1.0",
......
...@@ -6,6 +6,8 @@ $backup_dir = '/backup'; ...@@ -6,6 +6,8 @@ $backup_dir = '/backup';
$log_dir = '/log'; $log_dir = '/log';
//location of pg dump //location of pg dump
$pg_dump_dir = '/usr/bin'; $pg_dump_dir = '/usr/bin';
//db host
$pghost = 'localhost';
//db username //db username
$pguser = ''; $pguser = '';
//db password //db password
......
<!-- /* Copyright (c) 2011, David Morley. This file is licensed under the Affero General Public License version 3 or later. See the COPYRIGHT file. */ --> <!-- /* Copyright (c) 2011, David Morley. This file is licensed under the Affero General Public License version 3 or later. See the COPYRIGHT file. */ -->
<?php <?php
use RedBeanPHP\R;
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../logging.php'; require_once __DIR__ . '/../logging.php';
require_once __DIR__ . '/../config.php'; require_once __DIR__ . '/../config.php';
define('PODUPTIME', microtime(true));
$log = new Logging(); $log = new Logging();
$log->lfile(__DIR__ . '/../' . $log_dir . '/add.log'); $log->lfile(__DIR__ . '/../' . $log_dir . '/add.log');
if (!($_domain = $_GET['domain'] ?? null)) { if (!($_domain = $_GET['domain'] ?? null)) {
...@@ -9,6 +16,7 @@ if (!($_domain = $_GET['domain'] ?? null)) { ...@@ -9,6 +16,7 @@ if (!($_domain = $_GET['domain'] ?? null)) {
die('no pod domain given'); die('no pod domain given');
} }
// Other parameters.
$_email = $_GET['email'] ?? ''; $_email = $_GET['email'] ?? '';
$_podmin_statement = $_GET['podmin_statement'] ?? ''; $_podmin_statement = $_GET['podmin_statement'] ?? '';
$_podmin_notify = $_GET['podmin_notify'] ?? 0; $_podmin_notify = $_GET['podmin_notify'] ?? 0;
...@@ -18,29 +26,41 @@ if (!filter_var(gethostbyname($_domain), FILTER_VALIDATE_IP)) { ...@@ -18,29 +26,41 @@ if (!filter_var(gethostbyname($_domain), FILTER_VALIDATE_IP)) {
die('Could not validate the domain name, be sure to enter it as "domain.com" (no caps, no slashes, no extras)'); die('Could not validate the domain name, be sure to enter it as "domain.com" (no caps, no slashes, no extras)');
} }
$dbh = pg_connect("dbname=$pgdb user=$pguser password=$pgpass"); // Set up global DB connection.
$dbh || die('Error in connection: ' . pg_last_error()); R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
R::testConnection() || die('Error in DB connection');
$sql = 'SELECT domain, stats_apikey, publickey, email FROM pods'; try {
$result = pg_query($dbh, $sql); $pods = R::getAll('
$result || die('Error in SQL query: ' . pg_last_error()); SELECT id, domain, stats_apikey, publickey, email
FROM pods
');
} catch (\RedBeanPHP\RedException $e) {
die('Error in SQL query: ' . $e->getMessage());
}
while ($row = pg_fetch_array($result)) { foreach ($pods as $pod) {
if ($row['domain'] === $_domain ) { if ($pod['domain'] === $_domain) {
if ($row['email']) { if ($pod['email']) {
$log->lwrite('domain already exists and is registered to an owner' . $_domain); $log->lwrite('domain already exists and is registered to an owner' . $_domain);
die('domain already exists and is registered to an owner, use the edit function to modify'); die('domain already exists and is registered to an owner, use the edit function to modify');
} }
$digtxt = exec(escapeshellcmd('dig ' . $_domain . ' TXT +short')); $digtxt = exec(escapeshellcmd('dig ' . $_domain . ' TXT +short'));
if (strpos($digtxt, $row['publickey']) !== false) { if (strpos($digtxt, $pod['publickey']) !== false) {
echo 'domain validated, you can now add details '; echo 'domain validated, you can now add details ';
$uuid = md5(uniqid($_domain, true)); $uuid = md5(uniqid($_domain, true));
$expire = time() + 2700; $expire = time() + 2700;
$sql = 'UPDATE pods SET token = $1, tokenexpire = $2 WHERE domain = $3';
$result = pg_query_params($dbh, $sql, [$uuid, date('Y-m-d H:i:s', $expire), $_domain]); try {
$result || die('Error in SQL query: ' . pg_last_error()); $p = R::findOne('pods', $pod['id']);
$p['token'] = $uuid;
$p['tokenexpire'] = date('Y-m-d H:i:s', $expire);
R::store($p);
} catch (\RedBeanPHP\RedException $e) {
die('Error in SQL query: ' . $e->getMessage());
}
echo <<<EOF echo <<<EOF
<form action="edit.php" method="get"> <form action="edit.php" method="get">
<input type="hidden" name="domain" value="{$_domain}"> <input type="hidden" name="domain" value="{$_domain}">
...@@ -51,11 +71,11 @@ while ($row = pg_fetch_array($result)) { ...@@ -51,11 +71,11 @@ while ($row = pg_fetch_array($result)) {
<input type="submit" name="action" value="save"> <input type="submit" name="action" value="save">
</form> </form>
EOF; EOF;
die; die;
} else { } else {
$log->lwrite('domain already exists and can be registered' . $_domain); $log->lwrite('domain already exists and can be registered' . $_domain);
die('domain already exists, you can claim the domain by adding a DNS TXT record that states<br><b> ' . $_domain . ' IN TXT "' . $row['publickey'] . '"</b>'); die('domain already exists, you can claim the domain by adding a DNS TXT record that states<br><b> ' . $_domain . ' IN TXT "' . $pod['publickey'] . '"</b>');
} }
} }
} }
...@@ -74,10 +94,19 @@ if (stristr($outputssl, 'openRegistrations')) { ...@@ -74,10 +94,19 @@ if (stristr($outputssl, 'openRegistrations')) {
$log->lwrite('Your pod has ssl and is valid ' . $_domain); $log->lwrite('Your pod has ssl and is valid ' . $_domain);
echo 'Your pod has ssl and is valid<br>'; echo 'Your pod has ssl and is valid<br>';
$publickey = md5(uniqid($domain, true)); $publickey = md5(uniqid($_domain, true));
$sql = 'INSERT INTO pods (domain, email, podmin_statement, podmin_notify, publickey) VALUES ($1, $2, $3, $4, $5)';
$result = pg_query_params($dbh, $sql, [$_domain, $_email, $_podmin_statement, $_podmin_notify, $publickey]); try {
$result || die('Error in SQL query: ' . pg_last_error()); $p = R::dispense('pods');
$p['domain'] = $_domain;
$p['email'] = $_email;
$p['podmin_statement'] = $_podmin_statement;
$p['podmin_notify'] = $_podmin_notify;
$p['publickey'] = $publickey;
R::store($p);
} catch (\RedBeanPHP\RedException $e) {
die('Error in SQL query: ' . $e->getMessage());
}
if ($_email) { if ($_email) {
$to = $adminemail; $to = $adminemail;
...@@ -94,7 +123,7 @@ if (stristr($outputssl, 'openRegistrations')) { ...@@ -94,7 +123,7 @@ if (stristr($outputssl, 'openRegistrations')) {
@mail($to, $subject, implode("\r\n", $message_lines), implode("\r\n", $headers)); @mail($to, $subject, implode("\r\n", $message_lines), implode("\r\n", $headers));
} }
echo 'Data successfully inserted! Your pod will be reviewed and live on the list in a few hours!'; echo 'Data successfully inserted! Your pod will be reviewed and live on the list in a few hours!';
} else { } else {
......
...@@ -2,33 +2,43 @@ ...@@ -2,33 +2,43 @@
//Copyright (c) 2011, David Morley. This file is licensed under the Affero General Public License version 3 or later. See the COPYRIGHT file. //Copyright (c) 2011, David Morley. This file is licensed under the Affero General Public License version 3 or later. See the COPYRIGHT file.
//this is just a single api for a pod for the android app to get data //this is just a single api for a pod for the android app to get data
use RedBeanPHP\R;
// Required parameters. // Required parameters.
($_domain = $_GET['domain'] ?? null) || die('no domain given'); ($_domain = $_GET['domain'] ?? null) || die('no domain given');
// Other parameters. // Other parameters.
$_format = $_GET['format'] ?? ''; $_format = $_GET['format'] ?? '';
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php'; require_once __DIR__ . '/../config.php';
$dbh = pg_connect("dbname=$pgdb user=$pguser password=$pgpass"); define('PODUPTIME', microtime(true));
$dbh || die('Error in connection: ' . pg_last_error());
// Set up global DB connection.
$sql = 'SELECT hgitdate,id,domain,status,secure,score,userrating,adminrating,city,state,country,lat,long,ip,ipv6,pingdomurl,monthsmonitored,uptimelast7,responsetimelast7,local_posts,comment_counts,dateCreated,dateUpdated,dateLaststats,hidden FROM pods_apiv1 WHERE domain = $1'; R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
$result = pg_query_params($dbh, $sql, [$_domain]); R::testConnection() || die('Error in DB connection');
$result || die('Error in SQL query: ' . pg_last_error());
try {
while ($row = pg_fetch_array($result)) { $pod = R::getRow('
if ($_format === 'json') { SELECT hgitdate, id, domain, status, secure, score, userrating, adminrating, city, state, country, lat, long, ip, ipv6, pingdomurl, monthsmonitored, uptimelast7, responsetimelast7, local_posts, comment_counts, dateCreated, dateUpdated, dateLaststats, hidden
echo json_encode($row); FROM pods_apiv1
} else { WHERE domain = ?
echo 'Status: ' . $row['status'] . '<br>'; ', [$_domain]);
echo 'Last Git Pull: ' . $row['hgitdate'] . '<br>'; } catch (\RedBeanPHP\RedException $e) {
echo 'Uptime This Month ' . $row['uptimelast7'] . '<br>'; die('Error in SQL query: ' . $e->getMessage());
echo 'Months Monitored: ' . $row['monthsmonitored'] . '<br>'; }
echo 'Response Time: ' . $row['responsetimelast7'] . '<br>';
echo 'User Rating: ' . $row['userrating'] . '<br>'; if ($_format === 'json') {
echo 'Server Location: ' . $row['country'] . '<br>'; echo json_encode($pod);
echo 'Latitude: ' . $row['lat'] . '<br>'; } else {
echo 'Longitude: ' . $row['long'] . '<br>'; echo 'Status: ' . $pod['status'] . '<br>';
} echo 'Last Git Pull: ' . $pod['hgitdate'] . '<br>';
echo 'Uptime This Month ' . $pod['uptimelast7'] . '<br>';
echo 'Months Monitored: ' . $pod['monthsmonitored'] . '<br>';
echo 'Response Time: ' . $pod['responsetimelast7'] . '<br>';
echo 'User Rating: ' . $pod['userrating'] . '<br>';
echo 'Server Location: ' . $pod['country'] . '<br>';
echo 'Latitude: ' . $pod['lat'] . '<br>';
echo 'Longitude: ' . $pod['long'] . '<br>';
} }
<?php <?php
use RedBeanPHP\R;
// Required parameters. // Required parameters.
($_domain = $_GET['domain'] ?? null) || die('no pod domain given'); ($_domain = $_GET['domain'] ?? null) || die('no pod domain given');
($_token = $_GET['token'] ?? null) || die('no token given'); ($_token = $_GET['token'] ?? null) || die('no token given');
...@@ -11,55 +14,64 @@ $_email = $_GET['email'] ?? ''; ...@@ -11,55 +14,64 @@ $_email = $_GET['email'] ?? '';
$_podmin_statement = $_GET['podmin_statement'] ?? ''; $_podmin_statement = $_GET['podmin_statement'] ?? '';
$_podmin_notify = $_GET['podmin_notify'] ?? 0; $_podmin_notify = $_GET['podmin_notify'] ?? 0;
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php'; require_once __DIR__ . '/../config.php';
$dbh = pg_connect("dbname=$pgdb user=$pguser password=$pgpass"); define('PODUPTIME', microtime(true));
$dbh || die('Error in connection: ' . pg_last_error());
$sql = 'SELECT domain,email,token,tokenexpire,weight,podmin_statement,podmin_notify FROM pods WHERE domain = $1'; // Set up global DB connection.
$result = pg_query_params($dbh, $sql, [$_domain]); R::setup("pgsql:host={$pghost};dbname={$pgdb}", $pguser, $pgpass, true);
$result || die('Error in SQL query: ' . pg_last_error()); R::testConnection() || die('Error in DB connection');
while ($row = pg_fetch_array($result)) { try {
$row['token'] === $_token || die('token mismatch'); $pod = R::findOne('pods', 'domain = ?', [$_domain]);
$row['tokenexpire'] >= date('Y-m-d H:i:s') || die('token expired'); $pod || die('domain not found');
} catch (\RedBeanPHP\RedException $e) {
die('Error in SQL query: ' . $e->getMessage());
}
// Delete and exit. $pod['token'] === $_token || die('token mismatch');
if ('delete' === $_action) { $pod['tokenexpire'] >= date('Y-m-d H:i:s') || die('token expired');
$sql = 'DELETE FROM pods WHERE domain = $1';
$result = pg_query_params($dbh, $sql, [$_domain]);
$result || die('Error in SQL query: ' . pg_last_error());
die('pod removed from DB'); // Delete and exit.
} if ('delete' === $_action) {
R::trash($pod);
die('pod removed from DB');
}
// Save and exit // Save and exit.
if ('save' === $_action) { if ('save' === $_action) {
$_weight <= 10 || die('10 is max weight'); $_weight <= 10 || die('10 is max weight');
$sql = 'UPDATE pods SET email = $1, weight = $2, podmin_statement = $3, podmin_notify = $4 WHERE domain = $5'; try {
$result = pg_query_params($dbh, $sql, [$_email, $_weight, $_podmin_statement, $_podmin_notify, $_domain]); $pod['email'] = $_email;
$result || die('Error in SQL query: ' . pg_last_error()); $pod['weight'] = $_weight;