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

/**
 * Pull pod info.
 */

declare(strict_types=1);
8

David Morley's avatar
David Morley 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
}

17
use Carbon\Carbon;
18
use DetectLanguage\DetectLanguage;
19
use GeoIp2\Database\Reader;
20 21
use Poduptime\PodStatus;
use RedBeanPHP\R;
22

23 24
$debug    = isset($_GET['debug']) || (isset($argv) && in_array('debug', $argv, true));
$sqldebug = isset($_GET['sqldebug']) || (isset($argv) && in_array('sqldebug', $argv, true));
David Morley's avatar
David Morley committed
25
$develop  = isset($_GET['develop']) || (isset($argv) && in_array('develop', $argv, true));
26 27
$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
28

29 30 31 32
$_domain = $_GET['domain'] ?? null;

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

34
require_once __DIR__ . '/../boot.php';
35

36
$sqldebug && R::fancyDebug(true);
37 38

try {
David Morley's avatar
David Morley committed
39
    // Setup GeoIP Database
40
    $reader = new Reader(c('geoip2db'));
David Morley's avatar
David Morley committed
41

42
    $sql = '
43
        SELECT domain, score, date_created, weight, podmin_notify, email, masterversion, shortversion, status, detectedlanguage
44 45 46 47
        FROM pods
    ';

    $pods = [];
David Morley's avatar
David Morley committed
48

49 50 51 52 53 54 55 56 57 58
    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]);
    }
59
} catch (\RedBeanPHP\RedException $e) {
60
    die('Error in SQL query: ' . $e->getMessage());
David Morley's avatar
David Morley committed
61 62
} catch (\MaxMind\Db\Reader\InvalidDatabaseException $e) {
    die('Invalid GeoIP database: ' . $e->getMessage());
David Morley's avatar
David Morley committed
63
}
64 65

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

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

88
    _debug('Domain', $domain);
89

David Morley's avatar
David Morley committed
90
    $user_rating = 0;
David Morley's avatar
David Morley committed
91

David Morley's avatar
David Morley committed
92 93
    if ($user_ratings = array_column($ratings, 'rating')) {
        $user_rating = round(array_sum($user_ratings) / count($user_ratings), 2);
94
    }
95

96
    $nodeinfo_meta = _curl("https://{$domain}/.well-known/nodeinfo");
97

98 99
    // Default link to fetch node info.
    $nodeinfo_url = "https://{$domain}/nodeinfo/1.0";
100

101
    if (!isset($nodeinfo_meta['error'])) {
102 103
        $info         = json_decode($nodeinfo_meta['body'], true);
        $nodeinfo_url = max($info['links'])['href'];
104 105
    }

106 107
    _debug('Nodeinfo link', $nodeinfo_url);
    $nodeinfo = _curl($nodeinfo_url);
108

109 110 111 112 113
    $outputssl      = $nodeinfo['body'];
    $outputsslerror = $nodeinfo['error'];
    $info           = $nodeinfo['info'];
    $conntime       = $nodeinfo['conntime'];
    $nstime         = $nodeinfo['nstime'];
114 115 116 117 118 119 120 121 122 123
    $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);

124
    $jsonssl = ($outputssl ? json_decode($outputssl) : null);
125 126

    if ($jsonssl !== null) {
127
        $version = $jsonssl->software->version ?? 0;
David Morley's avatar
David Morley committed
128 129
        preg_match_all('((?:\d(.|-)?)+(\.)\d+\.*)', $version, $sversion);
        $shortversion          = $sversion[0][0] ?? '0.0.0.0';
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        $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);
            }
        }
152 153 154 155 156 157 158 159 160 161

        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;
David Morley's avatar
David Morley committed
162
            $c['version']        = $version;
David Morley's avatar
David Morley committed
163

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

David Morley's avatar
David Morley committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
        _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'));
David Morley's avatar
David Morley committed
190

David Morley's avatar
David Morley committed
191
        _debug('Masterversion', $masterversion);
David Morley's avatar
David Morley committed
192

David Morley's avatar
David Morley committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
        $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);
David Morley's avatar
David Morley committed
216

David Morley's avatar
David Morley committed
217 218 219 220 221 222
        $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) {
David Morley's avatar
David Morley committed
223 224 225

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

David Morley's avatar
David Morley committed
226 227 228 229
                $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
David Morley's avatar
David Morley committed
230 231 232

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

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

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

David Morley's avatar
David Morley committed
239 240 241 242 243 244
            $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');
        }

David Morley's avatar
David Morley committed
245
        _debug('Pod code was updated after ', $updategap);
David Morley's avatar
David Morley committed
246

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

250 251
    // Default to the already saved language.
    $detectedlanguage = $language;
David Morley's avatar
David Morley committed
252

253 254
    $language_snippet = getWebsiteLanguageSnippetFromUrl("https://{$domain}/");
    if (!$language_snippet) {
David Morley's avatar
David Morley committed
255
        $detectedlanguage = null;
256
        --$score;
Armando Lüscher's avatar
Armando Lüscher committed
257
    } elseif ($debug || Carbon::now()->hour === 12) {
258
        $detectedlanguage = detectWebsiteLanguageFromSnippet($language_snippet);
David Morley's avatar
David Morley committed
259 260 261 262
    }

    _debug('Detected Language', $detectedlanguage);

263
    if (!$jsonssl || !$language_snippet) {
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
        _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());
        }

281
        --$score;
282 283 284 285 286
        $status = PodStatus::DOWN;
    }

    _debug('Signup Open', $signup);

287
    $dnsserver = c('dnsserver') ?: '1.1.1.1';
288 289 290 291 292 293 294
    $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));
David Morley's avatar
David Morley committed
295

296 297 298
    if ($getaonly) {
        preg_match('/A\s(.*)/', $getaonly[0], $aversion);
        $ip = trim($aversion[1]) ?? '';
299
    }
300 301 302 303
    $ip || $score -= 2;

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

305 306
    _debug('IPv4', $ip);
    _debug('IPv6', $ipv6);
307

David Morley's avatar
David Morley committed
308 309 310 311 312 313 314 315
    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;
316

David Morley's avatar
David Morley committed
317 318
        _debug('Location', json_encode($geo->raw), true);
    }
319 320 321 322 323 324
    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;
325 326

    try {
327 328 329 330 331 332 333 334 335 336
        $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;
337
    } catch (\RedBeanPHP\RedException $e) {
338
        die('Error in SQL query: ' . $e->getMessage());
339 340
    }

341
    _debug('Uptime', $uptime);
342

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

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

    _debug('Score', $score);
361
    _debug('Weighted Score', $weightedscore);
362

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    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;
David Morley's avatar
David Morley committed
388
        if ($dbstatus == PodStatus::UP && $status == PodStatus::UP) {
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
            $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 {
408 409
            echo 'Data not saved, testing only';
            echo $newline;
410 411 412
        }
    } catch (\RedBeanPHP\RedException $e) {
        die('Error in SQL query: ' . $e->getMessage());
413
    }
David Morley's avatar
David Morley committed
414

415
    echo 'Success ' . $domain;
416

417 418
    echo $newline;
    echo $newline;
David Morley's avatar
David Morley committed
419
}
420

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

432 433 434
    if (!$debug) {
        return;
    }
435

436
    $output = (string) $var;
437 438 439 440 441
    if ($dump || is_array($var)) {
        $output = print_r($var, true);
    } elseif (is_bool($var)) {
        $output = $var ? 'true' : 'false';
    }
442

443
    printf('%s: %s%s', $label, $output, $newline);
444
}
445

446 447 448 449 450 451 452 453
/**
 * Execute cURL request and return array of data.
 *
 * @param string $url
 *
 * @return array
 */
function _curl(string $url): array
454 455 456 457 458 459 460
{
    $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);
461
    curl_setopt($chss, CURLOPT_CAINFO, c('cafullpath'));
462 463 464 465 466 467
    $data = [
        'body'     => curl_exec($chss),
        'error'    => curl_error($chss),
        'info'     => curl_getinfo($chss, CURLINFO_CERTINFO),
        'conntime' => curl_getinfo($chss, CURLINFO_CONNECT_TIME),
        'nstime'   => curl_getinfo($chss, CURLINFO_NAMELOOKUP_TIME),
468 469
    ];
    curl_close($chss);
470 471

    return $data;
472
}
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493

/**
 * Get a language snippet from a given URL.
 *
 * @param string $url
 *
 * @return null|string
 */
function getWebsiteLanguageSnippetFromUrl(string $url): ?string
{
    $curl = _curl($url);

    if (!$curl['body']) {
        return null;
    }

    libxml_use_internal_errors(true);

    $d = new DOMDocument;
    $d->loadHTML($curl['body']);

Armando Lüscher's avatar
Armando Lüscher committed
494 495
    $snippet = $d->getElementsByTagName('title')->item(0)->textContent ?? '';

496 497 498 499
    for ($type = 1; $type < 6; $type++) {
        foreach ($d->getElementsByTagName('h' . $type) as $h) {
            // Ignore possibly generic "JavaScript required" texts.
            if (stripos($h->textContent, 'javascript') === false) {
Armando Lüscher's avatar
Armando Lüscher committed
500
                $snippet .= ' ' . $h->textContent;
501 502 503
            }
        }
    }
504

Armando Lüscher's avatar
Armando Lüscher committed
505 506 507 508
    // Get descriptions of meta tags.
    foreach ($d->getElementsByTagName('meta') as $meta) {
        if (strtolower($meta->getAttribute('name')) === 'description') {
            $snippet .= ' ' . $meta->getAttribute('value');
509 510
        }
    }
511

Armando Lüscher's avatar
Armando Lüscher committed
512
    return $snippet;
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
}

/**
 * Detect the language of the given text snippet.
 *
 * @param string $snippet
 *
 * @return null|string
 */
function detectWebsiteLanguageFromSnippet(string $snippet): ?string
{
    if (!$snippet) {
        return null;
    }

    return DetectLanguage::simpleDetect($snippet);
}

/**
 * Detect the website language of the given URL.
 *
 * @param string $url
 *
 * @return null|string
 */
function detectWebsiteLanguageFromUrl(string $url): ?string
{
    return detectWebsiteLanguageFromSnippet(
        getWebsiteLanguageSnippetFromUrl($url)
    );
}