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