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