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