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