]> git.mxchange.org Git - friendica.git/blob - src/Protocol/PortableContact.php
4eaf5bbb6c74c76e4eda74763a6478f42f16831f
[friendica.git] / src / Protocol / PortableContact.php
1 <?php
2 /**
3  * @file src/Protocol/PortableContact.php
4  *
5  * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6  * @todo Fetch profile data from profile page for Redmatrix users
7  * @todo Detect if it is a forum
8  */
9
10 namespace Friendica\Protocol;
11
12 use Friendica\Content\Text\HTML;
13 use Friendica\Core\Config;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
16 use Friendica\Model\GContact;
17 use Friendica\Model\Profile;
18 use Friendica\Network\Probe;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Protocol\Diaspora;
22 use dba;
23 use DOMDocument;
24 use DOMXPath;
25 use Exception;
26
27 require_once 'include/dba.php';
28
29 class PortableContact
30 {
31         /**
32          * @brief Fetch POCO data
33          *
34          * @param integer $cid  Contact ID
35          * @param integer $uid  User ID
36          * @param integer $zcid Global Contact ID
37          * @param integer $url  POCO address that should be polled
38          *
39          * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
40          * and add the entries to the gcontact (Global Contact) table, or update existing entries
41          * if anything (name or photo) has changed.
42          * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
43          *
44          * Once the global contact is stored add (if necessary) the contact linkage which associates
45          * the given uid, cid to the global contact entry. There can be many uid/cid combinations
46          * pointing to the same global contact id.
47          *
48          */
49         public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
50         {
51                 // Call the function "load" via the worker
52                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
53         }
54
55         /**
56          * @brief Fetch POCO data from the worker
57          *
58          * @param integer $cid  Contact ID
59          * @param integer $uid  User ID
60          * @param integer $zcid Global Contact ID
61          * @param integer $url  POCO address that should be polled
62          *
63          */
64         public static function load($cid, $uid, $zcid, $url)
65         {
66                 $a = get_app();
67
68                 if ($cid) {
69                         if (!$url || !$uid) {
70                                 $contact = dba::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
71                                 if (DBM::is_result($contact)) {
72                                         $url = $contact['poco'];
73                                         $uid = $contact['uid'];
74                                 }
75                         }
76                         if (!$uid) {
77                                 return;
78                         }
79                 }
80
81                 if (!$url) {
82                         return;
83                 }
84
85                 $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation') ;
86
87                 logger('load: ' . $url, LOGGER_DEBUG);
88
89                 $s = Network::fetchUrl($url);
90
91                 logger('load: returns ' . $s, LOGGER_DATA);
92
93                 logger('load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
94
95                 if (($a->get_curl_code() > 299) || (! $s)) {
96                         return;
97                 }
98
99                 $j = json_decode($s);
100
101                 logger('load: json: ' . print_r($j, true), LOGGER_DATA);
102
103                 if (! isset($j->entry)) {
104                         return;
105                 }
106
107                 $total = 0;
108                 foreach ($j->entry as $entry) {
109                         $total ++;
110                         $profile_url = '';
111                         $profile_photo = '';
112                         $connect_url = '';
113                         $name = '';
114                         $network = '';
115                         $updated = NULL_DATE;
116                         $location = '';
117                         $about = '';
118                         $keywords = '';
119                         $gender = '';
120                         $contact_type = -1;
121                         $generation = 0;
122
123                         $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 = constant($data->register_policy);
1325                                         $platform = $data->platform;
1326                                 }
1327                         }
1328                 }
1329
1330                 // Every server has got at least an admin account
1331                 if (!$failure && ($registered_users == 0)) {
1332                         $registered_users = 1;
1333                 }
1334
1335                 if ($possible_failure && !$failure) {
1336                         $failure = true;
1337                 }
1338
1339                 if ($failure) {
1340                         $last_contact = $orig_last_contact;
1341                         $last_failure = DateTimeFormat::utcNow();
1342                 } else {
1343                         $last_contact = DateTimeFormat::utcNow();
1344                         $last_failure = $orig_last_failure;
1345                 }
1346
1347                 if (($last_contact <= $last_failure) && !$failure) {
1348                         logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1349                 } elseif (($last_contact >= $last_failure) && $failure) {
1350                         logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1351                 }
1352
1353                 // Check again if the server exists
1354                 $found = dba::exists('gserver', ['nurl' => normalise_link($server_url)]);
1355
1356                 $version = strip_tags($version);
1357                 $site_name = strip_tags($site_name);
1358                 $info = strip_tags($info);
1359                 $platform = strip_tags($platform);
1360
1361                 $fields = ['url' => $server_url, 'version' => $version,
1362                                 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1363                                 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1364                                 'platform' => $platform, 'registered-users' => $registered_users,
1365                                 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1366
1367                 if ($found) {
1368                         dba::update('gserver', $fields, ['nurl' => normalise_link($server_url)]);
1369                 } elseif (!$failure) {
1370                         $fields['nurl'] = normalise_link($server_url);
1371                         $fields['created'] = DateTimeFormat::utcNow();
1372                         dba::insert('gserver', $fields);
1373                 }
1374
1375                 if (!$failure && in_array($fields['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1376                         self::discoverRelay($server_url);
1377                 }
1378
1379                 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1380
1381                 return !$failure;
1382         }
1383
1384         /**
1385          * @brief Fetch relay data from a given server url
1386          *
1387          * @param string $server_url address of the server
1388          */
1389         private static function discoverRelay($server_url)
1390         {
1391                 logger("Discover relay data for server " . $server_url, LOGGER_DEBUG);
1392
1393                 $serverret = Network::curl($server_url."/.well-known/x-social-relay");
1394                 if (!$serverret["success"]) {
1395                         return;
1396                 }
1397
1398                 $data = json_decode($serverret['body']);
1399                 if (!is_object($data)) {
1400                         return;
1401                 }
1402
1403                 $gserver = dba::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => normalise_link($server_url)]);
1404                 if (!DBM::is_result($gserver)) {
1405                         return;
1406                 }
1407
1408                 if (($gserver['relay-subscribe'] != $data->subscribe) || ($gserver['relay-scope'] != $data->scope)) {
1409                         $fields = ['relay-subscribe' => $data->subscribe, 'relay-scope' => $data->scope];
1410                         dba::update('gserver', $fields, ['id' => $gserver['id']]);
1411                 }
1412
1413                 dba::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1414                 if ($data->scope == 'tags') {
1415                         // Avoid duplicates
1416                         $tags = [];
1417                         foreach ($data->tags as $tag) {
1418                                 $tag = mb_strtolower($tag);
1419                                 $tags[$tag] = $tag;
1420                         }
1421
1422                         foreach ($tags as $tag) {
1423                                 dba::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
1424                         }
1425                 }
1426
1427                 // Create or update the relay contact
1428                 $fields = [];
1429                 if (isset($data->protocols)) {
1430                         if (isset($data->protocols->diaspora)) {
1431                                 $fields['network'] = NETWORK_DIASPORA;
1432                                 if (isset($data->protocols->diaspora->receive)) {
1433                                         $fields['batch'] = $data->protocols->diaspora->receive;
1434                                 } elseif (is_string($data->protocols->diaspora)) {
1435                                         $fields['batch'] = $data->protocols->diaspora;
1436                                 }
1437                         }
1438                         if (isset($data->protocols->dfrn)) {
1439                                 $fields['network'] = NETWORK_DFRN;
1440                                 if (isset($data->protocols->dfrn->receive)) {
1441                                         $fields['batch'] = $data->protocols->dfrn->receive;
1442                                 } elseif (is_string($data->protocols->dfrn)) {
1443                                         $fields['batch'] = $data->protocols->dfrn;
1444                                 }
1445                         }
1446                 }
1447                 Diaspora::setRelayContact($server_url, $fields);
1448         }
1449
1450         /**
1451          * @brief Returns a list of all known servers
1452          * @return array List of server urls
1453          */
1454         public static function serverlist()
1455         {
1456                 $r = q(
1457                         "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1458                         WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1459                         ORDER BY `last_contact`
1460                         LIMIT 1000",
1461                         dbesc(NETWORK_DFRN),
1462                         dbesc(NETWORK_DIASPORA),
1463                         dbesc(NETWORK_OSTATUS)
1464                 );
1465
1466                 if (!DBM::is_result($r)) {
1467                         return false;
1468                 }
1469
1470                 return $r;
1471         }
1472
1473         /**
1474          * @brief Fetch server list from remote servers and adds them when they are new.
1475          *
1476          * @param string $poco URL to the POCO endpoint
1477          */
1478         private static function fetchServerlist($poco)
1479         {
1480                 $serverret = Network::curl($poco."/@server");
1481                 if (!$serverret["success"]) {
1482                         return;
1483                 }
1484                 $serverlist = json_decode($serverret['body']);
1485
1486                 if (!is_array($serverlist)) {
1487                         return;
1488                 }
1489
1490                 foreach ($serverlist as $server) {
1491                         $server_url = str_replace("/index.php", "", $server->url);
1492
1493                         $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1494                         if (!DBM::is_result($r)) {
1495                                 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1496                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1497                         }
1498                 }
1499         }
1500
1501         private static function discoverFederation()
1502         {
1503                 $last = Config::get('poco', 'last_federation_discovery');
1504
1505                 if ($last) {
1506                         $next = $last + (24 * 60 * 60);
1507                         if ($next > time()) {
1508                                 return;
1509                         }
1510                 }
1511
1512                 // Discover Friendica, Hubzilla and Diaspora servers
1513                 $serverdata = Network::fetchUrl("http://the-federation.info/pods.json");
1514
1515                 if ($serverdata) {
1516                         $servers = json_decode($serverdata);
1517
1518                         if (is_array($servers->pods)) {
1519                                 foreach ($servers->pods as $server) {
1520                                         Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1521                                 }
1522                         }
1523                 }
1524
1525                 // Disvover Mastodon servers
1526                 if (!Config::get('system', 'ostatus_disabled')) {
1527                         $accesstoken = Config::get('system', 'instances_social_key');
1528                         if (!empty($accesstoken)) {
1529                                 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1530                                 $header = ['Authorization: Bearer '.$accesstoken];
1531                                 $serverdata = Network::curl($api, false, $redirects, ['headers' => $header]);
1532                                 if ($serverdata['success']) {
1533                                         $servers = json_decode($serverdata['body']);
1534                                         foreach ($servers->instances as $server) {
1535                                                 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1536                                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1537                                         }
1538                                 }
1539                         }
1540                 }
1541
1542                 // Currently disabled, since the service isn't available anymore.
1543                 // It is not removed since I hope that there will be a successor.
1544                 // Discover GNU Social Servers.
1545                 //if (!Config::get('system','ostatus_disabled')) {
1546                 //      $serverdata = "http://gstools.org/api/get_open_instances/";
1547
1548                 //      $result = Network::curl($serverdata);
1549                 //      if ($result["success"]) {
1550                 //              $servers = json_decode($result["body"]);
1551
1552                 //              foreach($servers->data as $server)
1553                 //                      self::checkServer($server->instance_address);
1554                 //      }
1555                 //}
1556
1557                 Config::set('poco', 'last_federation_discovery', time());
1558         }
1559
1560         public static function discoverSingleServer($id)
1561         {
1562                 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1563                 if (!DBM::is_result($r)) {
1564                         return false;
1565                 }
1566
1567                 $server = $r[0];
1568
1569                 // Discover new servers out there (Works from Friendica version 3.5.2)
1570                 self::fetchServerlist($server["poco"]);
1571
1572                 // Fetch all users from the other server
1573                 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1574
1575                 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1576
1577                 $retdata = Network::curl($url);
1578                 if ($retdata["success"]) {
1579                         $data = json_decode($retdata["body"]);
1580
1581                         self::discoverServer($data, 2);
1582
1583                         if (Config::get('system', 'poco_discovery') > 1) {
1584                                 $timeframe = Config::get('system', 'poco_discovery_since');
1585                                 if ($timeframe == 0) {
1586                                         $timeframe = 30;
1587                                 }
1588
1589                                 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1590
1591                                 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1592                                 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1593
1594                                 $success = false;
1595
1596                                 $retdata = Network::curl($url);
1597                                 if ($retdata["success"]) {
1598                                         logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1599                                         $success = self::discoverServer(json_decode($retdata["body"]));
1600                                 }
1601
1602                                 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1603                                         logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1604                                         self::discoverServerUsers($data, $server);
1605                                 }
1606                         }
1607
1608                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1609                         dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1610
1611                         return true;
1612                 } else {
1613                         // If the server hadn't replied correctly, then force a sanity check
1614                         self::checkServer($server["url"], $server["network"], true);
1615
1616                         // If we couldn't reach the server, we will try it some time later
1617                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1618                         dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1619
1620                         return false;
1621                 }
1622         }
1623
1624         public static function discover($complete = false)
1625         {
1626                 // Update the server list
1627                 self::discoverFederation();
1628
1629                 $no_of_queries = 5;
1630
1631                 $requery_days = intval(Config::get("system", "poco_requery_days"));
1632
1633                 if ($requery_days == 0) {
1634                         $requery_days = 7;
1635                 }
1636                 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1637
1638                 $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));
1639                 if (DBM::is_result($r)) {
1640                         foreach ($r as $server) {
1641                                 if (!self::checkServer($server["url"], $server["network"])) {
1642                                         // The server is not reachable? Okay, then we will try it later
1643                                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1644                                         dba::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1645                                         continue;
1646                                 }
1647
1648                                 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1649                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "update_server_directory", (int)$server['id']);
1650
1651                                 if (!$complete && (--$no_of_queries == 0)) {
1652                                         break;
1653                                 }
1654                         }
1655                 }
1656         }
1657
1658         private static function discoverServerUsers($data, $server)
1659         {
1660                 if (!isset($data->entry)) {
1661                         return;
1662                 }
1663
1664                 foreach ($data->entry as $entry) {
1665                         $username = "";
1666                         if (isset($entry->urls)) {
1667                                 foreach ($entry->urls as $url) {
1668                                         if ($url->type == 'profile') {
1669                                                 $profile_url = $url->value;
1670                                                 $urlparts = parse_url($profile_url);
1671                                                 $username = end(explode("/", $urlparts["path"]));
1672                                         }
1673                                 }
1674                         }
1675                         if ($username != "") {
1676                                 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1677
1678                                 // Fetch all contacts from a given user from the other server
1679                                 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1680
1681                                 $retdata = Network::curl($url);
1682                                 if ($retdata["success"]) {
1683                                         self::discoverServer(json_decode($retdata["body"]), 3);
1684                                 }
1685                         }
1686                 }
1687         }
1688
1689         private static function discoverServer($data, $default_generation = 0)
1690         {
1691                 if (!isset($data->entry) || !count($data->entry)) {
1692                         return false;
1693                 }
1694
1695                 $success = false;
1696
1697                 foreach ($data->entry as $entry) {
1698                         $profile_url = '';
1699                         $profile_photo = '';
1700                         $connect_url = '';
1701                         $name = '';
1702                         $network = '';
1703                         $updated = NULL_DATE;
1704                         $location = '';
1705                         $about = '';
1706                         $keywords = '';
1707                         $gender = '';
1708                         $contact_type = -1;
1709                         $generation = $default_generation;
1710
1711                         $name = $entry->displayName;
1712
1713                         if (isset($entry->urls)) {
1714                                 foreach ($entry->urls as $url) {
1715                                         if ($url->type == 'profile') {
1716                                                 $profile_url = $url->value;
1717                                                 continue;
1718                                         }
1719                                         if ($url->type == 'webfinger') {
1720                                                 $connect_url = str_replace('acct:' , '', $url->value);
1721                                                 continue;
1722                                         }
1723                                 }
1724                         }
1725
1726                         if (isset($entry->photos)) {
1727                                 foreach ($entry->photos as $photo) {
1728                                         if ($photo->type == 'profile') {
1729                                                 $profile_photo = $photo->value;
1730                                                 continue;
1731                                         }
1732                                 }
1733                         }
1734
1735                         if (isset($entry->updated)) {
1736                                 $updated = date(DateTimeFormat::MYSQL, strtotime($entry->updated));
1737                         }
1738
1739                         if (isset($entry->network)) {
1740                                 $network = $entry->network;
1741                         }
1742
1743                         if (isset($entry->currentLocation)) {
1744                                 $location = $entry->currentLocation;
1745                         }
1746
1747                         if (isset($entry->aboutMe)) {
1748                                 $about = HTML::toBBCode($entry->aboutMe);
1749                         }
1750
1751                         if (isset($entry->gender)) {
1752                                 $gender = $entry->gender;
1753                         }
1754
1755                         if (isset($entry->generation) && ($entry->generation > 0)) {
1756                                 $generation = ++$entry->generation;
1757                         }
1758
1759                         if (isset($entry->contactType) && ($entry->contactType >= 0)) {
1760                                 $contact_type = $entry->contactType;
1761                         }
1762
1763                         if (isset($entry->tags)) {
1764                                 foreach ($entry->tags as $tag) {
1765                                         $keywords = implode(", ", $tag);
1766                                 }
1767                         }
1768
1769                         if ($generation > 0) {
1770                                 $success = true;
1771
1772                                 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1773
1774                                 $gcontact = ["url" => $profile_url,
1775                                                 "name" => $name,
1776                                                 "network" => $network,
1777                                                 "photo" => $profile_photo,
1778                                                 "about" => $about,
1779                                                 "location" => $location,
1780                                                 "gender" => $gender,
1781                                                 "keywords" => $keywords,
1782                                                 "connect" => $connect_url,
1783                                                 "updated" => $updated,
1784                                                 "contact-type" => $contact_type,
1785                                                 "generation" => $generation];
1786
1787                                 try {
1788                                         $gcontact = GContact::sanitize($gcontact);
1789                                         GContact::update($gcontact);
1790                                 } catch (Exception $e) {
1791                                         logger($e->getMessage(), LOGGER_DEBUG);
1792                                 }
1793
1794                                 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1795                         }
1796                 }
1797                 return $success;
1798         }
1799
1800 }