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