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