]> git.mxchange.org Git - friendica.git/blob - src/Protocol/PortableContact.php
Revert "Move Objects to Model"
[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\GlobalContact;
16 use Friendica\Network\Probe;
17 use Friendica\Object\Photo;
18 use Friendica\Object\Profile;
19 use dba;
20 use DOMDocument;
21 use DomXPath;
22 use Exception;
23
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 = GlobalContact::sanitize($gcontact);
197                                 $gcid = GlobalContact::update($gcontact);
198
199                                 GlobalContact::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                                                 GlobalContact::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                         GlobalContact::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 = GlobalContact::sanitize($gcontact);
472                                 GlobalContact::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                 GlobalContact::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                 $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
820                 return $server;
821         }
822
823         public static function checkServer($server_url, $network = "", $force = false)
824         {
825                 // Unify the server address
826                 $server_url = trim($server_url, "/");
827                 $server_url = str_replace("/index.php", "", $server_url);
828
829                 if ($server_url == "") {
830                         return false;
831                 }
832
833                 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
834                 if (DBM::is_result($servers)) {
835                         if ($servers[0]["created"] <= NULL_DATE) {
836                                 q(
837                                         "UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
838                                         dbesc(datetime_convert()),
839                                         dbesc(normalise_link($server_url))
840                                 );
841                         }
842                         $poco = $servers[0]["poco"];
843                         $noscrape = $servers[0]["noscrape"];
844
845                         if ($network == "") {
846                                 $network = $servers[0]["network"];
847                         }
848
849                         $last_contact = $servers[0]["last_contact"];
850                         $last_failure = $servers[0]["last_failure"];
851                         $version = $servers[0]["version"];
852                         $platform = $servers[0]["platform"];
853                         $site_name = $servers[0]["site_name"];
854                         $info = $servers[0]["info"];
855                         $register_policy = $servers[0]["register_policy"];
856
857                         if (!$force && !self::updateNeeded($servers[0]["created"], "", $last_failure, $last_contact)) {
858                                 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
859                                 return ($last_contact >= $last_failure);
860                         }
861                 } else {
862                         $poco = "";
863                         $noscrape = "";
864                         $version = "";
865                         $platform = "";
866                         $site_name = "";
867                         $info = "";
868                         $register_policy = -1;
869
870                         $last_contact = NULL_DATE;
871                         $last_failure = NULL_DATE;
872                 }
873                 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
874
875                 $failure = false;
876                 $possible_failure = false;
877                 $orig_last_failure = $last_failure;
878                 $orig_last_contact = $last_contact;
879
880                 // Check if the page is accessible via SSL.
881                 $orig_server_url = $server_url;
882                 $server_url = str_replace("http://", "https://", $server_url);
883
884                 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
885                 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
886
887                 // Quit if there is a timeout.
888                 // But we want to make sure to only quit if we are mostly sure that this server url fits.
889                 if (DBM::is_result($servers) && ($orig_server_url == $server_url) &&
890                         ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
891                         logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
892                         dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
893                         return false;
894                 }
895
896                 // Maybe the page is unencrypted only?
897                 $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
898                 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
899                         $server_url = str_replace("https://", "http://", $server_url);
900
901                         // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
902                         $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
903
904                         // Quit if there is a timeout
905                         if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
906                                 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
907                                 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
908                                 return false;
909                         }
910
911                         $xmlobj = @simplexml_load_string($serverret["body"], 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
912                 }
913
914                 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
915                         // Workaround for bad configured servers (known nginx problem)
916                         if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
917                                 $failure = true;
918                         }
919                         $possible_failure = true;
920                 }
921
922                 // If the server has no possible failure we reset the cached data
923                 if (!$possible_failure) {
924                         $version = "";
925                         $platform = "";
926                         $site_name = "";
927                         $info = "";
928                         $register_policy = -1;
929                 }
930
931                 // Look for poco
932                 if (!$failure) {
933                         $serverret = z_fetch_url($server_url."/poco");
934                         if ($serverret["success"]) {
935                                 $data = json_decode($serverret["body"]);
936                                 if (isset($data->totalResults)) {
937                                         $poco = $server_url."/poco";
938                                         $server = self::detectPocoData($data);
939                                         if ($server) {
940                                                 $platform = $server['platform'];
941                                                 $network = $server['network'];
942                                                 $version = '';
943                                                 $site_name = '';
944                                         }
945                                 }
946                         }
947                 }
948
949                 if (!$failure) {
950                         // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
951                         $serverret = z_fetch_url($server_url);
952
953                         if (!$serverret["success"] || ($serverret["body"] == "")) {
954                                 $failure = true;
955                         } else {
956                                 $server = self::detectServerType($serverret["body"]);
957                                 if ($server) {
958                                         $platform = $server['platform'];
959                                         $network = $server['network'];
960                                         $version = $server['version'];
961                                         $site_name = $server['site_name'];
962                                 }
963
964                                 $lines = explode("\n", $serverret["header"]);
965                                 if (count($lines)) {
966                                         foreach ($lines as $line) {
967                                                 $line = trim($line);
968                                                 if (stristr($line, 'X-Diaspora-Version:')) {
969                                                         $platform = "Diaspora";
970                                                         $version = trim(str_replace("X-Diaspora-Version:", "", $line));
971                                                         $version = trim(str_replace("x-diaspora-version:", "", $version));
972                                                         $network = NETWORK_DIASPORA;
973                                                         $versionparts = explode("-", $version);
974                                                         $version = $versionparts[0];
975                                                 }
976
977                                                 if (stristr($line, 'Server: Mastodon')) {
978                                                         $platform = "Mastodon";
979                                                         $network = NETWORK_OSTATUS;
980                                                 }
981                                         }
982                                 }
983                         }
984                 }
985
986                 if (!$failure && ($poco == "")) {
987                         // Test for Statusnet
988                         // Will also return data for Friendica and GNU Social - but it will be overwritten later
989                         // The "not implemented" is a special treatment for really, really old Friendica versions
990                         $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
991                         if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
992                                 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
993                                 $platform = "StatusNet";
994                                 // Remove junk that some GNU Social servers return
995                                 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
996                                 $version = trim($version, '"');
997                                 $network = NETWORK_OSTATUS;
998                         }
999
1000                         // Test for GNU Social
1001                         $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1002                         if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1003                                 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1004                                 $platform = "GNU Social";
1005                                 // Remove junk that some GNU Social servers return
1006                                 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1007                                 $version = trim($version, '"');
1008                                 $network = NETWORK_OSTATUS;
1009                         }
1010
1011                         // Test for Mastodon
1012                         $orig_version = $version;
1013                         $serverret = z_fetch_url($server_url."/api/v1/instance");
1014                         if ($serverret["success"] && ($serverret["body"] != '')) {
1015                                 $data = json_decode($serverret["body"]);
1016                                 if (isset($data->version)) {
1017                                         $platform = "Mastodon";
1018                                         $version = $data->version;
1019                                         $site_name = $data->title;
1020                                         $info = $data->description;
1021                                         $network = NETWORK_OSTATUS;
1022                                 }
1023                         }
1024                         if (strstr($orig_version.$version, 'Pleroma')) {
1025                                 $platform = 'Pleroma';
1026                                 $version = trim(str_replace('Pleroma', '', $version));
1027                         }
1028                 }
1029
1030                 if (!$failure) {
1031                         // Test for Hubzilla and Red
1032                         $serverret = z_fetch_url($server_url."/siteinfo.json");
1033                         if ($serverret["success"]) {
1034                                 $data = json_decode($serverret["body"]);
1035                                 if (isset($data->url)) {
1036                                         $platform = $data->platform;
1037                                         $version = $data->version;
1038                                         $network = NETWORK_DIASPORA;
1039                                 }
1040                                 if (!empty($data->site_name)) {
1041                                         $site_name = $data->site_name;
1042                                 }
1043                                 switch ($data->register_policy) {
1044                                         case "REGISTER_OPEN":
1045                                                 $register_policy = REGISTER_OPEN;
1046                                                 break;
1047                                         case "REGISTER_APPROVE":
1048                                                 $register_policy = REGISTER_APPROVE;
1049                                                 break;
1050                                         case "REGISTER_CLOSED":
1051                                         default:
1052                                                 $register_policy = REGISTER_CLOSED;
1053                                                 break;
1054                                 }
1055                         } else {
1056                                 // Test for Hubzilla, Redmatrix or Friendica
1057                                 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1058                                 if ($serverret["success"]) {
1059                                         $data = json_decode($serverret["body"]);
1060                                         if (isset($data->site->server)) {
1061                                                 if (isset($data->site->platform)) {
1062                                                         $platform = $data->site->platform->PLATFORM_NAME;
1063                                                         $version = $data->site->platform->STD_VERSION;
1064                                                         $network = NETWORK_DIASPORA;
1065                                                 }
1066                                                 if (isset($data->site->BlaBlaNet)) {
1067                                                         $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1068                                                         $version = $data->site->BlaBlaNet->STD_VERSION;
1069                                                         $network = NETWORK_DIASPORA;
1070                                                 }
1071                                                 if (isset($data->site->hubzilla)) {
1072                                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
1073                                                         $version = $data->site->hubzilla->RED_VERSION;
1074                                                         $network = NETWORK_DIASPORA;
1075                                                 }
1076                                                 if (isset($data->site->redmatrix)) {
1077                                                         if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1078                                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
1079                                                         } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1080                                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
1081                                                         }
1082
1083                                                         $version = $data->site->redmatrix->RED_VERSION;
1084                                                         $network = NETWORK_DIASPORA;
1085                                                 }
1086                                                 if (isset($data->site->friendica)) {
1087                                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1088                                                         $version = $data->site->friendica->FRIENDICA_VERSION;
1089                                                         $network = NETWORK_DFRN;
1090                                                 }
1091
1092                                                 $site_name = $data->site->name;
1093
1094                                                 $data->site->closed = self::toBoolean($data->site->closed);
1095                                                 $data->site->private = self::toBoolean($data->site->private);
1096                                                 $data->site->inviteonly = self::toBoolean($data->site->inviteonly);
1097
1098                                                 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1099                                                         $register_policy = REGISTER_APPROVE;
1100                                                 } elseif (!$data->site->closed && !$data->site->private) {
1101                                                         $register_policy = REGISTER_OPEN;
1102                                                 } else {
1103                                                         $register_policy = REGISTER_CLOSED;
1104                                                 }
1105                                         }
1106                                 }
1107                         }
1108                 }
1109
1110                 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1111                 if (!$failure) {
1112                         $serverret = z_fetch_url($server_url."/statistics.json");
1113                         if ($serverret["success"]) {
1114                                 $data = json_decode($serverret["body"]);
1115                                 if (isset($data->version)) {
1116                                         $version = $data->version;
1117                                         // Version numbers on statistics.json are presented with additional info, e.g.:
1118                                         // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1119                                         $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1120                                 }
1121
1122                                 if (!empty($data->name)) {
1123                                         $site_name = $data->name;
1124                                 }
1125
1126                                 if (!empty($data->network)) {
1127                                         $platform = $data->network;
1128                                 }
1129
1130                                 if ($platform == "Diaspora") {
1131                                         $network = NETWORK_DIASPORA;
1132                                 }
1133
1134                                 if ($data->registrations_open) {
1135                                         $register_policy = REGISTER_OPEN;
1136                                 } else {
1137                                         $register_policy = REGISTER_CLOSED;
1138                                 }
1139                         }
1140                 }
1141
1142                 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1143                 if (!$failure) {
1144                         $server = self::fetchNodeinfo($server_url);
1145                         if ($server) {
1146                                 $register_policy = $server['register_policy'];
1147
1148                                 if (isset($server['platform'])) {
1149                                         $platform = $server['platform'];
1150                                 }
1151
1152                                 if (isset($server['network'])) {
1153                                         $network = $server['network'];
1154                                 }
1155
1156                                 if (isset($server['version'])) {
1157                                         $version = $server['version'];
1158                                 }
1159
1160                                 if (isset($server['site_name'])) {
1161                                         $site_name = $server['site_name'];
1162                                 }
1163                         }
1164                 }
1165
1166                 // Check for noscrape
1167                 // Friendica servers could be detected as OStatus servers
1168                 if (!$failure && in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1169                         $serverret = z_fetch_url($server_url."/friendica/json");
1170
1171                         if (!$serverret["success"]) {
1172                                 $serverret = z_fetch_url($server_url."/friendika/json");
1173                         }
1174
1175                         if ($serverret["success"]) {
1176                                 $data = json_decode($serverret["body"]);
1177
1178                                 if (isset($data->version)) {
1179                                         $network = NETWORK_DFRN;
1180
1181                                         $noscrape = $data->no_scrape_url;
1182                                         $version = $data->version;
1183                                         $site_name = $data->site_name;
1184                                         $info = $data->info;
1185                                         $register_policy_str = $data->register_policy;
1186                                         $platform = $data->platform;
1187
1188                                         switch ($register_policy_str) {
1189                                                 case "REGISTER_CLOSED":
1190                                                         $register_policy = REGISTER_CLOSED;
1191                                                         break;
1192                                                 case "REGISTER_APPROVE":
1193                                                         $register_policy = REGISTER_APPROVE;
1194                                                         break;
1195                                                 case "REGISTER_OPEN":
1196                                                         $register_policy = REGISTER_OPEN;
1197                                                         break;
1198                                         }
1199                                 }
1200                         }
1201                 }
1202
1203                 if ($possible_failure && !$failure) {
1204                         $failure = true;
1205                 }
1206
1207                 if ($failure) {
1208                         $last_contact = $orig_last_contact;
1209                         $last_failure = datetime_convert();
1210                 } else {
1211                         $last_contact = datetime_convert();
1212                         $last_failure = $orig_last_failure;
1213                 }
1214
1215                 if (($last_contact <= $last_failure) && !$failure) {
1216                         logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1217                 } elseif (($last_contact >= $last_failure) && $failure) {
1218                         logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1219                 }
1220
1221                 // Check again if the server exists
1222                 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1223
1224                 $version = strip_tags($version);
1225                 $site_name = strip_tags($site_name);
1226                 $info = strip_tags($info);
1227                 $platform = strip_tags($platform);
1228
1229                 if ($servers) {
1230                         q(
1231                                 "UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1232                                 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1233                                 dbesc($server_url),
1234                                 dbesc($version),
1235                                 dbesc($site_name),
1236                                 dbesc($info),
1237                                 intval($register_policy),
1238                                 dbesc($poco),
1239                                 dbesc($noscrape),
1240                                 dbesc($network),
1241                                 dbesc($platform),
1242                                 dbesc($last_contact),
1243                                 dbesc($last_failure),
1244                                 dbesc(normalise_link($server_url))
1245                         );
1246                 } elseif (!$failure) {
1247                         q(
1248                                 "INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1249                                                 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1250                                 dbesc($server_url),
1251                                 dbesc(normalise_link($server_url)),
1252                                 dbesc($version),
1253                                 dbesc($site_name),
1254                                 dbesc($info),
1255                                 intval($register_policy),
1256                                 dbesc($poco),
1257                                 dbesc($noscrape),
1258                                 dbesc($network),
1259                                 dbesc($platform),
1260                                 dbesc(datetime_convert()),
1261                                 dbesc($last_contact),
1262                                 dbesc($last_failure),
1263                                 dbesc(datetime_convert())
1264                         );
1265                 }
1266                 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1267
1268                 return !$failure;
1269         }
1270
1271         /**
1272          * @brief Returns a list of all known servers
1273          * @return array List of server urls
1274          */
1275         public static function serverlist()
1276         {
1277                 $r = q(
1278                         "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1279                         WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1280                         ORDER BY `last_contact`
1281                         LIMIT 1000",
1282                         dbesc(NETWORK_DFRN),
1283                         dbesc(NETWORK_DIASPORA),
1284                         dbesc(NETWORK_OSTATUS)
1285                 );
1286
1287                 if (!DBM::is_result($r)) {
1288                         return false;
1289                 }
1290
1291                 return $r;
1292         }
1293
1294         /**
1295          * @brief Fetch server list from remote servers and adds them when they are new.
1296          *
1297          * @param string $poco URL to the POCO endpoint
1298          */
1299         public static function fetchServerlist($poco)
1300         {
1301                 $serverret = z_fetch_url($poco."/@server");
1302                 if (!$serverret["success"]) {
1303                         return;
1304                 }
1305                 $serverlist = json_decode($serverret['body']);
1306
1307                 if (!is_array($serverlist)) {
1308                         return;
1309                 }
1310
1311                 foreach ($serverlist as $server) {
1312                         $server_url = str_replace("/index.php", "", $server->url);
1313
1314                         $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1315                         if (!DBM::is_result($r)) {
1316                                 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1317                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1318                         }
1319                 }
1320         }
1321
1322         public static function discoverFederation()
1323         {
1324                 $last = Config::get('poco', 'last_federation_discovery');
1325
1326                 if ($last) {
1327                         $next = $last + (24 * 60 * 60);
1328                         if ($next > time()) {
1329                                 return;
1330                         }
1331                 }
1332
1333                 // Discover Friendica, Hubzilla and Diaspora servers
1334                 $serverdata = fetch_url("http://the-federation.info/pods.json");
1335
1336                 if ($serverdata) {
1337                         $servers = json_decode($serverdata);
1338
1339                         foreach ($servers->pods as $server) {
1340                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://".$server->host);
1341                         }
1342                 }
1343
1344                 // Disvover Mastodon servers
1345                 if (!Config::get('system', 'ostatus_disabled')) {
1346                         $accesstoken = Config::get('system', 'instances_social_key');
1347                         if (!empty($accesstoken)) {
1348                                 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1349                                 $header = array('Authorization: Bearer '.$accesstoken);
1350                                 $serverdata = z_fetch_url($api, false, $redirects, ['headers' => $header]);
1351                                 if ($serverdata['success']) {
1352                                         $servers = json_decode($serverdata['body']);
1353                                         foreach ($servers->instances as $server) {
1354                                                 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1355                                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1356                                         }
1357                                 }
1358                         }
1359                 }
1360
1361                 // Currently disabled, since the service isn't available anymore.
1362                 // It is not removed since I hope that there will be a successor.
1363                 // Discover GNU Social Servers.
1364                 //if (!Config::get('system','ostatus_disabled')) {
1365                 //      $serverdata = "http://gstools.org/api/get_open_instances/";
1366
1367                 //      $result = z_fetch_url($serverdata);
1368                 //      if ($result["success"]) {
1369                 //              $servers = json_decode($result["body"]);
1370
1371                 //              foreach($servers->data as $server)
1372                 //                      self::checkServer($server->instance_address);
1373                 //      }
1374                 //}
1375
1376                 Config::set('poco', 'last_federation_discovery', time());
1377         }
1378
1379         public static function discoverSingleServer($id)
1380         {
1381                 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1382                 if (!DBM::is_result($r)) {
1383                         return false;
1384                 }
1385
1386                 $server = $r[0];
1387
1388                 // Discover new servers out there (Works from Friendica version 3.5.2)
1389                 self::fetchServerlist($server["poco"]);
1390
1391                 // Fetch all users from the other server
1392                 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1393
1394                 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1395
1396                 $retdata = z_fetch_url($url);
1397                 if ($retdata["success"]) {
1398                         $data = json_decode($retdata["body"]);
1399
1400                         self::discoverServer($data, 2);
1401
1402                         if (Config::get('system', 'poco_discovery') > 1) {
1403                                 $timeframe = Config::get('system', 'poco_discovery_since');
1404                                 if ($timeframe == 0) {
1405                                         $timeframe = 30;
1406                                 }
1407
1408                                 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1409
1410                                 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1411                                 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1412
1413                                 $success = false;
1414
1415                                 $retdata = z_fetch_url($url);
1416                                 if ($retdata["success"]) {
1417                                         logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1418                                         $success = self::discoverServer(json_decode($retdata["body"]));
1419                                 }
1420
1421                                 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1422                                         logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1423                                         self::discoverServerUsers($data, $server);
1424                                 }
1425                         }
1426
1427                         q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1428
1429                         return true;
1430                 } else {
1431                         // If the server hadn't replied correctly, then force a sanity check
1432                         self::checkServer($server["url"], $server["network"], true);
1433
1434                         // If we couldn't reach the server, we will try it some time later
1435                         q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1436
1437                         return false;
1438                 }
1439         }
1440
1441         public static function discover($complete = false)
1442         {
1443                 // Update the server list
1444                 self::discoverFederation();
1445
1446                 $no_of_queries = 5;
1447
1448                 $requery_days = intval(Config::get("system", "poco_requery_days"));
1449
1450                 if ($requery_days == 0) {
1451                         $requery_days = 7;
1452                 }
1453                 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1454
1455                 $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));
1456                 if (DBM::is_result($r)) {
1457                         foreach ($r as $server) {
1458                                 if (!self::checkServer($server["url"], $server["network"])) {
1459                                         // The server is not reachable? Okay, then we will try it later
1460                                         q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($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         public 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         public 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 = array("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 = GlobalContact::sanitize($gcontact);
1605                                         GlobalContact::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 }