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