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