pull.php 16.7 KB
Newer Older
MatrixCrawler's avatar
MatrixCrawler committed
1
<?php
2 3 4 5 6 7

/**
 * Pull pod info.
 */

declare(strict_types=1);
8

dmorley's avatar
dmorley committed
9 10 11 12 13 14
if (!in_array(PHP_SAPI, ['cgi-fcgi', 'cli'])) {
    $referer = ($_SERVER['HTTP_REFERER'] ? parse_url($_SERVER['HTTP_REFERER'])['host'] : '');
    if ($referer !== $_SERVER['SERVER_NAME']) {
        header('HTTP/1.0 403 Forbidden');
        exit;
    }
15 16
}

dmorley's avatar
dmorley committed
17
use GeoIp2\Database\Reader;
18
use LanguageDetection\Language;
19 20
use Poduptime\PodStatus;
use RedBeanPHP\R;
noplanman's avatar
noplanman committed
21

22 23
$debug    = isset($_GET['debug']) || (isset($argv) && in_array('debug', $argv, true));
$sqldebug = isset($_GET['sqldebug']) || (isset($argv) && in_array('sqldebug', $argv, true));
dmorley's avatar
dmorley committed
24
$develop  = isset($_GET['develop']) || (isset($argv) && in_array('develop', $argv, true));
25 26
$write    = !(isset($_GET['nowrite']) || (isset($argv) && in_array('nowrite', $argv, true)));
$newline  = PHP_SAPI === 'cli' ? "\n\n" : '<br><br>';
David Morley's avatar
David Morley committed
27

noplanman's avatar
noplanman committed
28 29 30 31
$_domain = $_GET['domain'] ?? null;

// Must have a domain, except if called from CLI.
$_domain || PHP_SAPI === 'cli' || die('No valid input');
32

noplanman's avatar
noplanman committed
33
require_once __DIR__ . '/../boot.php';
noplanman's avatar
noplanman committed
34

noplanman's avatar
noplanman committed
35
$sqldebug && R::fancyDebug(true);
noplanman's avatar
noplanman committed
36 37

try {
dmorley's avatar
dmorley committed
38
    // Setup GeoIP Database
noplanman's avatar
noplanman committed
39
    $reader = new Reader(c('geoip2db'));
dmorley's avatar
dmorley committed
40

41
    $sql = '
dmorley's avatar
dmorley committed
42
        SELECT domain, score, date_created, weight, podmin_notify, email, masterversion, shortversion, status
43 44 45 46
        FROM pods
    ';

    $pods = [];
dmorley's avatar
dmorley committed
47

48 49 50 51 52 53 54 55 56 57
    if ($_domain) {
        $sql  .= ' WHERE domain = ?';
        $pods = R::getAll($sql, [$_domain]);
    } elseif (PHP_SAPI === 'cli' && (isset($argv) && in_array('Check_System_Deleted', $argv, true))) {
        $sql  .= ' WHERE status = ?';
        $pods = R::getAll($sql, [PodStatus::SYSTEM_DELETED]);
    } elseif (PHP_SAPI === 'cli') {
        $sql  .= ' WHERE status < ?';
        $pods = R::getAll($sql, [PodStatus::PAUSED]);
    }
noplanman's avatar
noplanman committed
58
} catch (\RedBeanPHP\RedException $e) {
59
    die('Error in SQL query: ' . $e->getMessage());
dmorley's avatar
dmorley committed
60 61
} catch (\MaxMind\Db\Reader\InvalidDatabaseException $e) {
    die('Invalid GeoIP database: ' . $e->getMessage());
dmorley's avatar
cleanup  
dmorley committed
62
}
noplanman's avatar
noplanman committed
63 64

foreach ($pods as $pod) {
65 66
    $domain    = $pod['domain'];
    $score     = (int) $pod['score'];
dmorley's avatar
dmorley committed
67
    $dbscore   = $score;
68 69 70 71 72 73 74 75 76 77
    $dateadded = $pod['date_created'];
    $weight    = $pod['weight'];
    $email     = $pod['email'];
    $notify    = $pod['podmin_notify'];
    $masterv   = $pod['masterversion'];
    $shortv    = $pod['shortversion'];
    $dbstatus  = $pod['status'];

    try {
        $ratings = R::getAll('
dmorley's avatar
dmorley committed
78 79
            SELECT rating
            FROM ratingcomments
80 81 82 83 84
            WHERE domain = ?
        ', [$domain]);
    } catch (\RedBeanPHP\RedException $e) {
        die('Error in SQL query: ' . $e->getMessage());
    }
85

86
    _debug('Domain', $domain);
noplanman's avatar
noplanman committed
87

dmorley's avatar
dmorley committed
88
    $user_rating = 0;
dmorley's avatar
dmorley committed
89

dmorley's avatar
dmorley committed
90 91
    if ($user_ratings = array_column($ratings, 'rating')) {
        $user_rating = round(array_sum($user_ratings) / count($user_ratings), 2);
92
    }
93

dmorley's avatar
dmorley committed
94 95
    // Default link to fetch node info.
    $link = "https://{$domain}/nodeinfo/1.0";
noplanman's avatar
noplanman committed
96

97 98 99 100 101
    extract(_curl("https://{$domain}/.well-known/nodeinfo"));
    $outputwellknown  = $curl_body;

    if ($outputwellknown !== false) {
        $info = json_decode($outputwellknown, true);
dmorley's avatar
dmorley committed
102
        $link = max($info['links'])['href'];
103 104
    }

dmorley's avatar
dmorley committed
105
    _debug('Nodeinfo link', $link);
106
    extract(_curl($link));
dmorley's avatar
dmorley committed
107

108 109 110 111 112
    $outputssl      = $curl_body;
    $outputsslerror = $curl_error;
    $info           = $curl_info;
    $conntime       = $curl_conntime;
    $nstime         = $curl_nstime;
113 114 115 116 117 118 119 120 121 122
    $latency        = $conntime - $nstime;
    $sslexpire      = $info[0]['Expire date'] ?? null;

    _debug('Nodeinfo output', $outputssl, true);
    _debug('Nodeinfo output error', $outputsslerror, true);
    _debug('Cert expire date', $sslexpire);
    _debug('Conntime', $conntime);
    _debug('NStime', $nstime);
    _debug('Latency', $latency);

dmorley's avatar
dmorley committed
123
    $jsonssl = ($outputssl ? json_decode($outputssl) : null);
124 125

    if ($jsonssl !== null) {
dmorley's avatar
dmorley committed
126 127 128
        $version               = $jsonssl->software->version ?? 0;
        preg_match_all('((?:\d(.|-)?)+(\.)\d+\.*)', $version, $sversion);
        $shortversion          = $sversion[0][0] ?? '0.0.0.0';
dmorley's avatar
dmorley committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
        $signup                = ($jsonssl->openRegistrations ?? false) === true;
        $softwarename          = $jsonssl->software->name ?? 'unknown';
        $name                  = $jsonssl->metadata->nodeName ?? $softwarename;
        $total_users           = $jsonssl->usage->users->total ?? 0;
        $active_users_halfyear = $jsonssl->usage->users->activeHalfyear ?? 0;
        $active_users_monthly  = $jsonssl->usage->users->activeMonth ?? 0;
        $local_posts           = $jsonssl->usage->localPosts ?? 0;
        $comment_counts        = $jsonssl->usage->localComments ?? 0;
        $service_xmpp          = ($jsonssl->metadata->xmppChat ?? false) === true;
        $service_facebook      = false;
        $service_twitter       = false;
        $service_tumblr        = false;
        $service_wordpress     = false;
        if (json_last_error() === 0) {
            (!$jsonssl->software->version) || $score += 1;
            if (is_array($jsonssl->services->outbound)) {
                $service_facebook  = in_array('facebook', $jsonssl->services->outbound, true);
                $service_twitter   = in_array('twitter', $jsonssl->services->outbound, true);
                $service_tumblr    = in_array('tumblr', $jsonssl->services->outbound, true);
                $service_wordpress = in_array('wordpress', $jsonssl->services->outbound, true);
            }
        }
151 152 153 154 155 156 157 158 159 160

        try {
            $c                   = R::dispense('checks');
            $c['domain']         = $domain;
            $c['online']         = true;
            $c['latency']        = $latency;
            $c['total_users']    = $total_users;
            $c['local_posts']    = $local_posts;
            $c['comment_counts'] = $comment_counts;
            $c['shortversion']   = $shortversion;
dmorley's avatar
dmorley committed
161
            $c['version']        = $version;
dmorley's avatar
dmorley committed
162

163 164 165 166 167 168 169 170 171
            if ($write) {
                R::store($c);
            } else {
                echo $c;
            }
        } catch (\RedBeanPHP\RedException $e) {
            die('Error in SQL query: ' . $e->getMessage());
        }

dmorley's avatar
dmorley committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
        _debug('Version code', $shortversion);

        try {
            $masterdata = R::getRow('
                SELECT version, devlastcommit, releasedate
                FROM masterversions
                WHERE software = ?
                ORDER BY id
                DESC LIMIT 1
            ', [$softwarename]);
        } catch (\RedBeanPHP\RedException $e) {
            die('Error in SQL query: ' . $e->getMessage());
        }

        $masterversion = ($masterdata['version'] ?? '0.0.0.0');
        $devlastcommit = ($masterdata['devlastcommit'] ?? date('Y-m-d H:i:s'));
        $releasedate   = ($masterdata['releasedate'] ?? date('Y-m-d H:i:s'));
dmorley's avatar
dmorley committed
189

dmorley's avatar
dmorley committed
190
        _debug('Masterversion', $masterversion);
dmorley's avatar
dmorley committed
191

dmorley's avatar
dmorley committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        $masterversioncheck = explode('.', $masterversion);
        $shortversioncheck  = (strpos($shortversion, '.') ? explode('.', $shortversion) : implode('.', ['0', preg_replace('/\D/', '', $shortversion), '0']));
        //this is still off with a pod with v1 as total version. cant explode that, won't have a [0] or [1] later to use either

        _debug('Days since master code release', date_diff(new DateTime($releasedate), new DateTime())->format('%d'));

        try {
            $lastpodupdates = R::getRow('
                SELECT DISTINCT ON (shortversion, date_checked) shortversion, date_checked
                FROM checks
                WHERE domain = ?
                    AND shortversion IS NOT NULL
                ORDER BY shortversion DESC, date_checked
                LIMIT 1
            ', [$domain]);
        } catch (\RedBeanPHP\RedException $e) {
            die('Error in SQL query: ' . $e->getMessage());
        }

        $lastdatechecked = ($lastpodupdates['date_checked'] ?? date('Y-m-d H:i:s'));
        $devlastdays     = $devlastcommit ? date_diff(new DateTime($devlastcommit), new DateTime())->format('%a') : 30;//tmp//if no dev branch then what?

        _debug('Dev last commit was  ', $devlastdays);
dmorley's avatar
dmorley committed
215

dmorley's avatar
dmorley committed
216 217 218 219 220 221
        $updategap = date_diff(new DateTime($lastdatechecked), new DateTime($devlastcommit))->format('%a');

        if (strpos($version, 'dev') !== false || strpos($version, 'rc') !== false || $shortversioncheck > $masterversioncheck) {
            //tmp//if pod is on the development branch - see when you last updated your pod and when the last commit was made to dev branch - if the repo is active and your not updating every 120 days why are you on dev branch?

            if ($updategap + $devlastdays > 400) {
dmorley's avatar
dmorley committed
222 223 224

                _debug('Outdated More than 400 days', 'Yes');

dmorley's avatar
dmorley committed
225 226 227 228
                $score -= 2;
            }
        } elseif (($masterversioncheck[1] - $shortversioncheck[1]) > 1) {
            ///tmp/If pod is two versions off AND it's been more than 60 days since that release came out AND your on the master production branch
dmorley's avatar
dmorley committed
229 230 231

            _debug('Outdated second decimal > 1', 'Yes');

dmorley's avatar
dmorley committed
232 233
            $score     -= 2;
            $updategap = date_diff(new DateTime($lastdatechecked), new DateTime($releasedate))->format('%a');
dmorley's avatar
dmorley committed
234 235 236 237
        } elseif ($updategap - date_diff(new DateTime($releasedate), new DateTime())->format('%a') > 400) {

            _debug('Outdated more than 400 days since x ', 'Yes');

dmorley's avatar
dmorley committed
238 239 240 241 242 243
            $score     -= 2;
            $updategap = date_diff(new DateTime($lastdatechecked), new DateTime($releasedate))->format('%a');
        } else {
            $updategap = date_diff(new DateTime($lastdatechecked), new DateTime($releasedate))->format('%a');
        }

dmorley's avatar
dmorley committed
244
        _debug('Pod code was updated after ', $updategap);
dmorley's avatar
dmorley committed
245

246 247 248
        $status = PodStatus::UP;
    }

dmorley's avatar
dmorley committed
249 250
    $d = new DOMDocument;
    libxml_use_internal_errors(true);
251 252 253
    extract(_curl("https://{$domain}/"));
    $outputbody  = $curl_body;
    ($outputbody ? $d->loadHTML($outputbody) : $d->loadHTML('<html></html>'));
dmorley's avatar
dmorley committed
254 255 256 257
    $body = $d->getElementsByTagName('html')->item(0);

    if ($body) {
        $ld               = new Language;
258
        $detectedlanguage = key($ld->detect($body->nodeValue)->bestResults()->close());
dmorley's avatar
dmorley committed
259 260 261 262 263 264 265 266 267
    } else {
        $score -= 1;
        $detectedlanguage = null;
    }

    _debug('Detected Language', $detectedlanguage);

    if (!$jsonssl || !$body) {

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
        _debug('Connection', 'Can not connect to pod');

        try {
            $c            = R::dispense('checks');
            $c['domain']  = $domain;
            $c['online']  = false;
            $c['error']   = $outputsslerror;
            $c['latency'] = $latency;
            if ($write) {
                R::store($c);
            } else {
                echo $c;
            }
        } catch (\RedBeanPHP\RedException $e) {
            die('Error in SQL query: ' . $e->getMessage());
        }

        $score  -= 1;
        $status = PodStatus::DOWN;
    }

    _debug('Signup Open', $signup);

noplanman's avatar
noplanman committed
291
    $dnsserver = c('dnsserver') ?: '1.1.1.1';
292 293 294 295 296 297 298
    $delv      = new NPM\Xec\Command("delv @{$dnsserver} {$domain}");
    $delv->throwExceptionOnError(false);

    $ip         = '';
    $iplookupv4 = explode(PHP_EOL, trim($delv->execute([], null, 15)->stdout));
    $dnssec     = in_array('; fully validated', $iplookupv4, true) ?? false;
    $getaonly   = array_values(preg_grep('/\s+IN\s+A\s+.*/', $iplookupv4));
dmorley's avatar
dmorley committed
299

300 301 302
    if ($getaonly) {
        preg_match('/A\s(.*)/', $getaonly[0], $aversion);
        $ip = trim($aversion[1]) ?? '';
noplanman's avatar
noplanman committed
303
    }
304 305 306 307
    $ip || $score -= 2;

    $iplookupv6 = explode(PHP_EOL, trim($delv->execute(['AAAA'], null, 15)->stdout));
    $ipv6       = (bool) preg_grep('/\s+IN\s+AAAA\s+.*/', $iplookupv6);
308

309 310
    _debug('IPv4', $ip);
    _debug('IPv6', $ipv6);
noplanman's avatar
noplanman committed
311

dmorley's avatar
dmorley committed
312 313 314 315 316 317 318 319
    if ($ip) {
        $geo         = $reader->city($ip);
        $countryname = ($geo->country->name ?? null) ?: null;
        $country     = ($geo->country->isoCode ?? null) ?: null;
        $city        = ($geo->city->name ?? null) ?: null;
        $state       = ($geo->mostSpecificSubdivision->name ?? null) ?: null;
        $lat         = ($geo->location->latitude ?? null) ?: 0;
        $long        = ($geo->location->longitude ?? null) ?: 0;
320

dmorley's avatar
dmorley committed
321 322
        _debug('Location', json_encode($geo->raw), true);
    }
323 324 325 326 327 328
    echo $newline;
    $statslastdate = date('Y-m-d H:i:s');

    $diff   = (new DateTime())->diff(new DateTime($dateadded));
    $months = $diff->m + ($diff->y * 12);
    $days   = $diff->days;
noplanman's avatar
noplanman committed
329 330

    try {
331 332 333 334 335 336 337 338 339 340
        $checks = R::getRow('
            SELECT
                round(avg(latency) * 1000) AS latency,
                round(avg(online::INT) * 100, 2) AS online
            FROM checks
            WHERE domain = ?
        ', [$domain]);

        $avglatency = $checks['latency'] ?? 0;
        $uptime     = $checks['online'] ?? 0;
noplanman's avatar
noplanman committed
341
    } catch (\RedBeanPHP\RedException $e) {
342
        die('Error in SQL query: ' . $e->getMessage());
noplanman's avatar
noplanman committed
343 344
    }

345
    _debug('Uptime', $uptime);
noplanman's avatar
noplanman committed
346

dmorley's avatar
dmorley committed
347
    if ($score == 49 && $notify && !$develop && $dbscore == 50) {
348
        $to      = $email;
noplanman's avatar
noplanman committed
349
        $headers = ['From: ' . c('adminemail'), 'Bcc: ' . c('adminemail')];
350
        $subject = 'Monitoring notice from poduptime';
dmorley's avatar
dmorley committed
351
        $message = 'Notice for ' . $domain . '. Your score is ' . $score . ' and your pod will fall off the list soon.';
352
        @mail($to, $subject, $message, implode("\r\n", $headers));
dmorley's avatar
dmorley committed
353

354
        _debug('Mail Notice', 'sent to ' . $email);
dmorley's avatar
dmorley committed
355
    }
356 357 358 359
    if ($score > 100) {
        $score = 100;
    } elseif ($score < 0) {
        $score = 0;
dmorley's avatar
dmorley committed
360
        $status = PodStatus::SYSTEM_DELETED;
dmorley's avatar
dmorley committed
361
    }
362
    $weightedscore = ($uptime + $score - (10 - $weight)) / 2;
dmorley's avatar
dmorley committed
363 364

    _debug('Score', $score);
365
    _debug('Weighted Score', $weightedscore);
noplanman's avatar
noplanman committed
366

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    try {
        $p                     = R::findOne('pods', 'domain = ?', [$domain]);
        $p['ip']               = $ip;
        $p['ipv6']             = $ipv6;
        $p['daysmonitored']    = $days;
        $p['monthsmonitored']  = $months;
        $p['uptime_alltime']   = $uptime;
        $p['status']           = $status;
        $p['date_laststats']   = $statslastdate;
        $p['date_updated']     = date('Y-m-d H:i:s');
        $p['latency']          = $avglatency;
        $p['score']            = $score;
        $p['country']          = $country;
        $p['countryname']      = $countryname;
        $p['city']             = $city;
        $p['state']            = $state;
        $p['lat']              = $lat;
        $p['long']             = $long;
        $p['detectedlanguage'] = $detectedlanguage;
        $p['userrating']       = $user_rating;
        $p['masterversion']    = $masterversion;
        $p['weightedscore']    = $weightedscore;
        $p['sslvalid']         = $outputsslerror;
        $p['dnssec']           = $dnssec;
        $p['sslexpire']        = $sslexpire;
dmorley's avatar
dmorley committed
392
        if ($dbstatus == PodStatus::UP && $status == PodStatus::UP) {
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
            $p['shortversion']          = $shortversion;
            $p['signup']                = $signup;
            $p['total_users']           = $total_users;
            $p['active_users_halfyear'] = $active_users_halfyear;
            $p['active_users_monthly']  = $active_users_monthly;
            $p['local_posts']           = $local_posts;
            $p['name']                  = $name;
            $p['comment_counts']        = $comment_counts;
            $p['service_facebook']      = $service_facebook;
            $p['service_tumblr']        = $service_tumblr;
            $p['service_twitter']       = $service_twitter;
            $p['service_wordpress']     = $service_wordpress;
            $p['service_xmpp']          = $service_xmpp;
            $p['softwarename']          = $softwarename;
        }

        if ($write) {
            R::store($p);
        } else {
dmorley's avatar
dmorley committed
412 413
            echo 'Data not saved, testing only';
            echo $newline;
414 415 416
        }
    } catch (\RedBeanPHP\RedException $e) {
        die('Error in SQL query: ' . $e->getMessage());
417
    }
David Morley's avatar
David Morley committed
418

419
    echo 'Success ' . $domain;
noplanman's avatar
noplanman committed
420

421 422
    echo $newline;
    echo $newline;
David Morley's avatar
David Morley committed
423
}
424

David Morley's avatar
David Morley committed
425 426
/**
 * Output a debug message and variable value
noplanman's avatar
noplanman committed
427
 *
David Morley's avatar
David Morley committed
428 429 430 431
 * @param string $label
 * @param mixed  $var
 * @param bool   $dump
 */
noplanman's avatar
noplanman committed
432 433
function _debug($label, $var = null, $dump = false)
{
434
    global $debug, $newline;
435

436 437 438
    if (!$debug) {
        return;
    }
noplanman's avatar
noplanman committed
439

dmorley's avatar
dmorley committed
440
    $output = (string) $var;
441 442 443 444 445
    if ($dump || is_array($var)) {
        $output = print_r($var, true);
    } elseif (is_bool($var)) {
        $output = $var ? 'true' : 'false';
    }
noplanman's avatar
noplanman committed
446

447
    printf('%s: %s%s', $label, $output, $newline);
448
}
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

function _curl($url)
{
    global $cafullpath;

    $chss = curl_init();
    curl_setopt($chss, CURLOPT_URL, $url);
    curl_setopt($chss, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($chss, CURLOPT_TIMEOUT, 20);
    curl_setopt($chss, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($chss, CURLOPT_CERTINFO, 1);
    curl_setopt($chss, CURLOPT_CAINFO, $cafullpath);
    return [
        'curl_body'     => curl_exec($chss),
        'curl_error'    => curl_error($chss),
        'curl_info'     => curl_getinfo($chss, CURLINFO_CERTINFO),
        'curl_conntime' => curl_getinfo($chss, CURLINFO_CONNECT_TIME),
        'curl_nstime'   => curl_getinfo($chss, CURLINFO_NAMELOOKUP_TIME)
    ];
    curl_close($chss);
}