+ /**
+ * Checks if the given server is reachable
+ *
+ * @param string $profile URL of the given profile
+ * @param string $server URL of the given server (If empty, taken from profile)
+ * @param string $network Network value that is used, when detection failed
+ * @param boolean $force Force an update.
+ *
+ * @return boolean 'true' if server seems vital
+ */
+ public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
+ {
+ if ($server == '') {
+ $server = Contact::getBasepath($profile);
+ }
+
+ if ($server == '') {
+ return true;
+ }
+
+ return self::check($server, $network, $force);
+ }
+
+ /**
+ * Checks the state of the given server.
+ *
+ * @param string $server_url URL of the given server
+ * @param string $network Network value that is used, when detection failed
+ * @param boolean $force Force an update.
+ *
+ * @return boolean 'true' if server seems vital
+ */
+ public static function check(string $server_url, string $network = '', bool $force = false)
+ {
+ // Unify the server address
+ $server_url = trim($server_url, '/');
+ $server_url = str_replace('/index.php', '', $server_url);
+
+ if ($server_url == '') {
+ return false;
+ }
+
+ $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
+ if (DBA::isResult($gserver)) {
+ if ($gserver['created'] <= DBA::NULL_DATETIME) {
+ $fields = ['created' => DateTimeFormat::utcNow()];
+ $condition = ['nurl' => Strings::normaliseLink($server_url)];
+ DBA::update('gserver', $fields, $condition);
+ }
+
+ $last_contact = $gserver['last_contact'];
+ $last_failure = $gserver['last_failure'];
+
+ // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
+ // It can happen that a zero date is in the database, but storing it again is forbidden.
+ if ($last_contact < DBA::NULL_DATETIME) {
+ $last_contact = DBA::NULL_DATETIME;
+ }
+
+ if ($last_failure < DBA::NULL_DATETIME) {
+ $last_failure = DBA::NULL_DATETIME;
+ }
+
+ if (!$force && !PortableContact::updateNeeded($gserver['created'], '', $last_failure, $last_contact)) {
+ Logger::info('No update needed', ['server' => $server_url]);
+ return ($last_contact >= $last_failure);
+ }
+ Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force, 'Created' => $gserver['created'], 'Failure' => $last_failure, 'Contact' => $last_contact]);
+ } else {
+ Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
+ }
+
+ return self::detect($server_url, $network);
+ }
+