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