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