Merge pull request #4691 from annando/relais-discovery
[friendica.git/.git] / src / Protocol / PortableContact.php
1 <?php
2 /**
3  * @file src/Protocol/PortableContact.php
4  *
5  * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6  * @todo Fetch profile data from profile page for Redmatrix users
7  * @todo Detect if it is a forum
8  */
9
10 namespace Friendica\Protocol;
11
12 use Friendica\Content\Text\HTML;
13 use Friendica\Core\Config;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
16 use Friendica\Model\GContact;
17 use Friendica\Model\Profile;
18 use Friendica\Network\Probe;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use dba;
22 use DOMDocument;
23 use DOMXPath;
24 use Exception;
25
26 require_once 'include/dba.php';
27
28 class PortableContact
29 {
30         /**
31          * @brief Fetch POCO data
32          *
33          * @param integer $cid  Contact ID
34          * @param integer $uid  User ID
35          * @param integer $zcid Global Contact ID
36          * @param integer $url  POCO address that should be polled
37          *
38          * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
39          * and add the entries to the gcontact (Global Contact) table, or update existing entries
40          * if anything (name or photo) has changed.
41          * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
42          *
43          * Once the global contact is stored add (if necessary) the contact linkage which associates
44          * the given uid, cid to the global contact entry. There can be many uid/cid combinations
45          * pointing to the same global contact id.
46          *
47          */
48         public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
49         {
50                 // Call the function "load" via the worker
51                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
52         }
53
54         /**
55          * @brief Fetch POCO data from the worker
56          *
57          * @param integer $cid  Contact ID
58          * @param integer $uid  User ID
59          * @param integer $zcid Global Contact ID
60          * @param integer $url  POCO address that should be polled
61          *
62          */
63         public static function load($cid, $uid, $zcid, $url)
64         {
65                 $a = get_app();
66
67                 if ($cid) {
68                         if (!$url || !$uid) {
69                                 $contact = dba::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
70                                 if (DBM::is_result($contact)) {
71                                         $url = $contact['poco'];
72                                         $uid = $contact['uid'];
73                                 }
74                         }
75                         if (!$uid) {
76                                 return;
77                         }
78                 }
79
80                 if (!$url) {
81                         return;
82                 }
83
84                 $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation') ;
85
86                 logger('load: ' . $url, LOGGER_DEBUG);
87
88                 $s = Network::fetchUrl($url);
89
90                 logger('load: returns ' . $s, LOGGER_DATA);
91
92                 logger('load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
93
94                 if (($a->get_curl_code() > 299) || (! $s)) {
95                         return;
96                 }
97
98                 $j = json_decode($s);
99
100                 logger('load: json: ' . print_r($j, true), LOGGER_DATA);
101
102                 if (! isset($j->entry)) {
103                         return;
104                 }
105
106                 $total = 0;
107                 foreach ($j->entry as $entry) {
108                         $total ++;
109                         $profile_url = '';
110                         $profile_photo = '';
111                         $connect_url = '';
112                         $name = '';
113                         $network = '';
114                         $updated = NULL_DATE;
115                         $location = '';
116                         $about = '';
117                         $keywords = '';
118                         $gender = '';
119                         $contact_type = -1;
120                         $generation = 0;
121
122                         $name = $entry->displayName;
123
124                         if (isset($entry->urls)) {
125                                 foreach ($entry->urls as $url) {
126                                         if ($url->type == 'profile') {
127                                                 $profile_url = $url->value;
128                                                 continue;
129                                         }
130                                         if ($url->type == 'webfinger') {
131                                                 $connect_url = str_replace('acct:', '', $url->value);
132                                                 continue;
133                                         }
134                                 }
135                         }
136                         if (isset($entry->photos)) {
137                                 foreach ($entry->photos as $photo) {
138                                         if ($photo->type == 'profile') {
139                                                 $profile_photo = $photo->value;
140                                                 continue;
141                                         }
142                                 }
143                         }
144
145                         if (isset($entry->updated)) {
146                                 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
147                         }
148
149                         if (isset($entry->network)) {
150                                 $network = $entry->network;
151                         }
152
153                         if (isset($entry->currentLocation)) {
154                                 $location = $entry->currentLocation;
155                         }
156
157                         if (isset($entry->aboutMe)) {
158                                 $about = HTML::toBBCode($entry->aboutMe);
159                         }
160
161                         if (isset($entry->gender)) {
162                                 $gender = $entry->gender;
163                         }
164
165                         if (isset($entry->generation) && ($entry->generation > 0)) {
166                                 $generation = ++$entry->generation;
167                         }
168
169                         if (isset($entry->tags)) {
170                                 foreach ($entry->tags as $tag) {
171                                         $keywords = implode(", ", $tag);
172                                 }
173                         }
174
175                         if (isset($entry->contactType) && ($entry->contactType >= 0)) {
176                                 $contact_type = $entry->contactType;
177                         }
178
179                         $gcontact = ["url" => $profile_url,
180                                         "name" => $name,
181                                         "network" => $network,
182                                         "photo" => $profile_photo,
183                                         "about" => $about,
184                                         "location" => $location,
185                                         "gender" => $gender,
186                                         "keywords" => $keywords,
187                                         "connect" => $connect_url,
188                                         "updated" => $updated,
189                                         "contact-type" => $contact_type,
190                                         "generation" => $generation];
191
192                         try {
193                                 $gcontact = GContact::sanitize($gcontact);
194                                 $gcid = GContact::update($gcontact);
195
196                                 GContact::link($gcid, $uid, $cid, $zcid);
197                         } catch (Exception $e) {
198                                 logger($e->getMessage(), LOGGER_DEBUG);
199                         }
200                 }
201                 logger("load: loaded $total entries", LOGGER_DEBUG);
202
203                 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
204                 dba::delete('glink', $condition);
205         }
206
207         public static function reachable($profile, $server = "", $network = "", $force = false)
208         {
209                 if ($server == "") {
210                         $server = self::detectServer($profile);
211                 }
212
213                 if ($server == "") {
214                         return true;
215                 }
216
217                 return self::checkServer($server, $network, $force);
218         }
219
220         public static function detectServer($profile)
221         {
222                 // Try to detect the server path based upon some known standard paths
223                 $server_url = "";
224
225                 if ($server_url == "") {
226                         $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
227                         if ($friendica != $profile) {
228                                 $server_url = $friendica;
229                                 $network = NETWORK_DFRN;
230                         }
231                 }
232
233                 if ($server_url == "") {
234                         $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
235                         if ($diaspora != $profile) {
236                                 $server_url = $diaspora;
237                                 $network = NETWORK_DIASPORA;
238                         }
239                 }
240
241                 if ($server_url == "") {
242                         $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
243                         if ($red != $profile) {
244                                 $server_url = $red;
245                                 $network = NETWORK_DIASPORA;
246                         }
247                 }
248
249                 // Mastodon
250                 if ($server_url == "") {
251                         $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
252                         if ($mastodon != $profile) {
253                                 $server_url = $mastodon;
254                                 $network = NETWORK_OSTATUS;
255                         }
256                 }
257
258                 // Numeric OStatus variant
259                 if ($server_url == "") {
260                         $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
261                         if ($ostatus != $profile) {
262                                 $server_url = $ostatus;
263                                 $network = NETWORK_OSTATUS;
264                         }
265                 }
266
267                 // Wild guess
268                 if ($server_url == "") {
269                         $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
270                         if ($base != $profile) {
271                                 $server_url = $base;
272                                 $network = NETWORK_PHANTOM;
273                         }
274                 }
275
276                 if ($server_url == "") {
277                         return "";
278                 }
279
280                 $r = q(
281                         "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
282                         dbesc(normalise_link($server_url))
283                 );
284
285                 if (DBM::is_result($r)) {
286                         return $server_url;
287                 }
288
289                 // Fetch the host-meta to check if this really is a server
290                 $serverret = Network::curl($server_url."/.well-known/host-meta");
291                 if (!$serverret["success"]) {
292                         return "";
293                 }
294
295                 return $server_url;
296         }
297
298         public static function alternateOStatusUrl($url)
299         {
300                 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
301         }
302
303         public static function lastUpdated($profile, $force = false)
304         {
305                 $gcontacts = q(
306                         "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
307                         dbesc(normalise_link($profile))
308                 );
309
310                 if (!DBM::is_result($gcontacts)) {
311                         return false;
312                 }
313
314                 $contact = ["url" => $profile];
315
316                 if ($gcontacts[0]["created"] <= NULL_DATE) {
317                         $contact['created'] = DateTimeFormat::utcNow();
318                 }
319
320                 $server_url = '';
321                 if ($force) {
322                         $server_url = normalise_link(self::detectServer($profile));
323                 }
324
325                 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
326                         $server_url = $gcontacts[0]["server_url"];
327                 }
328
329                 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
330                         $server_url = normalise_link(self::detectServer($profile));
331                 }
332
333                 if (!in_array($gcontacts[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""])) {
334                         logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
335                         return false;
336                 }
337
338                 if ($server_url != "") {
339                         if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
340                                 if ($force) {
341                                         $fields = ['last_failure' => DateTimeFormat::utcNow()];
342                                         dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
343                                 }
344
345                                 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
346                                 return false;
347                         }
348                         $contact['server_url'] = $server_url;
349                 }
350
351                 if (in_array($gcontacts[0]["network"], ["", NETWORK_FEED])) {
352                         $server = q(
353                                 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
354                                 dbesc(normalise_link($server_url))
355                         );
356
357                         if ($server) {
358                                 $contact['network'] = $server[0]["network"];
359                         } else {
360                                 return false;
361                         }
362                 }
363
364                 // noscrape is really fast so we don't cache the call.
365                 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
366                         //  Use noscrape if possible
367                         $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
368
369                         if ($server) {
370                                 $noscraperet = Network::curl($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
371
372                                 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
373                                         $noscrape = json_decode($noscraperet["body"], true);
374
375                                         if (is_array($noscrape)) {
376                                                 $contact["network"] = $server[0]["network"];
377
378                                                 if (isset($noscrape["fn"])) {
379                                                         $contact["name"] = $noscrape["fn"];
380                                                 }
381                                                 if (isset($noscrape["comm"])) {
382                                                         $contact["community"] = $noscrape["comm"];
383                                                 }
384                                                 if (isset($noscrape["tags"])) {
385                                                         $keywords = implode(" ", $noscrape["tags"]);
386                                                         if ($keywords != "") {
387                                                                 $contact["keywords"] = $keywords;
388                                                         }
389                                                 }
390
391                                                 $location = Profile::formatLocation($noscrape);
392                                                 if ($location) {
393                                                         $contact["location"] = $location;
394                                                 }
395                                                 if (isset($noscrape["dfrn-notify"])) {
396                                                         $contact["notify"] = $noscrape["dfrn-notify"];
397                                                 }
398                                                 // Remove all fields that are not present in the gcontact table
399                                                 unset($noscrape["fn"]);
400                                                 unset($noscrape["key"]);
401                                                 unset($noscrape["homepage"]);
402                                                 unset($noscrape["comm"]);
403                                                 unset($noscrape["tags"]);
404                                                 unset($noscrape["locality"]);
405                                                 unset($noscrape["region"]);
406                                                 unset($noscrape["country-name"]);
407                                                 unset($noscrape["contacts"]);
408                                                 unset($noscrape["dfrn-request"]);
409                                                 unset($noscrape["dfrn-confirm"]);
410                                                 unset($noscrape["dfrn-notify"]);
411                                                 unset($noscrape["dfrn-poll"]);
412
413                                                 // Set the date of the last contact
414                                                 /// @todo By now the function "update_gcontact" doesn't work with this field
415                                                 //$contact["last_contact"] = DateTimeFormat::utcNow();
416
417                                                 $contact = array_merge($contact, $noscrape);
418
419                                                 GContact::update($contact);
420
421                                                 if (trim($noscrape["updated"]) != "") {
422                                                         $fields = ['last_contact' => DateTimeFormat::utcNow()];
423                                                         dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
424
425                                                         logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
426
427                                                         return $noscrape["updated"];
428                                                 }
429                                         }
430                                 }
431                         }
432                 }
433
434                 // If we only can poll the feed, then we only do this once a while
435                 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
436                         logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
437
438                         GContact::update($contact);
439                         return $gcontacts[0]["updated"];
440                 }
441
442                 $data = Probe::uri($profile);
443
444                 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
445                 // Then check the other link and delete this one
446                 if (($data["network"] == NETWORK_OSTATUS) && self::alternateOStatusUrl($profile)
447                         && (normalise_link($profile) == normalise_link($data["alias"]))
448                         && (normalise_link($profile) != normalise_link($data["url"]))
449                 ) {
450                         // Delete the old entry
451                         dba::delete('gcontact', ['nurl' => normalise_link($profile)]);
452
453                         $gcontact = array_merge($gcontacts[0], $data);
454
455                         $gcontact["server_url"] = $data["baseurl"];
456
457                         try {
458                                 $gcontact = GContact::sanitize($gcontact);
459                                 GContact::update($gcontact);
460
461                                 self::lastUpdated($data["url"], $force);
462                         } catch (Exception $e) {
463                                 logger($e->getMessage(), LOGGER_DEBUG);
464                         }
465
466                         logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
467                         return false;
468                 }
469
470                 if (($data["poll"] == "") || (in_array($data["network"], [NETWORK_FEED, NETWORK_PHANTOM]))) {
471                         $fields = ['last_failure' => DateTimeFormat::utcNow()];
472                         dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
473
474                         logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
475                         return false;
476                 }
477
478                 $contact = array_merge($contact, $data);
479
480                 $contact["server_url"] = $data["baseurl"];
481
482                 GContact::update($contact);
483
484                 $feedret = Network::curl($data["poll"]);
485
486                 if (!$feedret["success"]) {
487                         $fields = ['last_failure' => DateTimeFormat::utcNow()];
488                         dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
489
490                         logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
491                         return false;
492                 }
493
494                 $doc = new DOMDocument();
495                 @$doc->loadXML($feedret["body"]);
496
497                 $xpath = new DOMXPath($doc);
498                 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
499
500                 $entries = $xpath->query('/atom:feed/atom:entry');
501
502                 $last_updated = "";
503
504                 foreach ($entries as $entry) {
505                         $published = DateTimeFormat::utc($xpath->query('atom:published/text()', $entry)->item(0)->nodeValue);
506                         $updated   = DateTimeFormat::utc($xpath->query('atom:updated/text()'  , $entry)->item(0)->nodeValue);
507
508                         if ($last_updated < $published) {
509                                 $last_updated = $published;
510                         }
511
512                         if ($last_updated < $updated) {
513                                 $last_updated = $updated;
514                         }
515                 }
516
517                 // Maybe there aren't any entries. Then check if it is a valid feed
518                 if ($last_updated == "") {
519                         if ($xpath->query('/atom:feed')->length > 0) {
520                                 $last_updated = NULL_DATE;
521                         }
522                 }
523
524                 $fields = ['updated' => $last_updated, 'last_contact' => DateTimeFormat::utcNow()];
525                 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
526
527                 if (($gcontacts[0]["generation"] == 0)) {
528                         $fields = ['generation' => 9];
529                         dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
530                 }
531
532                 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
533
534                 return $last_updated;
535         }
536
537         public static function updateNeeded($created, $updated, $last_failure, $last_contact)
538         {
539                 $now = strtotime(DateTimeFormat::utcNow());
540
541                 if ($updated > $last_contact) {
542                         $contact_time = strtotime($updated);
543                 } else {
544                         $contact_time = strtotime($last_contact);
545                 }
546
547                 $failure_time = strtotime($last_failure);
548                 $created_time = strtotime($created);
549
550                 // If there is no "created" time then use the current time
551                 if ($created_time <= 0) {
552                         $created_time = $now;
553                 }
554
555                 // If the last contact was less than 24 hours then don't update
556                 if (($now - $contact_time) < (60 * 60 * 24)) {
557                         return false;
558                 }
559
560                 // If the last failure was less than 24 hours then don't update
561                 if (($now - $failure_time) < (60 * 60 * 24)) {
562                         return false;
563                 }
564
565                 // If the last contact was less than a week ago and the last failure is older than a week then don't update
566                 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
567                 //      return false;
568
569                 // If the last contact time was more than a week ago and the contact was created more than a week ago, then only try once a week
570                 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
571                         return false;
572                 }
573
574                 // If the last contact time was more than a month ago and the contact was created more than a month ago, then only try once a month
575                 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
576                         return false;
577                 }
578
579                 return true;
580         }
581
582         private static function toBoolean($val)
583         {
584                 if (($val == "true") || ($val == 1)) {
585                         return true;
586                 } elseif (($val == "false") || ($val == 0)) {
587                         return false;
588                 }
589
590                 return $val;
591         }
592
593         /**
594          * @brief Detect server type (Hubzilla or Friendica) via the poco data
595          *
596          * @param object $data POCO data
597          * @return array Server data
598          */
599         private static function detectPocoData($data)
600         {
601                 $server = false;
602
603                 if (!isset($data->entry)) {
604                         return false;
605                 }
606
607                 if (count($data->entry) == 0) {
608                         return false;
609                 }
610
611                 if (!isset($data->entry[0]->urls)) {
612                         return false;
613                 }
614
615                 if (count($data->entry[0]->urls) == 0) {
616                         return false;
617                 }
618
619                 foreach ($data->entry[0]->urls as $url) {
620                         if ($url->type == 'zot') {
621                                 $server = [];
622                                 $server["platform"] = 'Hubzilla';
623                                 $server["network"] = NETWORK_DIASPORA;
624                                 return $server;
625                         }
626                 }
627                 return false;
628         }
629
630         /**
631          * @brief Detect server type by using the nodeinfo data
632          *
633          * @param string $server_url address of the server
634          * @return array Server data
635          */
636         private static function fetchNodeinfo($server_url)
637         {
638                 $serverret = Network::curl($server_url."/.well-known/nodeinfo");
639                 if (!$serverret["success"]) {
640                         return false;
641                 }
642
643                 $nodeinfo = json_decode($serverret['body']);
644
645                 if (!is_object($nodeinfo)) {
646                         return false;
647                 }
648
649                 if (!is_array($nodeinfo->links)) {
650                         return false;
651                 }
652
653                 $nodeinfo1_url = '';
654                 $nodeinfo2_url = '';
655
656                 foreach ($nodeinfo->links as $link) {
657                         if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
658                                 $nodeinfo1_url = $link->href;
659                         }
660                         if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
661                                 $nodeinfo2_url = $link->href;
662                         }
663                 }
664
665                 if ($nodeinfo1_url . $nodeinfo2_url == '') {
666                         return false;
667                 }
668
669                 $server = [];
670
671                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
672                 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
673                         $server = self::parseNodeinfo2($nodeinfo2_url);
674                 }
675
676                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
677                 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
678                         $server = self::parseNodeinfo1($nodeinfo1_url);
679                 }
680
681                 return $server;
682         }
683
684         /**
685          * @brief Parses Nodeinfo 1
686          *
687          * @param string $nodeinfo_url address of the nodeinfo path
688          * @return array Server data
689          */
690         private static function parseNodeinfo1($nodeinfo_url)
691         {
692                 $serverret = Network::curl($nodeinfo_url);
693                 if (!$serverret["success"]) {
694                         return false;
695                 }
696
697                 $nodeinfo = json_decode($serverret['body']);
698                 if (!is_object($nodeinfo)) {
699                         return false;
700                 }
701
702                 $server = [];
703
704                 $server['register_policy'] = REGISTER_CLOSED;
705
706                 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
707                         $server['register_policy'] = REGISTER_OPEN;
708                 }
709
710                 if (is_object($nodeinfo->software)) {
711                         if (isset($nodeinfo->software->name)) {
712                                 $server['platform'] = $nodeinfo->software->name;
713                         }
714
715                         if (isset($nodeinfo->software->version)) {
716                                 $server['version'] = $nodeinfo->software->version;
717                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
718                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
719                                 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
720                         }
721                 }
722
723                 if (is_object($nodeinfo->metadata)) {
724                         if (isset($nodeinfo->metadata->nodeName)) {
725                                 $server['site_name'] = $nodeinfo->metadata->nodeName;
726                         }
727                 }
728
729                 if (!empty($nodeinfo->usage->users->total)) {
730                         $server['registered-users'] = $nodeinfo->usage->users->total;
731                 }
732
733                 $diaspora = false;
734                 $friendica = false;
735                 $gnusocial = false;
736
737                 if (is_array($nodeinfo->protocols->inbound)) {
738                         foreach ($nodeinfo->protocols->inbound as $inbound) {
739                                 if ($inbound == 'diaspora') {
740                                         $diaspora = true;
741                                 }
742                                 if ($inbound == 'friendica') {
743                                         $friendica = true;
744                                 }
745                                 if ($inbound == 'gnusocial') {
746                                         $gnusocial = true;
747                                 }
748                         }
749                 }
750
751                 if ($gnusocial) {
752                         $server['network'] = NETWORK_OSTATUS;
753                 }
754                 if ($diaspora) {
755                         $server['network'] = NETWORK_DIASPORA;
756                 }
757                 if ($friendica) {
758                         $server['network'] = NETWORK_DFRN;
759                 }
760
761                 if (!$server) {
762                         return false;
763                 }
764
765                 return $server;
766         }
767
768         /**
769          * @brief Parses Nodeinfo 2
770          *
771          * @param string $nodeinfo_url address of the nodeinfo path
772          * @return array Server data
773          */
774         private static function parseNodeinfo2($nodeinfo_url)
775         {
776                 $serverret = Network::curl($nodeinfo_url);
777                 if (!$serverret["success"]) {
778                         return false;
779                 }
780
781                 $nodeinfo = json_decode($serverret['body']);
782                 if (!is_object($nodeinfo)) {
783                         return false;
784                 }
785
786                 $server = [];
787
788                 $server['register_policy'] = REGISTER_CLOSED;
789
790                 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
791                         $server['register_policy'] = REGISTER_OPEN;
792                 }
793
794                 if (is_object($nodeinfo->software)) {
795                         if (isset($nodeinfo->software->name)) {
796                                 $server['platform'] = $nodeinfo->software->name;
797                         }
798
799                         if (isset($nodeinfo->software->version)) {
800                                 $server['version'] = $nodeinfo->software->version;
801                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
802                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
803                                 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
804                         }
805                 }
806
807                 if (is_object($nodeinfo->metadata)) {
808                         if (isset($nodeinfo->metadata->nodeName)) {
809                                 $server['site_name'] = $nodeinfo->metadata->nodeName;
810                         }
811                 }
812
813                 if (!empty($nodeinfo->usage->users->total)) {
814                         $server['registered-users'] = $nodeinfo->usage->users->total;
815                 }
816
817                 $diaspora = false;
818                 $friendica = false;
819                 $gnusocial = false;
820
821                 if (is_array($nodeinfo->protocols)) {
822                         foreach ($nodeinfo->protocols as $protocol) {
823                                 if ($protocol == 'diaspora') {
824                                         $diaspora = true;
825                                 }
826                                 if ($protocol == 'friendica') {
827                                         $friendica = true;
828                                 }
829                                 if ($protocol == 'gnusocial') {
830                                         $gnusocial = true;
831                                 }
832                         }
833                 }
834
835                 if ($gnusocial) {
836                         $server['network'] = NETWORK_OSTATUS;
837                 }
838                 if ($diaspora) {
839                         $server['network'] = NETWORK_DIASPORA;
840                 }
841                 if ($friendica) {
842                         $server['network'] = NETWORK_DFRN;
843                 }
844
845                 if (!$server) {
846                         return false;
847                 }
848
849                 return $server;
850         }
851
852         /**
853          * @brief Detect server type (Hubzilla or Friendica) via the front page body
854          *
855          * @param string $body Front page of the server
856          * @return array Server data
857          */
858         private static function detectServerType($body)
859         {
860                 $server = false;
861
862                 $doc = new DOMDocument();
863                 @$doc->loadHTML($body);
864                 $xpath = new DOMXPath($doc);
865
866                 $list = $xpath->query("//meta[@name]");
867
868                 foreach ($list as $node) {
869                         $attr = [];
870                         if ($node->attributes->length) {
871                                 foreach ($node->attributes as $attribute) {
872                                         $attr[$attribute->name] = $attribute->value;
873                                 }
874                         }
875                         if ($attr['name'] == 'generator') {
876                                 $version_part = explode(" ", $attr['content']);
877                                 if (count($version_part) == 2) {
878                                         if (in_array($version_part[0], ["Friendika", "Friendica"])) {
879                                                 $server = [];
880                                                 $server["platform"] = $version_part[0];
881                                                 $server["version"] = $version_part[1];
882                                                 $server["network"] = NETWORK_DFRN;
883                                         }
884                                 }
885                         }
886                 }
887
888                 if (!$server) {
889                         $list = $xpath->query("//meta[@property]");
890
891                         foreach ($list as $node) {
892                                 $attr = [];
893                                 if ($node->attributes->length) {
894                                         foreach ($node->attributes as $attribute) {
895                                                 $attr[$attribute->name] = $attribute->value;
896                                         }
897                                 }
898                                 if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
899                                         $server = [];
900                                         $server["platform"] = $attr['content'];
901                                         $server["version"] = "";
902                                         $server["network"] = NETWORK_DIASPORA;
903                                 }
904                         }
905                 }
906
907                 if (!$server) {
908                         return false;
909                 }
910
911                 $server["site_name"] = $xpath->evaluate("//head/title/text()")->item(0)->nodeValue;
912                 return $server;
913         }
914
915         public static function checkServer($server_url, $network = "", $force = false)
916         {
917                 // Unify the server address
918                 $server_url = trim($server_url, "/");
919                 $server_url = str_replace("/index.php", "", $server_url);
920
921                 if ($server_url == "") {
922                         return false;
923                 }
924
925                 $gserver = dba::selectFirst('gserver', [], ['nurl' => normalise_link($server_url)]);
926                 if (DBM::is_result($gserver)) {
927                         if ($gserver["created"] <= NULL_DATE) {
928                                 $fields = ['created' => DateTimeFormat::utcNow()];
929                                 $condition = ['nurl' => normalise_link($server_url)];
930                                 dba::update('gserver', $fields, $condition);
931                         }
932                         $poco = $gserver["poco"];
933                         $noscrape = $gserver["noscrape"];
934
935                         if ($network == "") {
936                                 $network = $gserver["network"];
937                         }
938
939                         $last_contact = $gserver["last_contact"];
940                         $last_failure = $gserver["last_failure"];
941                         $version = $gserver["version"];
942                         $platform = $gserver["platform"];
943                         $site_name = $gserver["site_name"];
944                         $info = $gserver["info"];
945                         $register_policy = $gserver["register_policy"];
946                         $registered_users = $gserver["registered-users"];
947
948                         // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
949                         // It can happen that a zero date is in the database, but storing it again is forbidden.
950                         if ($last_contact < NULL_DATE) {
951                                 $last_contact = NULL_DATE;
952                         }
953                         if ($last_failure < NULL_DATE) {
954                                 $last_failure = NULL_DATE;
955                         }
956
957                         if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
958                                 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
959                                 return ($last_contact >= $last_failure);
960                         }
961                 } else {
962                         $poco = "";
963                         $noscrape = "";
964                         $version = "";
965                         $platform = "";
966                         $site_name = "";
967                         $info = "";
968                         $register_policy = -1;
969                         $registered_users = 0;
970
971                         $last_contact = NULL_DATE;
972                         $last_failure = NULL_DATE;
973                 }
974                 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
975
976                 $failure = false;
977                 $possible_failure = false;
978                 $orig_last_failure = $last_failure;
979                 $orig_last_contact = $last_contact;
980
981                 // Mastodon uses the "@" for user profiles.
982                 // But this can be misunderstood.
983                 if (parse_url($server_url, PHP_URL_USER) != '') {
984                         dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
985                         return false;
986                 }
987
988                 // Check if the page is accessible via SSL.
989                 $orig_server_url = $server_url;
990                 $server_url = str_replace("http://", "https://", $server_url);
991
992                 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
993                 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
994
995                 // Quit if there is a timeout.
996                 // But we want to make sure to only quit if we are mostly sure that this server url fits.
997                 if (DBM::is_result($gserver) && ($orig_server_url == $server_url) &&
998                         ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
999                         logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1000                         dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1001                         return false;
1002                 }
1003
1004                 // Maybe the page is unencrypted only?
1005                 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1006                 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
1007                         $server_url = str_replace("https://", "http://", $server_url);
1008
1009                         // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1010                         $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1011
1012                         // Quit if there is a timeout
1013                         if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1014                                 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1015                                 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1016                                 return false;
1017                         }
1018
1019                         $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1020                 }
1021
1022                 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
1023                         // Workaround for bad configured servers (known nginx problem)
1024                         if (!in_array($serverret["debug"]["http_code"], ["403", "404"])) {
1025                                 $failure = true;
1026                         }
1027                         $possible_failure = true;
1028                 }
1029
1030                 // If the server has no possible failure we reset the cached data
1031                 if (!$possible_failure) {
1032                         $version = "";
1033                         $platform = "";
1034                         $site_name = "";
1035                         $info = "";
1036                         $register_policy = -1;
1037                 }
1038
1039                 if (!$failure) {
1040                         // This will be too low, but better than no value at all.
1041                         $registered_users = dba::count('gcontact', ['server_url' => normalise_link($server_url)]);
1042                 }
1043
1044                 // Look for poco
1045                 if (!$failure) {
1046                         $serverret = Network::curl($server_url."/poco");
1047                         if ($serverret["success"]) {
1048                                 $data = json_decode($serverret["body"]);
1049                                 if (isset($data->totalResults)) {
1050                                         $registered_users = $data->totalResults;
1051                                         $poco = $server_url."/poco";
1052                                         $server = self::detectPocoData($data);
1053                                         if ($server) {
1054                                                 $platform = $server['platform'];
1055                                                 $network = $server['network'];
1056                                                 $version = '';
1057                                                 $site_name = '';
1058                                         }
1059                                 }
1060                                 // There are servers out there who don't return 404 on a failure
1061                                 // We have to be sure that don't misunderstand this
1062                                 if (is_null($data)) {
1063                                         $poco = "";
1064                                         $noscrape = "";
1065                                         $network = "";
1066                                 }
1067                         }
1068                 }
1069
1070                 if (!$failure) {
1071                         // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1072                         $serverret = Network::curl($server_url);
1073
1074                         if (!$serverret["success"] || ($serverret["body"] == "")) {
1075                                 $failure = true;
1076                         } else {
1077                                 $server = self::detectServerType($serverret["body"]);
1078                                 if ($server) {
1079                                         $platform = $server['platform'];
1080                                         $network = $server['network'];
1081                                         $version = $server['version'];
1082                                         $site_name = $server['site_name'];
1083                                 }
1084
1085                                 $lines = explode("\n", $serverret["header"]);
1086                                 if (count($lines)) {
1087                                         foreach ($lines as $line) {
1088                                                 $line = trim($line);
1089                                                 if (stristr($line, 'X-Diaspora-Version:')) {
1090                                                         $platform = "Diaspora";
1091                                                         $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1092                                                         $version = trim(str_replace("x-diaspora-version:", "", $version));
1093                                                         $network = NETWORK_DIASPORA;
1094                                                         $versionparts = explode("-", $version);
1095                                                         $version = $versionparts[0];
1096                                                 }
1097
1098                                                 if (stristr($line, 'Server: Mastodon')) {
1099                                                         $platform = "Mastodon";
1100                                                         $network = NETWORK_OSTATUS;
1101                                                 }
1102                                         }
1103                                 }
1104                         }
1105                 }
1106
1107                 if (!$failure && ($poco == "")) {
1108                         // Test for Statusnet
1109                         // Will also return data for Friendica and GNU Social - but it will be overwritten later
1110                         // The "not implemented" is a special treatment for really, really old Friendica versions
1111                         $serverret = Network::curl($server_url."/api/statusnet/version.json");
1112                         if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1113                                 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1114                                 $platform = "StatusNet";
1115                                 // Remove junk that some GNU Social servers return
1116                                 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1117                                 $version = trim($version, '"');
1118                                 $network = NETWORK_OSTATUS;
1119                         }
1120
1121                         // Test for GNU Social
1122                         $serverret = Network::curl($server_url."/api/gnusocial/version.json");
1123                         if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1124                                 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1125                                 $platform = "GNU Social";
1126                                 // Remove junk that some GNU Social servers return
1127                                 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1128                                 $version = trim($version, '"');
1129                                 $network = NETWORK_OSTATUS;
1130                         }
1131
1132                         // Test for Mastodon
1133                         $orig_version = $version;
1134                         $serverret = Network::curl($server_url."/api/v1/instance");
1135                         if ($serverret["success"] && ($serverret["body"] != '')) {
1136                                 $data = json_decode($serverret["body"]);
1137
1138                                 if (isset($data->version)) {
1139                                         $platform = "Mastodon";
1140                                         $version = $data->version;
1141                                         $site_name = $data->title;
1142                                         $info = $data->description;
1143                                         $network = NETWORK_OSTATUS;
1144                                 }
1145                                 if (!empty($data->stats->user_count)) {
1146                                         $registered_users = $data->stats->user_count;
1147                                 }
1148                         }
1149                         if (strstr($orig_version.$version, 'Pleroma')) {
1150                                 $platform = 'Pleroma';
1151                                 $version = trim(str_replace('Pleroma', '', $version));
1152                         }
1153                 }
1154
1155                 if (!$failure) {
1156                         // Test for Hubzilla and Red
1157                         $serverret = Network::curl($server_url."/siteinfo.json");
1158                         if ($serverret["success"]) {
1159                                 $data = json_decode($serverret["body"]);
1160                                 if (isset($data->url)) {
1161                                         $platform = $data->platform;
1162                                         $version = $data->version;
1163                                         $network = NETWORK_DIASPORA;
1164                                 }
1165                                 if (!empty($data->site_name)) {
1166                                         $site_name = $data->site_name;
1167                                 }
1168                                 if (!empty($data->channels_total)) {
1169                                         $registered_users = $data->channels_total;
1170                                 }
1171                                 switch ($data->register_policy) {
1172                                         case "REGISTER_OPEN":
1173                                                 $register_policy = REGISTER_OPEN;
1174                                                 break;
1175                                         case "REGISTER_APPROVE":
1176                                                 $register_policy = REGISTER_APPROVE;
1177                                                 break;
1178                                         case "REGISTER_CLOSED":
1179                                         default:
1180                                                 $register_policy = REGISTER_CLOSED;
1181                                                 break;
1182                                 }
1183                         } else {
1184                                 // Test for Hubzilla, Redmatrix or Friendica
1185                                 $serverret = Network::curl($server_url."/api/statusnet/config.json");
1186                                 if ($serverret["success"]) {
1187                                         $data = json_decode($serverret["body"]);
1188                                         if (isset($data->site->server)) {
1189                                                 if (isset($data->site->platform)) {
1190                                                         $platform = $data->site->platform->PLATFORM_NAME;
1191                                                         $version = $data->site->platform->STD_VERSION;
1192                                                         $network = NETWORK_DIASPORA;
1193                                                 }
1194                                                 if (isset($data->site->BlaBlaNet)) {
1195                                                         $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1196                                                         $version = $data->site->BlaBlaNet->STD_VERSION;
1197                                                         $network = NETWORK_DIASPORA;
1198                                                 }
1199                                                 if (isset($data->site->hubzilla)) {
1200                                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
1201                                                         $version = $data->site->hubzilla->RED_VERSION;
1202                                                         $network = NETWORK_DIASPORA;
1203                                                 }
1204                                                 if (isset($data->site->redmatrix)) {
1205                                                         if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1206                                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
1207                                                         } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1208                                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
1209                                                         }
1210
1211                                                         $version = $data->site->redmatrix->RED_VERSION;
1212                                                         $network = NETWORK_DIASPORA;
1213                                                 }
1214                                                 if (isset($data->site->friendica)) {
1215                                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1216                                                         $version = $data->site->friendica->FRIENDICA_VERSION;
1217                                                         $network = NETWORK_DFRN;
1218                                                 }
1219
1220                                                 $site_name = $data->site->name;
1221
1222                                                 $data->site->closed = self::toBoolean($data->site->closed);
1223                                                 $data->site->private = self::toBoolean($data->site->private);
1224                                                 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1225
1226                                                 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1227                                                         $register_policy = REGISTER_APPROVE;
1228                                                 } elseif (!$data->site->closed && !$data->site->private) {
1229                                                         $register_policy = REGISTER_OPEN;
1230                                                 } else {
1231                                                         $register_policy = REGISTER_CLOSED;
1232                                                 }
1233                                         }
1234                                 }
1235                         }
1236                 }
1237
1238                 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1239                 if (!$failure) {
1240                         $serverret = Network::curl($server_url."/statistics.json");
1241                         if ($serverret["success"]) {
1242                                 $data = json_decode($serverret["body"]);
1243
1244                                 if (isset($data->version)) {
1245                                         $version = $data->version;
1246                                         // Version numbers on statistics.json are presented with additional info, e.g.:
1247                                         // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1248                                         $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1249                                 }
1250
1251                                 if (!empty($data->name)) {
1252                                         $site_name = $data->name;
1253                                 }
1254
1255                                 if (!empty($data->network)) {
1256                                         $platform = $data->network;
1257                                 }
1258
1259                                 if ($platform == "Diaspora") {
1260                                         $network = NETWORK_DIASPORA;
1261                                 }
1262
1263                                 if ($data->registrations_open) {
1264                                         $register_policy = REGISTER_OPEN;
1265                                 } else {
1266                                         $register_policy = REGISTER_CLOSED;
1267                                 }
1268                         }
1269                 }
1270
1271                 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1272                 if (!$failure) {
1273                         $server = self::fetchNodeinfo($server_url);
1274                         if ($server) {
1275                                 $register_policy = $server['register_policy'];
1276
1277                                 if (isset($server['platform'])) {
1278                                         $platform = $server['platform'];
1279                                 }
1280
1281                                 if (isset($server['network'])) {
1282                                         $network = $server['network'];
1283                                 }
1284
1285                                 if (isset($server['version'])) {
1286                                         $version = $server['version'];
1287                                 }
1288
1289                                 if (isset($server['site_name'])) {
1290                                         $site_name = $server['site_name'];
1291                                 }
1292
1293                                 if (isset($server['registered-users'])) {
1294                                         $registered_users = $server['registered-users'];
1295                                 }
1296                         }
1297                 }
1298
1299                 // Check for noscrape
1300                 // Friendica servers could be detected as OStatus servers
1301                 if (!$failure && in_array($network, [NETWORK_DFRN, NETWORK_OSTATUS])) {
1302                         $serverret = Network::curl($server_url."/friendica/json");
1303
1304                         if (!$serverret["success"]) {
1305                                 $serverret = Network::curl($server_url."/friendika/json");
1306                         }
1307
1308                         if ($serverret["success"]) {
1309                                 $data = json_decode($serverret["body"]);
1310
1311                                 if (isset($data->version)) {
1312                                         $network = NETWORK_DFRN;
1313
1314                                         $noscrape = defaults($data->no_scrape_url, '');
1315                                         $version = $data->version;
1316                                         $site_name = $data->site_name;
1317                                         $info = $data->info;
1318                                         $register_policy_str = $data->register_policy;
1319                                         $platform = $data->platform;
1320
1321                                         switch ($register_policy_str) {
1322                                                 case "REGISTER_CLOSED":
1323                                                         $register_policy = REGISTER_CLOSED;
1324                                                         break;
1325                                                 case "REGISTER_APPROVE":
1326                                                         $register_policy = REGISTER_APPROVE;
1327                                                         break;
1328                                                 case "REGISTER_OPEN":
1329                                                         $register_policy = REGISTER_OPEN;
1330                                                         break;
1331                                         }
1332                                 }
1333                         }
1334                 }
1335
1336                 // Every server has got at least an admin account
1337                 if (!$failure && ($registered_users == 0)) {
1338                         $registered_users = 1;
1339                 }
1340
1341                 if ($possible_failure && !$failure) {
1342                         $failure = true;
1343                 }
1344
1345                 if ($failure) {
1346                         $last_contact = $orig_last_contact;
1347                         $last_failure = DateTimeFormat::utcNow();
1348                 } else {
1349                         $last_contact = DateTimeFormat::utcNow();
1350                         $last_failure = $orig_last_failure;
1351                 }
1352
1353                 if (($last_contact <= $last_failure) && !$failure) {
1354                         logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1355                 } elseif (($last_contact >= $last_failure) && $failure) {
1356                         logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1357                 }
1358
1359                 // Check again if the server exists
1360                 $found = dba::exists('gserver', ['nurl' => normalise_link($server_url)]);
1361
1362                 $version = strip_tags($version);
1363                 $site_name = strip_tags($site_name);
1364                 $info = strip_tags($info);
1365                 $platform = strip_tags($platform);
1366
1367                 $fields = ['url' => $server_url, 'version' => $version,
1368                                 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1369                                 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1370                                 'platform' => $platform, 'registered-users' => $registered_users,
1371                                 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1372
1373                 if ($found) {
1374                         dba::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1375                 } elseif (!$failure) {
1376                         $fields['nurl'] = normalise_link($server_url);
1377                         $fields['created'] = DateTimeFormat::utcNow();
1378                         dba::insert('gserver', $fields);
1379                 }
1380
1381                 if (!$failure && in_array($fields['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1382                         self::discoverRelay($server_url);
1383                 }
1384
1385                 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1386
1387                 return !$failure;
1388         }
1389
1390         private static function discoverRelay($server_url)
1391         {
1392                 logger("Discover relay data for server " . $server_url, LOGGER_DEBUG);
1393
1394                 $serverret = Network::curl($server_url."/.well-known/x-social-relay");
1395                 if (!$serverret["success"]) {
1396                         return;
1397                 }
1398
1399                 $data = json_decode($serverret['body']);
1400                 if (!is_object($data)) {
1401                         return;
1402                 }
1403
1404                 $gserver = dba::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => normalise_link($server_url)]);
1405                 if (!DBM::is_result($gserver)) {
1406                         return;
1407                 }
1408
1409                 if (($gserver['relay-subscribe'] != $data->subscribe) || ($gserver['relay-scope'] != $data->scope)) {
1410                         $fields = ['relay-subscribe' => $data->subscribe, 'relay-scope' => $data->scope];
1411                         dba::update('gserver', $fields, ['id' => $gserver['id']]);
1412                 }
1413
1414                 dba::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1415                 if ($data->scope == 'tags') {
1416                         foreach ($data->tags as $tag) {
1417                                 dba::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag]);
1418                         }
1419                 }
1420         }
1421
1422         /**
1423          * @brief Returns a list of all known servers
1424          * @return array List of server urls
1425          */
1426         public static function serverlist()
1427         {
1428                 $r = q(
1429                         "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1430                         WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1431                         ORDER BY `last_contact`
1432                         LIMIT 1000",
1433                         dbesc(NETWORK_DFRN),
1434                         dbesc(NETWORK_DIASPORA),
1435                         dbesc(NETWORK_OSTATUS)
1436                 );
1437
1438                 if (!DBM::is_result($r)) {
1439                         return false;
1440                 }
1441
1442                 return $r;
1443         }
1444
1445         /**
1446          * @brief Fetch server list from remote servers and adds them when they are new.
1447          *
1448          * @param string $poco URL to the POCO endpoint
1449          */
1450         private static function fetchServerlist($poco)
1451         {
1452                 $serverret = Network::curl($poco."/@server");
1453                 if (!$serverret["success"]) {
1454                         return;
1455                 }
1456                 $serverlist = json_decode($serverret['body']);
1457
1458                 if (!is_array($serverlist)) {
1459                         return;
1460                 }
1461
1462                 foreach ($serverlist as $server) {
1463                         $server_url = str_replace("/index.php", "", $server->url);
1464
1465                         $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1466                         if (!DBM::is_result($r)) {
1467                                 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1468                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1469                         }
1470                 }
1471         }
1472
1473         private static function discoverFederation()
1474         {
1475                 $last = Config::get('poco', 'last_federation_discovery');
1476
1477                 if ($last) {
1478                         $next = $last + (24 * 60 * 60);
1479                         if ($next > time()) {
1480                                 return;
1481                         }
1482                 }
1483
1484                 // Discover Friendica, Hubzilla and Diaspora servers
1485                 $serverdata = Network::fetchUrl("http://the-federation.info/pods.json");
1486
1487                 if ($serverdata) {
1488                         $servers = json_decode($serverdata);
1489
1490                         foreach ($servers->pods as $server) {
1491                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1492                         }
1493                 }
1494
1495                 // Disvover Mastodon servers
1496                 if (!Config::get('system', 'ostatus_disabled')) {
1497                         $accesstoken = Config::get('system', 'instances_social_key');
1498                         if (!empty($accesstoken)) {
1499                                 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1500                                 $header = ['Authorization: Bearer '.$accesstoken];
1501                                 $serverdata = Network::curl($api, false, $redirects, ['headers' => $header]);
1502                                 if ($serverdata['success']) {
1503                                         $servers = json_decode($serverdata['body']);
1504                                         foreach ($servers->instances as $server) {
1505                                                 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1506                                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1507                                         }
1508                                 }
1509                         }
1510                 }
1511
1512                 // Currently disabled, since the service isn't available anymore.
1513                 // It is not removed since I hope that there will be a successor.
1514                 // Discover GNU Social Servers.
1515                 //if (!Config::get('system','ostatus_disabled')) {
1516                 //      $serverdata = "http://gstools.org/api/get_open_instances/";
1517
1518                 //      $result = Network::curl($serverdata);
1519                 //      if ($result["success"]) {
1520                 //              $servers = json_decode($result["body"]);
1521
1522                 //              foreach($servers->data as $server)
1523                 //                      self::checkServer($server->instance_address);
1524                 //      }
1525                 //}
1526
1527                 Config::set('poco', 'last_federation_discovery', time());
1528         }
1529
1530         public static function discoverSingleServer($id)
1531         {
1532                 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1533                 if (!DBM::is_result($r)) {
1534                         return false;
1535                 }
1536
1537                 $server = $r[0];
1538
1539                 // Discover new servers out there (Works from Friendica version 3.5.2)
1540                 self::fetchServerlist($server["poco"]);
1541
1542                 // Fetch all users from the other server
1543                 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1544
1545                 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1546
1547                 $retdata = Network::curl($url);
1548                 if ($retdata["success"]) {
1549                         $data = json_decode($retdata["body"]);
1550
1551                         self::discoverServer($data, 2);
1552
1553                         if (Config::get('system', 'poco_discovery') > 1) {
1554                                 $timeframe = Config::get('system', 'poco_discovery_since');
1555                                 if ($timeframe == 0) {
1556                                         $timeframe = 30;
1557                                 }
1558
1559                                 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1560
1561                                 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1562                                 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1563
1564                                 $success = false;
1565
1566                                 $retdata = Network::curl($url);
1567                                 if ($retdata["success"]) {
1568                                         logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1569                                         $success = self::discoverServer(json_decode($retdata["body"]));
1570                                 }
1571
1572                                 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1573                                         logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1574                                         self::discoverServerUsers($data, $server);
1575                                 }
1576                         }
1577
1578                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1579                         dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1580
1581                         return true;
1582                 } else {
1583                         // If the server hadn't replied correctly, then force a sanity check
1584                         self::checkServer($server["url"], $server["network"], true);
1585
1586                         // If we couldn't reach the server, we will try it some time later
1587                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1588                         dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1589
1590                         return false;
1591                 }
1592         }
1593
1594         public static function discover($complete = false)
1595         {
1596                 // Update the server list
1597                 self::discoverFederation();
1598
1599                 $no_of_queries = 5;
1600
1601                 $requery_days = intval(Config::get("system", "poco_requery_days"));
1602
1603                 if ($requery_days == 0) {
1604                         $requery_days = 7;
1605                 }
1606                 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1607
1608                 $r = q("SELECT `id`, `url`, `network` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `poco` != '' AND `last_poco_query` < '%s' ORDER BY RAND()", dbesc($last_update));
1609                 if (DBM::is_result($r)) {
1610                         foreach ($r as $server) {
1611                                 if (!self::checkServer($server["url"], $server["network"])) {
1612                                         // The server is not reachable? Okay, then we will try it later
1613                                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1614                                         dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1615                                         continue;
1616                                 }
1617
1618                                 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1619                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "update_server_directory", (int)$server['id']);
1620
1621                                 if (!$complete && (--$no_of_queries == 0)) {
1622                                         break;
1623                                 }
1624                         }
1625                 }
1626         }
1627
1628         private static function discoverServerUsers($data, $server)
1629         {
1630                 if (!isset($data->entry)) {
1631                         return;
1632                 }
1633
1634                 foreach ($data->entry as $entry) {
1635                         $username = "";
1636                         if (isset($entry->urls)) {
1637                                 foreach ($entry->urls as $url) {
1638                                         if ($url->type == 'profile') {
1639                                                 $profile_url = $url->value;
1640                                                 $urlparts = parse_url($profile_url);
1641                                                 $username = end(explode("/", $urlparts["path"]));
1642                                         }
1643                                 }
1644                         }
1645                         if ($username != "") {
1646                                 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1647
1648                                 // Fetch all contacts from a given user from the other server
1649                                 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1650
1651                                 $retdata = Network::curl($url);
1652                                 if ($retdata["success"]) {
1653                                         self::discoverServer(json_decode($retdata["body"]), 3);
1654                                 }
1655                         }
1656                 }
1657         }
1658
1659         private static function discoverServer($data, $default_generation = 0)
1660         {
1661                 if (!isset($data->entry) || !count($data->entry)) {
1662                         return false;
1663                 }
1664
1665                 $success = false;
1666
1667                 foreach ($data->entry as $entry) {
1668                         $profile_url = '';
1669                         $profile_photo = '';
1670                         $connect_url = '';
1671                         $name = '';
1672                         $network = '';
1673                         $updated = NULL_DATE;
1674                         $location = '';
1675                         $about = '';
1676                         $keywords = '';
1677                         $gender = '';
1678                         $contact_type = -1;
1679                         $generation = $default_generation;
1680
1681                         $name = $entry->displayName;
1682
1683                         if (isset($entry->urls)) {
1684                                 foreach ($entry->urls as $url) {
1685                                         if ($url->type == 'profile') {
1686                                                 $profile_url = $url->value;
1687                                                 continue;
1688                                         }
1689                                         if ($url->type == 'webfinger') {
1690                                                 $connect_url = str_replace('acct:' , '', $url->value);
1691                                                 continue;
1692                                         }
1693                                 }
1694                         }
1695
1696                         if (isset($entry->photos)) {
1697                                 foreach ($entry->photos as $photo) {
1698                                         if ($photo->type == 'profile') {
1699                                                 $profile_photo = $photo->value;
1700                                                 continue;
1701                                         }
1702                                 }
1703                         }
1704
1705                         if (isset($entry->updated)) {
1706                                 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
1707                         }
1708
1709                         if (isset($entry->network)) {
1710                                 $network = $entry->network;
1711                         }
1712
1713                         if (isset($entry->currentLocation)) {
1714                                 $location = $entry->currentLocation;
1715                         }
1716
1717                         if (isset($entry->aboutMe)) {
1718                                 $about = HTML::toBBCode($entry->aboutMe);
1719                         }
1720
1721                         if (isset($entry->gender)) {
1722                                 $gender = $entry->gender;
1723                         }
1724
1725                         if (isset($entry->generation) && ($entry->generation > 0)) {
1726                                 $generation = ++$entry->generation;
1727                         }
1728
1729                         if (isset($entry->contactType) && ($entry->contactType >= 0)) {
1730                                 $contact_type = $entry->contactType;
1731                         }
1732
1733                         if (isset($entry->tags)) {
1734                                 foreach ($entry->tags as $tag) {
1735                                         $keywords = implode(", ", $tag);
1736                                 }
1737                         }
1738
1739                         if ($generation > 0) {
1740                                 $success = true;
1741
1742                                 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1743
1744                                 $gcontact = ["url" => $profile_url,
1745                                                 "name" => $name,
1746                                                 "network" => $network,
1747                                                 "photo" => $profile_photo,
1748                                                 "about" => $about,
1749                                                 "location" => $location,
1750                                                 "gender" => $gender,
1751                                                 "keywords" => $keywords,
1752                                                 "connect" => $connect_url,
1753                                                 "updated" => $updated,
1754                                                 "contact-type" => $contact_type,
1755                                                 "generation" => $generation];
1756
1757                                 try {
1758                                         $gcontact = GContact::sanitize($gcontact);
1759                                         GContact::update($gcontact);
1760                                 } catch (Exception $e) {
1761                                         logger($e->getMessage(), LOGGER_DEBUG);
1762                                 }
1763
1764                                 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1765                         }
1766                 }
1767                 return $success;
1768         }
1769
1770 }