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