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