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