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