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