Merge pull request #5030 from annando/fix-sql
[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 = ['last_contact' => DateTimeFormat::utcNow()];
526
527                 if (!empty($last_updated)) {
528                         $fields['updated'] = $last_updated;
529                 }
530
531                 dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
532
533                 if (($gcontacts[0]["generation"] == 0)) {
534                         $fields = ['generation' => 9];
535                         dba::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
536                 }
537
538                 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
539
540                 return $last_updated;
541         }
542
543         public static function updateNeeded($created, $updated, $last_failure, $last_contact)
544         {
545                 $now = strtotime(DateTimeFormat::utcNow());
546
547                 if ($updated > $last_contact) {
548                         $contact_time = strtotime($updated);
549                 } else {
550                         $contact_time = strtotime($last_contact);
551                 }
552
553                 $failure_time = strtotime($last_failure);
554                 $created_time = strtotime($created);
555
556                 // If there is no "created" time then use the current time
557                 if ($created_time <= 0) {
558                         $created_time = $now;
559                 }
560
561                 // If the last contact was less than 24 hours then don't update
562                 if (($now - $contact_time) < (60 * 60 * 24)) {
563                         return false;
564                 }
565
566                 // If the last failure was less than 24 hours then don't update
567                 if (($now - $failure_time) < (60 * 60 * 24)) {
568                         return false;
569                 }
570
571                 // If the last contact was less than a week ago and the last failure is older than a week then don't update
572                 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
573                 //      return false;
574
575                 // 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
576                 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
577                         return false;
578                 }
579
580                 // 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
581                 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
582                         return false;
583                 }
584
585                 return true;
586         }
587
588         private static function toBoolean($val)
589         {
590                 if (($val == "true") || ($val == 1)) {
591                         return true;
592                 } elseif (($val == "false") || ($val == 0)) {
593                         return false;
594                 }
595
596                 return $val;
597         }
598
599         /**
600          * @brief Detect server type (Hubzilla or Friendica) via the poco data
601          *
602          * @param object $data POCO data
603          * @return array Server data
604          */
605         private static function detectPocoData($data)
606         {
607                 $server = false;
608
609                 if (!isset($data->entry)) {
610                         return false;
611                 }
612
613                 if (count($data->entry) == 0) {
614                         return false;
615                 }
616
617                 if (!isset($data->entry[0]->urls)) {
618                         return false;
619                 }
620
621                 if (count($data->entry[0]->urls) == 0) {
622                         return false;
623                 }
624
625                 foreach ($data->entry[0]->urls as $url) {
626                         if ($url->type == 'zot') {
627                                 $server = [];
628                                 $server["platform"] = 'Hubzilla';
629                                 $server["network"] = NETWORK_DIASPORA;
630                                 return $server;
631                         }
632                 }
633                 return false;
634         }
635
636         /**
637          * @brief Detect server type by using the nodeinfo data
638          *
639          * @param string $server_url address of the server
640          * @return array Server data
641          */
642         private static function fetchNodeinfo($server_url)
643         {
644                 $serverret = Network::curl($server_url."/.well-known/nodeinfo");
645                 if (!$serverret["success"]) {
646                         return false;
647                 }
648
649                 $nodeinfo = json_decode($serverret['body']);
650
651                 if (!is_object($nodeinfo)) {
652                         return false;
653                 }
654
655                 if (!is_array($nodeinfo->links)) {
656                         return false;
657                 }
658
659                 $nodeinfo1_url = '';
660                 $nodeinfo2_url = '';
661
662                 foreach ($nodeinfo->links as $link) {
663                         if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
664                                 $nodeinfo1_url = $link->href;
665                         }
666                         if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
667                                 $nodeinfo2_url = $link->href;
668                         }
669                 }
670
671                 if ($nodeinfo1_url . $nodeinfo2_url == '') {
672                         return false;
673                 }
674
675                 $server = [];
676
677                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
678                 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
679                         $server = self::parseNodeinfo2($nodeinfo2_url);
680                 }
681
682                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
683                 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
684                         $server = self::parseNodeinfo1($nodeinfo1_url);
685                 }
686
687                 return $server;
688         }
689
690         /**
691          * @brief Parses Nodeinfo 1
692          *
693          * @param string $nodeinfo_url address of the nodeinfo path
694          * @return array Server data
695          */
696         private static function parseNodeinfo1($nodeinfo_url)
697         {
698                 $serverret = Network::curl($nodeinfo_url);
699                 if (!$serverret["success"]) {
700                         return false;
701                 }
702
703                 $nodeinfo = json_decode($serverret['body']);
704                 if (!is_object($nodeinfo)) {
705                         return false;
706                 }
707
708                 $server = [];
709
710                 $server['register_policy'] = REGISTER_CLOSED;
711
712                 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
713                         $server['register_policy'] = REGISTER_OPEN;
714                 }
715
716                 if (is_object($nodeinfo->software)) {
717                         if (isset($nodeinfo->software->name)) {
718                                 $server['platform'] = $nodeinfo->software->name;
719                         }
720
721                         if (isset($nodeinfo->software->version)) {
722                                 $server['version'] = $nodeinfo->software->version;
723                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
724                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
725                                 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
726                         }
727                 }
728
729                 if (is_object($nodeinfo->metadata)) {
730                         if (isset($nodeinfo->metadata->nodeName)) {
731                                 $server['site_name'] = $nodeinfo->metadata->nodeName;
732                         }
733                 }
734
735                 if (!empty($nodeinfo->usage->users->total)) {
736                         $server['registered-users'] = $nodeinfo->usage->users->total;
737                 }
738
739                 $diaspora = false;
740                 $friendica = false;
741                 $gnusocial = false;
742
743                 if (is_array($nodeinfo->protocols->inbound)) {
744                         foreach ($nodeinfo->protocols->inbound as $inbound) {
745                                 if ($inbound == 'diaspora') {
746                                         $diaspora = true;
747                                 }
748                                 if ($inbound == 'friendica') {
749                                         $friendica = true;
750                                 }
751                                 if ($inbound == 'gnusocial') {
752                                         $gnusocial = true;
753                                 }
754                         }
755                 }
756
757                 if ($gnusocial) {
758                         $server['network'] = NETWORK_OSTATUS;
759                 }
760                 if ($diaspora) {
761                         $server['network'] = NETWORK_DIASPORA;
762                 }
763                 if ($friendica) {
764                         $server['network'] = NETWORK_DFRN;
765                 }
766
767                 if (!$server) {
768                         return false;
769                 }
770
771                 return $server;
772         }
773
774         /**
775          * @brief Parses Nodeinfo 2
776          *
777          * @param string $nodeinfo_url address of the nodeinfo path
778          * @return array Server data
779          */
780         private static function parseNodeinfo2($nodeinfo_url)
781         {
782                 $serverret = Network::curl($nodeinfo_url);
783                 if (!$serverret["success"]) {
784                         return false;
785                 }
786
787                 $nodeinfo = json_decode($serverret['body']);
788                 if (!is_object($nodeinfo)) {
789                         return false;
790                 }
791
792                 $server = [];
793
794                 $server['register_policy'] = REGISTER_CLOSED;
795
796                 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
797                         $server['register_policy'] = REGISTER_OPEN;
798                 }
799
800                 if (is_object($nodeinfo->software)) {
801                         if (isset($nodeinfo->software->name)) {
802                                 $server['platform'] = $nodeinfo->software->name;
803                         }
804
805                         if (isset($nodeinfo->software->version)) {
806                                 $server['version'] = $nodeinfo->software->version;
807                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
808                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
809                                 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
810                         }
811                 }
812
813                 if (is_object($nodeinfo->metadata)) {
814                         if (isset($nodeinfo->metadata->nodeName)) {
815                                 $server['site_name'] = $nodeinfo->metadata->nodeName;
816                         }
817                 }
818
819                 if (!empty($nodeinfo->usage->users->total)) {
820                         $server['registered-users'] = $nodeinfo->usage->users->total;
821                 }
822
823                 $diaspora = false;
824                 $friendica = false;
825                 $gnusocial = false;
826
827                 if (is_array($nodeinfo->protocols)) {
828                         foreach ($nodeinfo->protocols as $protocol) {
829                                 if ($protocol == 'diaspora') {
830                                         $diaspora = true;
831                                 }
832                                 if ($protocol == 'friendica') {
833                                         $friendica = true;
834                                 }
835                                 if ($protocol == 'gnusocial') {
836                                         $gnusocial = true;
837                                 }
838                         }
839                 }
840
841                 if ($gnusocial) {
842                         $server['network'] = NETWORK_OSTATUS;
843                 }
844                 if ($diaspora) {
845                         $server['network'] = NETWORK_DIASPORA;
846                 }
847                 if ($friendica) {
848                         $server['network'] = NETWORK_DFRN;
849                 }
850
851                 if (!$server) {
852                         return false;
853                 }
854
855                 return $server;
856         }
857
858         /**
859          * @brief Detect server type (Hubzilla or Friendica) via the front page body
860          *
861          * @param string $body Front page of the server
862          * @return array Server data
863          */
864         private static function detectServerType($body)
865         {
866                 $server = false;
867
868                 $doc = new DOMDocument();
869                 @$doc->loadHTML($body);
870                 $xpath = new DOMXPath($doc);
871
872                 $list = $xpath->query("//meta[@name]");
873
874                 foreach ($list as $node) {
875                         $attr = [];
876                         if ($node->attributes->length) {
877                                 foreach ($node->attributes as $attribute) {
878                                         $attr[$attribute->name] = $attribute->value;
879                                 }
880                         }
881                         if ($attr['name'] == 'generator') {
882                                 $version_part = explode(" ", $attr['content']);
883                                 if (count($version_part) == 2) {
884                                         if (in_array($version_part[0], ["Friendika", "Friendica"])) {
885                                                 $server = [];
886                                                 $server["platform"] = $version_part[0];
887                                                 $server["version"] = $version_part[1];
888                                                 $server["network"] = NETWORK_DFRN;
889                                         }
890                                 }
891                         }
892                 }
893
894                 if (!$server) {
895                         $list = $xpath->query("//meta[@property]");
896
897                         foreach ($list as $node) {
898                                 $attr = [];
899                                 if ($node->attributes->length) {
900                                         foreach ($node->attributes as $attribute) {
901                                                 $attr[$attribute->name] = $attribute->value;
902                                         }
903                                 }
904                                 if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
905                                         $server = [];
906                                         $server["platform"] = $attr['content'];
907                                         $server["version"] = "";
908                                         $server["network"] = NETWORK_DIASPORA;
909                                 }
910                         }
911                 }
912
913                 if (!$server) {
914                         return false;
915                 }
916
917                 $server["site_name"] = $xpath->evaluate("//head/title/text()")->item(0)->nodeValue;
918                 return $server;
919         }
920
921         public static function checkServer($server_url, $network = "", $force = false)
922         {
923                 // Unify the server address
924                 $server_url = trim($server_url, "/");
925                 $server_url = str_replace("/index.php", "", $server_url);
926
927                 if ($server_url == "") {
928                         return false;
929                 }
930
931                 $gserver = dba::selectFirst('gserver', [], ['nurl' => normalise_link($server_url)]);
932                 if (DBM::is_result($gserver)) {
933                         if ($gserver["created"] <= NULL_DATE) {
934                                 $fields = ['created' => DateTimeFormat::utcNow()];
935                                 $condition = ['nurl' => normalise_link($server_url)];
936                                 dba::update('gserver', $fields, $condition);
937                         }
938                         $poco = $gserver["poco"];
939                         $noscrape = $gserver["noscrape"];
940
941                         if ($network == "") {
942                                 $network = $gserver["network"];
943                         }
944
945                         $last_contact = $gserver["last_contact"];
946                         $last_failure = $gserver["last_failure"];
947                         $version = $gserver["version"];
948                         $platform = $gserver["platform"];
949                         $site_name = $gserver["site_name"];
950                         $info = $gserver["info"];
951                         $register_policy = $gserver["register_policy"];
952                         $registered_users = $gserver["registered-users"];
953
954                         // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
955                         // It can happen that a zero date is in the database, but storing it again is forbidden.
956                         if ($last_contact < NULL_DATE) {
957                                 $last_contact = NULL_DATE;
958                         }
959                         if ($last_failure < NULL_DATE) {
960                                 $last_failure = NULL_DATE;
961                         }
962
963                         if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
964                                 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
965                                 return ($last_contact >= $last_failure);
966                         }
967                 } else {
968                         $poco = "";
969                         $noscrape = "";
970                         $version = "";
971                         $platform = "";
972                         $site_name = "";
973                         $info = "";
974                         $register_policy = -1;
975                         $registered_users = 0;
976
977                         $last_contact = NULL_DATE;
978                         $last_failure = NULL_DATE;
979                 }
980                 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
981
982                 $failure = false;
983                 $possible_failure = false;
984                 $orig_last_failure = $last_failure;
985                 $orig_last_contact = $last_contact;
986
987                 // Mastodon uses the "@" for user profiles.
988                 // But this can be misunderstood.
989                 if (parse_url($server_url, PHP_URL_USER) != '') {
990                         dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
991                         return false;
992                 }
993
994                 // Check if the page is accessible via SSL.
995                 $orig_server_url = $server_url;
996                 $server_url = str_replace("http://", "https://", $server_url);
997
998                 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
999                 $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1000
1001                 // Quit if there is a timeout.
1002                 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1003                 if (DBM::is_result($gserver) && ($orig_server_url == $server_url) &&
1004                         ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1005                         logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1006                         dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1007                         return false;
1008                 }
1009
1010                 // Maybe the page is unencrypted only?
1011                 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1012                 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
1013                         $server_url = str_replace("https://", "http://", $server_url);
1014
1015                         // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1016                         $serverret = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1017
1018                         // Quit if there is a timeout
1019                         if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1020                                 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1021                                 dba::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
1022                                 return false;
1023                         }
1024
1025                         $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1026                 }
1027
1028                 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
1029                         // Workaround for bad configured servers (known nginx problem)
1030                         if (!in_array($serverret["debug"]["http_code"], ["403", "404"])) {
1031                                 $failure = true;
1032                         }
1033                         $possible_failure = true;
1034                 }
1035
1036                 // If the server has no possible failure we reset the cached data
1037                 if (!$possible_failure) {
1038                         $version = "";
1039                         $platform = "";
1040                         $site_name = "";
1041                         $info = "";
1042                         $register_policy = -1;
1043                 }
1044
1045                 if (!$failure) {
1046                         // This will be too low, but better than no value at all.
1047                         $registered_users = dba::count('gcontact', ['server_url' => normalise_link($server_url)]);
1048                 }
1049
1050                 // Look for poco
1051                 if (!$failure) {
1052                         $serverret = Network::curl($server_url."/poco");
1053                         if ($serverret["success"]) {
1054                                 $data = json_decode($serverret["body"]);
1055                                 if (isset($data->totalResults)) {
1056                                         $registered_users = $data->totalResults;
1057                                         $poco = $server_url."/poco";
1058                                         $server = self::detectPocoData($data);
1059                                         if ($server) {
1060                                                 $platform = $server['platform'];
1061                                                 $network = $server['network'];
1062                                                 $version = '';
1063                                                 $site_name = '';
1064                                         }
1065                                 }
1066                                 // There are servers out there who don't return 404 on a failure
1067                                 // We have to be sure that don't misunderstand this
1068                                 if (is_null($data)) {
1069                                         $poco = "";
1070                                         $noscrape = "";
1071                                         $network = "";
1072                                 }
1073                         }
1074                 }
1075
1076                 if (!$failure) {
1077                         // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1078                         $serverret = Network::curl($server_url);
1079
1080                         if (!$serverret["success"] || ($serverret["body"] == "")) {
1081                                 $failure = true;
1082                         } else {
1083                                 $server = self::detectServerType($serverret["body"]);
1084                                 if ($server) {
1085                                         $platform = $server['platform'];
1086                                         $network = $server['network'];
1087                                         $version = $server['version'];
1088                                         $site_name = $server['site_name'];
1089                                 }
1090
1091                                 $lines = explode("\n", $serverret["header"]);
1092                                 if (count($lines)) {
1093                                         foreach ($lines as $line) {
1094                                                 $line = trim($line);
1095                                                 if (stristr($line, 'X-Diaspora-Version:')) {
1096                                                         $platform = "Diaspora";
1097                                                         $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1098                                                         $version = trim(str_replace("x-diaspora-version:", "", $version));
1099                                                         $network = NETWORK_DIASPORA;
1100                                                         $versionparts = explode("-", $version);
1101                                                         $version = $versionparts[0];
1102                                                 }
1103
1104                                                 if (stristr($line, 'Server: Mastodon')) {
1105                                                         $platform = "Mastodon";
1106                                                         $network = NETWORK_OSTATUS;
1107                                                 }
1108                                         }
1109                                 }
1110                         }
1111                 }
1112
1113                 if (!$failure && ($poco == "")) {
1114                         // Test for Statusnet
1115                         // Will also return data for Friendica and GNU Social - but it will be overwritten later
1116                         // The "not implemented" is a special treatment for really, really old Friendica versions
1117                         $serverret = Network::curl($server_url."/api/statusnet/version.json");
1118                         if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1119                                 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1120                                 $platform = "StatusNet";
1121                                 // Remove junk that some GNU Social servers return
1122                                 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1123                                 $version = trim($version, '"');
1124                                 $network = NETWORK_OSTATUS;
1125                         }
1126
1127                         // Test for GNU Social
1128                         $serverret = Network::curl($server_url."/api/gnusocial/version.json");
1129                         if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1130                                 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1131                                 $platform = "GNU Social";
1132                                 // Remove junk that some GNU Social servers return
1133                                 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1134                                 $version = trim($version, '"');
1135                                 $network = NETWORK_OSTATUS;
1136                         }
1137
1138                         // Test for Mastodon
1139                         $orig_version = $version;
1140                         $serverret = Network::curl($server_url."/api/v1/instance");
1141                         if ($serverret["success"] && ($serverret["body"] != '')) {
1142                                 $data = json_decode($serverret["body"]);
1143
1144                                 if (isset($data->version)) {
1145                                         $platform = "Mastodon";
1146                                         $version = $data->version;
1147                                         $site_name = $data->title;
1148                                         $info = $data->description;
1149                                         $network = NETWORK_OSTATUS;
1150                                 }
1151                                 if (!empty($data->stats->user_count)) {
1152                                         $registered_users = $data->stats->user_count;
1153                                 }
1154                         }
1155                         if (strstr($orig_version.$version, 'Pleroma')) {
1156                                 $platform = 'Pleroma';
1157                                 $version = trim(str_replace('Pleroma', '', $version));
1158                         }
1159                 }
1160
1161                 if (!$failure) {
1162                         // Test for Hubzilla and Red
1163                         $serverret = Network::curl($server_url."/siteinfo.json");
1164                         if ($serverret["success"]) {
1165                                 $data = json_decode($serverret["body"]);
1166                                 if (isset($data->url)) {
1167                                         $platform = $data->platform;
1168                                         $version = $data->version;
1169                                         $network = NETWORK_DIASPORA;
1170                                 }
1171                                 if (!empty($data->site_name)) {
1172                                         $site_name = $data->site_name;
1173                                 }
1174                                 if (!empty($data->channels_total)) {
1175                                         $registered_users = $data->channels_total;
1176                                 }
1177                                 switch ($data->register_policy) {
1178                                         case "REGISTER_OPEN":
1179                                                 $register_policy = REGISTER_OPEN;
1180                                                 break;
1181                                         case "REGISTER_APPROVE":
1182                                                 $register_policy = REGISTER_APPROVE;
1183                                                 break;
1184                                         case "REGISTER_CLOSED":
1185                                         default:
1186                                                 $register_policy = REGISTER_CLOSED;
1187                                                 break;
1188                                 }
1189                         } else {
1190                                 // Test for Hubzilla, Redmatrix or Friendica
1191                                 $serverret = Network::curl($server_url."/api/statusnet/config.json");
1192                                 if ($serverret["success"]) {
1193                                         $data = json_decode($serverret["body"]);
1194                                         if (isset($data->site->server)) {
1195                                                 if (isset($data->site->platform)) {
1196                                                         $platform = $data->site->platform->PLATFORM_NAME;
1197                                                         $version = $data->site->platform->STD_VERSION;
1198                                                         $network = NETWORK_DIASPORA;
1199                                                 }
1200                                                 if (isset($data->site->BlaBlaNet)) {
1201                                                         $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1202                                                         $version = $data->site->BlaBlaNet->STD_VERSION;
1203                                                         $network = NETWORK_DIASPORA;
1204                                                 }
1205                                                 if (isset($data->site->hubzilla)) {
1206                                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
1207                                                         $version = $data->site->hubzilla->RED_VERSION;
1208                                                         $network = NETWORK_DIASPORA;
1209                                                 }
1210                                                 if (isset($data->site->redmatrix)) {
1211                                                         if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1212                                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
1213                                                         } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1214                                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
1215                                                         }
1216
1217                                                         $version = $data->site->redmatrix->RED_VERSION;
1218                                                         $network = NETWORK_DIASPORA;
1219                                                 }
1220                                                 if (isset($data->site->friendica)) {
1221                                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1222                                                         $version = $data->site->friendica->FRIENDICA_VERSION;
1223                                                         $network = NETWORK_DFRN;
1224                                                 }
1225
1226                                                 $site_name = $data->site->name;
1227
1228                                                 $data->site->closed = self::toBoolean($data->site->closed);
1229                                                 $data->site->private = self::toBoolean($data->site->private);
1230                                                 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1231
1232                                                 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1233                                                         $register_policy = REGISTER_APPROVE;
1234                                                 } elseif (!$data->site->closed && !$data->site->private) {
1235                                                         $register_policy = REGISTER_OPEN;
1236                                                 } else {
1237                                                         $register_policy = REGISTER_CLOSED;
1238                                                 }
1239                                         }
1240                                 }
1241                         }
1242                 }
1243
1244                 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1245                 if (!$failure) {
1246                         $serverret = Network::curl($server_url."/statistics.json");
1247                         if ($serverret["success"]) {
1248                                 $data = json_decode($serverret["body"]);
1249
1250                                 if (isset($data->version)) {
1251                                         $version = $data->version;
1252                                         // Version numbers on statistics.json are presented with additional info, e.g.:
1253                                         // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1254                                         $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1255                                 }
1256
1257                                 if (!empty($data->name)) {
1258                                         $site_name = $data->name;
1259                                 }
1260
1261                                 if (!empty($data->network)) {
1262                                         $platform = $data->network;
1263                                 }
1264
1265                                 if ($platform == "Diaspora") {
1266                                         $network = NETWORK_DIASPORA;
1267                                 }
1268
1269                                 if ($data->registrations_open) {
1270                                         $register_policy = REGISTER_OPEN;
1271                                 } else {
1272                                         $register_policy = REGISTER_CLOSED;
1273                                 }
1274                         }
1275                 }
1276
1277                 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1278                 if (!$failure) {
1279                         $server = self::fetchNodeinfo($server_url);
1280                         if ($server) {
1281                                 $register_policy = $server['register_policy'];
1282
1283                                 if (isset($server['platform'])) {
1284                                         $platform = $server['platform'];
1285                                 }
1286
1287                                 if (isset($server['network'])) {
1288                                         $network = $server['network'];
1289                                 }
1290
1291                                 if (isset($server['version'])) {
1292                                         $version = $server['version'];
1293                                 }
1294
1295                                 if (isset($server['site_name'])) {
1296                                         $site_name = $server['site_name'];
1297                                 }
1298
1299                                 if (isset($server['registered-users'])) {
1300                                         $registered_users = $server['registered-users'];
1301                                 }
1302                         }
1303                 }
1304
1305                 // Check for noscrape
1306                 // Friendica servers could be detected as OStatus servers
1307                 if (!$failure && in_array($network, [NETWORK_DFRN, NETWORK_OSTATUS])) {
1308                         $serverret = Network::curl($server_url."/friendica/json");
1309
1310                         if (!$serverret["success"]) {
1311                                 $serverret = Network::curl($server_url."/friendika/json");
1312                         }
1313
1314                         if ($serverret["success"]) {
1315                                 $data = json_decode($serverret["body"]);
1316
1317                                 if (isset($data->version)) {
1318                                         $network = NETWORK_DFRN;
1319
1320                                         $noscrape = defaults($data->no_scrape_url, '');
1321                                         $version = $data->version;
1322                                         $site_name = $data->site_name;
1323                                         $info = $data->info;
1324                                         $register_policy_str = $data->register_policy;
1325                                         $platform = $data->platform;
1326
1327                                         switch ($register_policy_str) {
1328                                                 case "REGISTER_CLOSED":
1329                                                         $register_policy = REGISTER_CLOSED;
1330                                                         break;
1331                                                 case "REGISTER_APPROVE":
1332                                                         $register_policy = REGISTER_APPROVE;
1333                                                         break;
1334                                                 case "REGISTER_OPEN":
1335                                                         $register_policy = REGISTER_OPEN;
1336                                                         break;
1337                                         }
1338                                 }
1339                         }
1340                 }
1341
1342                 // Every server has got at least an admin account
1343                 if (!$failure && ($registered_users == 0)) {
1344                         $registered_users = 1;
1345                 }
1346
1347                 if ($possible_failure && !$failure) {
1348                         $failure = true;
1349                 }
1350
1351                 if ($failure) {
1352                         $last_contact = $orig_last_contact;
1353                         $last_failure = DateTimeFormat::utcNow();
1354                 } else {
1355                         $last_contact = DateTimeFormat::utcNow();
1356                         $last_failure = $orig_last_failure;
1357                 }
1358
1359                 if (($last_contact <= $last_failure) && !$failure) {
1360                         logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1361                 } elseif (($last_contact >= $last_failure) && $failure) {
1362                         logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1363                 }
1364
1365                 // Check again if the server exists
1366                 $found = dba::exists('gserver', ['nurl' => normalise_link($server_url)]);
1367
1368                 $version = strip_tags($version);
1369                 $site_name = strip_tags($site_name);
1370                 $info = strip_tags($info);
1371                 $platform = strip_tags($platform);
1372
1373                 $fields = ['url' => $server_url, 'version' => $version,
1374                                 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1375                                 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1376                                 'platform' => $platform, 'registered-users' => $registered_users,
1377                                 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1378
1379                 if ($found) {
1380                         dba::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1381                 } elseif (!$failure) {
1382                         $fields['nurl'] = normalise_link($server_url);
1383                         $fields['created'] = DateTimeFormat::utcNow();
1384                         dba::insert('gserver', $fields);
1385                 }
1386
1387                 if (!$failure && in_array($fields['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1388                         self::discoverRelay($server_url);
1389                 }
1390
1391                 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1392
1393                 return !$failure;
1394         }
1395
1396         /**
1397          * @brief Fetch relay data from a given server url
1398          *
1399          * @param string $server_url address of the server
1400          */
1401         private static function discoverRelay($server_url)
1402         {
1403                 logger("Discover relay data for server " . $server_url, LOGGER_DEBUG);
1404
1405                 $serverret = Network::curl($server_url."/.well-known/x-social-relay");
1406                 if (!$serverret["success"]) {
1407                         return;
1408                 }
1409
1410                 $data = json_decode($serverret['body']);
1411                 if (!is_object($data)) {
1412                         return;
1413                 }
1414
1415                 $gserver = dba::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => normalise_link($server_url)]);
1416                 if (!DBM::is_result($gserver)) {
1417                         return;
1418                 }
1419
1420                 if (($gserver['relay-subscribe'] != $data->subscribe) || ($gserver['relay-scope'] != $data->scope)) {
1421                         $fields = ['relay-subscribe' => $data->subscribe, 'relay-scope' => $data->scope];
1422                         dba::update('gserver', $fields, ['id' => $gserver['id']]);
1423                 }
1424
1425                 dba::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1426                 if ($data->scope == 'tags') {
1427                         // Avoid duplicates
1428                         $tags = [];
1429                         foreach ($data->tags as $tag) {
1430                                 $tag = mb_strtolower($tag);
1431                                 $tags[$tag] = $tag;
1432                         }
1433
1434                         foreach ($tags as $tag) {
1435                                 dba::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
1436                         }
1437                 }
1438
1439                 // Create or update the relay contact
1440                 $fields = [];
1441                 if (isset($data->protocols)) {
1442                         if (isset($data->protocols->diaspora)) {
1443                                 $fields['network'] = NETWORK_DIASPORA;
1444                                 if (isset($data->protocols->diaspora->receive)) {
1445                                         $fields['batch'] = $data->protocols->diaspora->receive;
1446                                 } elseif (is_string($data->protocols->diaspora)) {
1447                                         $fields['batch'] = $data->protocols->diaspora;
1448                                 }
1449                         }
1450                         if (isset($data->protocols->dfrn)) {
1451                                 $fields['network'] = NETWORK_DFRN;
1452                                 if (isset($data->protocols->dfrn->receive)) {
1453                                         $fields['batch'] = $data->protocols->dfrn->receive;
1454                                 } elseif (is_string($data->protocols->dfrn)) {
1455                                         $fields['batch'] = $data->protocols->dfrn;
1456                                 }
1457                         }
1458                 }
1459                 Diaspora::setRelayContact($server_url, $fields);
1460         }
1461
1462         /**
1463          * @brief Returns a list of all known servers
1464          * @return array List of server urls
1465          */
1466         public static function serverlist()
1467         {
1468                 $r = q(
1469                         "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1470                         WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1471                         ORDER BY `last_contact`
1472                         LIMIT 1000",
1473                         dbesc(NETWORK_DFRN),
1474                         dbesc(NETWORK_DIASPORA),
1475                         dbesc(NETWORK_OSTATUS)
1476                 );
1477
1478                 if (!DBM::is_result($r)) {
1479                         return false;
1480                 }
1481
1482                 return $r;
1483         }
1484
1485         /**
1486          * @brief Fetch server list from remote servers and adds them when they are new.
1487          *
1488          * @param string $poco URL to the POCO endpoint
1489          */
1490         private static function fetchServerlist($poco)
1491         {
1492                 $serverret = Network::curl($poco."/@server");
1493                 if (!$serverret["success"]) {
1494                         return;
1495                 }
1496                 $serverlist = json_decode($serverret['body']);
1497
1498                 if (!is_array($serverlist)) {
1499                         return;
1500                 }
1501
1502                 foreach ($serverlist as $server) {
1503                         $server_url = str_replace("/index.php", "", $server->url);
1504
1505                         $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1506                         if (!DBM::is_result($r)) {
1507                                 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1508                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1509                         }
1510                 }
1511         }
1512
1513         private static function discoverFederation()
1514         {
1515                 $last = Config::get('poco', 'last_federation_discovery');
1516
1517                 if ($last) {
1518                         $next = $last + (24 * 60 * 60);
1519                         if ($next > time()) {
1520                                 return;
1521                         }
1522                 }
1523
1524                 // Discover Friendica, Hubzilla and Diaspora servers
1525                 $serverdata = Network::fetchUrl("http://the-federation.info/pods.json");
1526
1527                 if ($serverdata) {
1528                         $servers = json_decode($serverdata);
1529
1530                         foreach ($servers->pods as $server) {
1531                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1532                         }
1533                 }
1534
1535                 // Disvover Mastodon servers
1536                 if (!Config::get('system', 'ostatus_disabled')) {
1537                         $accesstoken = Config::get('system', 'instances_social_key');
1538                         if (!empty($accesstoken)) {
1539                                 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1540                                 $header = ['Authorization: Bearer '.$accesstoken];
1541                                 $serverdata = Network::curl($api, false, $redirects, ['headers' => $header]);
1542                                 if ($serverdata['success']) {
1543                                         $servers = json_decode($serverdata['body']);
1544                                         foreach ($servers->instances as $server) {
1545                                                 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1546                                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1547                                         }
1548                                 }
1549                         }
1550                 }
1551
1552                 // Currently disabled, since the service isn't available anymore.
1553                 // It is not removed since I hope that there will be a successor.
1554                 // Discover GNU Social Servers.
1555                 //if (!Config::get('system','ostatus_disabled')) {
1556                 //      $serverdata = "http://gstools.org/api/get_open_instances/";
1557
1558                 //      $result = Network::curl($serverdata);
1559                 //      if ($result["success"]) {
1560                 //              $servers = json_decode($result["body"]);
1561
1562                 //              foreach($servers->data as $server)
1563                 //                      self::checkServer($server->instance_address);
1564                 //      }
1565                 //}
1566
1567                 Config::set('poco', 'last_federation_discovery', time());
1568         }
1569
1570         public static function discoverSingleServer($id)
1571         {
1572                 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1573                 if (!DBM::is_result($r)) {
1574                         return false;
1575                 }
1576
1577                 $server = $r[0];
1578
1579                 // Discover new servers out there (Works from Friendica version 3.5.2)
1580                 self::fetchServerlist($server["poco"]);
1581
1582                 // Fetch all users from the other server
1583                 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1584
1585                 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1586
1587                 $retdata = Network::curl($url);
1588                 if ($retdata["success"]) {
1589                         $data = json_decode($retdata["body"]);
1590
1591                         self::discoverServer($data, 2);
1592
1593                         if (Config::get('system', 'poco_discovery') > 1) {
1594                                 $timeframe = Config::get('system', 'poco_discovery_since');
1595                                 if ($timeframe == 0) {
1596                                         $timeframe = 30;
1597                                 }
1598
1599                                 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1600
1601                                 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1602                                 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1603
1604                                 $success = false;
1605
1606                                 $retdata = Network::curl($url);
1607                                 if ($retdata["success"]) {
1608                                         logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1609                                         $success = self::discoverServer(json_decode($retdata["body"]));
1610                                 }
1611
1612                                 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1613                                         logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1614                                         self::discoverServerUsers($data, $server);
1615                                 }
1616                         }
1617
1618                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1619                         dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1620
1621                         return true;
1622                 } else {
1623                         // If the server hadn't replied correctly, then force a sanity check
1624                         self::checkServer($server["url"], $server["network"], true);
1625
1626                         // If we couldn't reach the server, we will try it some time later
1627                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1628                         dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1629
1630                         return false;
1631                 }
1632         }
1633
1634         public static function discover($complete = false)
1635         {
1636                 // Update the server list
1637                 self::discoverFederation();
1638
1639                 $no_of_queries = 5;
1640
1641                 $requery_days = intval(Config::get("system", "poco_requery_days"));
1642
1643                 if ($requery_days == 0) {
1644                         $requery_days = 7;
1645                 }
1646                 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1647
1648                 $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));
1649                 if (DBM::is_result($r)) {
1650                         foreach ($r as $server) {
1651                                 if (!self::checkServer($server["url"], $server["network"])) {
1652                                         // The server is not reachable? Okay, then we will try it later
1653                                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1654                                         dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1655                                         continue;
1656                                 }
1657
1658                                 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1659                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "update_server_directory", (int)$server['id']);
1660
1661                                 if (!$complete && (--$no_of_queries == 0)) {
1662                                         break;
1663                                 }
1664                         }
1665                 }
1666         }
1667
1668         private static function discoverServerUsers($data, $server)
1669         {
1670                 if (!isset($data->entry)) {
1671                         return;
1672                 }
1673
1674                 foreach ($data->entry as $entry) {
1675                         $username = "";
1676                         if (isset($entry->urls)) {
1677                                 foreach ($entry->urls as $url) {
1678                                         if ($url->type == 'profile') {
1679                                                 $profile_url = $url->value;
1680                                                 $urlparts = parse_url($profile_url);
1681                                                 $username = end(explode("/", $urlparts["path"]));
1682                                         }
1683                                 }
1684                         }
1685                         if ($username != "") {
1686                                 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1687
1688                                 // Fetch all contacts from a given user from the other server
1689                                 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1690
1691                                 $retdata = Network::curl($url);
1692                                 if ($retdata["success"]) {
1693                                         self::discoverServer(json_decode($retdata["body"]), 3);
1694                                 }
1695                         }
1696                 }
1697         }
1698
1699         private static function discoverServer($data, $default_generation = 0)
1700         {
1701                 if (!isset($data->entry) || !count($data->entry)) {
1702                         return false;
1703                 }
1704
1705                 $success = false;
1706
1707                 foreach ($data->entry as $entry) {
1708                         $profile_url = '';
1709                         $profile_photo = '';
1710                         $connect_url = '';
1711                         $name = '';
1712                         $network = '';
1713                         $updated = NULL_DATE;
1714                         $location = '';
1715                         $about = '';
1716                         $keywords = '';
1717                         $gender = '';
1718                         $contact_type = -1;
1719                         $generation = $default_generation;
1720
1721                         $name = $entry->displayName;
1722
1723                         if (isset($entry->urls)) {
1724                                 foreach ($entry->urls as $url) {
1725                                         if ($url->type == 'profile') {
1726                                                 $profile_url = $url->value;
1727                                                 continue;
1728                                         }
1729                                         if ($url->type == 'webfinger') {
1730                                                 $connect_url = str_replace('acct:' , '', $url->value);
1731                                                 continue;
1732                                         }
1733                                 }
1734                         }
1735
1736                         if (isset($entry->photos)) {
1737                                 foreach ($entry->photos as $photo) {
1738                                         if ($photo->type == 'profile') {
1739                                                 $profile_photo = $photo->value;
1740                                                 continue;
1741                                         }
1742                                 }
1743                         }
1744
1745                         if (isset($entry->updated)) {
1746                                 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
1747                         }
1748
1749                         if (isset($entry->network)) {
1750                                 $network = $entry->network;
1751                         }
1752
1753                         if (isset($entry->currentLocation)) {
1754                                 $location = $entry->currentLocation;
1755                         }
1756
1757                         if (isset($entry->aboutMe)) {
1758                                 $about = HTML::toBBCode($entry->aboutMe);
1759                         }
1760
1761                         if (isset($entry->gender)) {
1762                                 $gender = $entry->gender;
1763                         }
1764
1765                         if (isset($entry->generation) && ($entry->generation > 0)) {
1766                                 $generation = ++$entry->generation;
1767                         }
1768
1769                         if (isset($entry->contactType) && ($entry->contactType >= 0)) {
1770                                 $contact_type = $entry->contactType;
1771                         }
1772
1773                         if (isset($entry->tags)) {
1774                                 foreach ($entry->tags as $tag) {
1775                                         $keywords = implode(", ", $tag);
1776                                 }
1777                         }
1778
1779                         if ($generation > 0) {
1780                                 $success = true;
1781
1782                                 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1783
1784                                 $gcontact = ["url" => $profile_url,
1785                                                 "name" => $name,
1786                                                 "network" => $network,
1787                                                 "photo" => $profile_photo,
1788                                                 "about" => $about,
1789                                                 "location" => $location,
1790                                                 "gender" => $gender,
1791                                                 "keywords" => $keywords,
1792                                                 "connect" => $connect_url,
1793                                                 "updated" => $updated,
1794                                                 "contact-type" => $contact_type,
1795                                                 "generation" => $generation];
1796
1797                                 try {
1798                                         $gcontact = GContact::sanitize($gcontact);
1799                                         GContact::update($gcontact);
1800                                 } catch (Exception $e) {
1801                                         logger($e->getMessage(), LOGGER_DEBUG);
1802                                 }
1803
1804                                 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1805                         }
1806                 }
1807                 return $success;
1808         }
1809
1810 }