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