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