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