3 * @file include/socgraph.php
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
10 use \Friendica\Core\Config;
12 require_once('include/datetime.php');
13 require_once("include/Scrape.php");
14 require_once("include/network.php");
15 require_once("include/html2bbcode.php");
16 require_once("include/Contact.php");
17 require_once("include/Photo.php");
20 * @brief Fetch POCO data
22 * @param integer $cid Contact ID
23 * @param integer $uid User ID
24 * @param integer $zcid Global Contact ID
25 * @param integer $url POCO address that should be polled
27 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
28 * and add the entries to the gcontact (Global Contact) table, or update existing entries
29 * if anything (name or photo) has changed.
30 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
32 * Once the global contact is stored add (if necessary) the contact linkage which associates
33 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
34 * pointing to the same global contact id.
37 function poco_load($cid, $uid = 0, $zcid = 0, $url = null) {
38 // Call the function "poco_load_worker" via the worker
39 proc_run(PRIORITY_LOW, "include/discover_poco.php", "poco_load", intval($cid), intval($uid), intval($zcid), base64_encode($url));
43 * @brief Fetch POCO data from the worker
45 * @param integer $cid Contact ID
46 * @param integer $uid User ID
47 * @param integer $zcid Global Contact ID
48 * @param integer $url POCO address that should be polled
51 function poco_load_worker($cid, $uid, $zcid, $url) {
55 if((! $url) || (! $uid)) {
56 $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
59 if (dbm::is_result($r)) {
71 $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') ;
73 logger('poco_load: ' . $url, LOGGER_DEBUG);
77 logger('poco_load: returns ' . $s, LOGGER_DATA);
79 logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
81 if(($a->get_curl_code() > 299) || (! $s))
86 logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
88 if(! isset($j->entry))
92 foreach($j->entry as $entry) {
100 $updated = NULL_DATE;
108 $name = $entry->displayName;
110 if (isset($entry->urls)) {
111 foreach ($entry->urls as $url) {
112 if ($url->type == 'profile') {
113 $profile_url = $url->value;
116 if ($url->type == 'webfinger') {
117 $connect_url = str_replace('acct:' , '', $url->value);
122 if (isset($entry->photos)) {
123 foreach ($entry->photos as $photo) {
124 if ($photo->type == 'profile') {
125 $profile_photo = $photo->value;
131 if (isset($entry->updated)) {
132 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
135 if (isset($entry->network)) {
136 $network = $entry->network;
139 if (isset($entry->currentLocation)) {
140 $location = $entry->currentLocation;
143 if (isset($entry->aboutMe)) {
144 $about = html2bbcode($entry->aboutMe);
147 if (isset($entry->gender)) {
148 $gender = $entry->gender;
151 if (isset($entry->generation) AND ($entry->generation > 0)) {
152 $generation = ++$entry->generation;
155 if (isset($entry->tags)) {
156 foreach($entry->tags as $tag) {
157 $keywords = implode(", ", $tag);
161 if (isset($entry->contactType) AND ($entry->contactType >= 0))
162 $contact_type = $entry->contactType;
164 $gcontact = array("url" => $profile_url,
166 "network" => $network,
167 "photo" => $profile_photo,
169 "location" => $location,
171 "keywords" => $keywords,
172 "connect" => $connect_url,
173 "updated" => $updated,
174 "contact-type" => $contact_type,
175 "generation" => $generation);
178 $gcontact = sanitize_gcontact($gcontact);
179 $gcid = update_gcontact($gcontact);
181 link_gcontact($gcid, $uid, $cid, $zcid);
182 } catch (Exception $e) {
183 logger($e->getMessage(), LOGGER_DEBUG);
186 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
188 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
196 * @brief Sanitize the given gcontact data
198 * @param array $gcontact array with gcontact data
203 * 1: Profiles on this server
204 * 2: Contacts of profiles on this server
205 * 3: Contacts of contacts of profiles on this server
209 function sanitize_gcontact($gcontact) {
211 if ($gcontact['url'] == "") {
212 throw new Exception('URL is empty');
215 $urlparts = parse_url($gcontact['url']);
216 if (!isset($urlparts["scheme"])) {
217 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
220 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
221 "identi.ca", "alpha.app.net"))) {
222 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
225 // Don't store the statusnet connector as network
226 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
227 if ($gcontact['network'] == NETWORK_STATUSNET) {
228 $gcontact['network'] = "";
231 // Assure that there are no parameter fragments in the profile url
232 if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
233 $gcontact['url'] = clean_contact_url($gcontact['url']);
236 $alternate = poco_alternate_ostatus_url($gcontact['url']);
238 // The global contacts should contain the original picture, not the cached one
239 if (($gcontact['generation'] != 1) AND stristr(normalise_link($gcontact['photo']), normalise_link(App::get_baseurl()."/photo/"))) {
240 $gcontact['photo'] = "";
243 if (!isset($gcontact['network'])) {
244 $r = q("SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
245 dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
247 if (dbm::is_result($r)) {
248 $gcontact['network'] = $r[0]["network"];
251 if (($gcontact['network'] == "") OR ($gcontact['network'] == NETWORK_OSTATUS)) {
252 $r = q("SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
253 dbesc($gcontact['url']), dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
255 if (dbm::is_result($r)) {
256 $gcontact['network'] = $r[0]["network"];
261 $gcontact['server_url'] = '';
262 $gcontact['network'] = '';
264 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
265 dbesc(normalise_link($gcontact['url']))
269 if (!isset($gcontact['network']) AND ($x[0]["network"] != NETWORK_STATUSNET)) {
270 $gcontact['network'] = $x[0]["network"];
272 if ($gcontact['updated'] <= NULL_DATE) {
273 $gcontact['updated'] = $x[0]["updated"];
275 if (!isset($gcontact['server_url']) AND (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
276 $gcontact['server_url'] = $x[0]["server_url"];
278 if (!isset($gcontact['addr'])) {
279 $gcontact['addr'] = $x[0]["addr"];
283 if ((!isset($gcontact['network']) OR !isset($gcontact['name']) OR !isset($gcontact['addr']) OR !isset($gcontact['photo']) OR !isset($gcontact['server_url']) OR $alternate)
284 AND poco_reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)) {
285 $data = Probe::uri($gcontact['url']);
287 if ($data["network"] == NETWORK_PHANTOM) {
288 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
291 $orig_profile = $gcontact['url'];
293 $gcontact["server_url"] = $data["baseurl"];
295 $gcontact = array_merge($gcontact, $data);
297 if ($alternate AND ($gcontact['network'] == NETWORK_OSTATUS)) {
298 // Delete the old entry - if it exists
299 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
301 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
302 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
307 if (!isset($gcontact['name']) OR !isset($gcontact['photo'])) {
308 throw new Exception('No name and photo for URL '.$gcontact['url']);
311 if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
312 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
315 if (!isset($gcontact['server_url'])) {
316 // We check the server url to be sure that it is a real one
317 $server_url = poco_detect_server($gcontact['url']);
319 // We are now sure that it is a correct URL. So we use it in the future
320 if ($server_url != "") {
321 $gcontact['server_url'] = $server_url;
325 // The server URL doesn't seem to be valid, so we don't store it.
326 if (!poco_check_server($gcontact['server_url'], $gcontact['network'])) {
327 $gcontact['server_url'] = "";
334 * @brief Link the gcontact entry with user, contact and global contact
336 * @param integer $gcid Global contact ID
337 * @param integer $cid Contact ID
338 * @param integer $uid User ID
339 * @param integer $zcid Global Contact ID
342 function link_gcontact($gcid, $uid = 0, $cid = 0, $zcid = 0) {
348 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
354 if (!dbm::is_result($r)) {
355 q("INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
360 dbesc(datetime_convert())
363 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
364 dbesc(datetime_convert()),
373 function poco_reachable($profile, $server = "", $network = "", $force = false) {
376 $server = poco_detect_server($profile);
381 return poco_check_server($server, $network, $force);
384 function poco_detect_server($profile) {
386 // Try to detect the server path based upon some known standard paths
389 if ($server_url == "") {
390 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
391 if ($friendica != $profile) {
392 $server_url = $friendica;
393 $network = NETWORK_DFRN;
397 if ($server_url == "") {
398 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
399 if ($diaspora != $profile) {
400 $server_url = $diaspora;
401 $network = NETWORK_DIASPORA;
405 if ($server_url == "") {
406 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
407 if ($red != $profile) {
409 $network = NETWORK_DIASPORA;
414 if ($server_url == "") {
415 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
416 if ($mastodon != $profile) {
417 $server_url = $mastodon;
418 $network = NETWORK_OSTATUS;
422 // Numeric OStatus variant
423 if ($server_url == "") {
424 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
425 if ($ostatus != $profile) {
426 $server_url = $ostatus;
427 $network = NETWORK_OSTATUS;
432 if ($server_url == "") {
433 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
434 if ($base != $profile) {
436 $network = NETWORK_PHANTOM;
440 if ($server_url == "") {
444 $r = q("SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
445 dbesc(normalise_link($server_url)));
446 if (dbm::is_result($r)) {
450 // Fetch the host-meta to check if this really is a server
451 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
452 if (!$serverret["success"]) {
459 function poco_alternate_ostatus_url($url) {
460 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
463 function poco_last_updated($profile, $force = false) {
465 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
466 dbesc(normalise_link($profile)));
468 if (!dbm::is_result($gcontacts)) {
472 $contact = array("url" => $profile);
474 if ($gcontacts[0]["created"] <= NULL_DATE) {
475 $contact['created'] = datetime_convert();
479 $server_url = normalise_link(poco_detect_server($profile));
482 if (($server_url == '') AND ($gcontacts[0]["server_url"] != "")) {
483 $server_url = $gcontacts[0]["server_url"];
486 if (!$force AND (($server_url == '') OR ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
487 $server_url = normalise_link(poco_detect_server($profile));
490 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
491 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
495 if ($server_url != "") {
496 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
498 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
499 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
502 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
505 $contact['server_url'] = $server_url;
508 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
509 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
510 dbesc(normalise_link($server_url)));
513 $contact['network'] = $server[0]["network"];
519 // noscrape is really fast so we don't cache the call.
520 if (($server_url != "") AND ($gcontacts[0]["nick"] != "")) {
522 // Use noscrape if possible
523 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
526 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
528 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
530 $noscrape = json_decode($noscraperet["body"], true);
532 if (is_array($noscrape)) {
533 $contact["network"] = $server[0]["network"];
535 if (isset($noscrape["fn"])) {
536 $contact["name"] = $noscrape["fn"];
538 if (isset($noscrape["comm"])) {
539 $contact["community"] = $noscrape["comm"];
541 if (isset($noscrape["tags"])) {
542 $keywords = implode(" ", $noscrape["tags"]);
543 if ($keywords != "") {
544 $contact["keywords"] = $keywords;
548 $location = formatted_location($noscrape);
550 $contact["location"] = $location;
552 if (isset($noscrape["dfrn-notify"])) {
553 $contact["notify"] = $noscrape["dfrn-notify"];
555 // Remove all fields that are not present in the gcontact table
556 unset($noscrape["fn"]);
557 unset($noscrape["key"]);
558 unset($noscrape["homepage"]);
559 unset($noscrape["comm"]);
560 unset($noscrape["tags"]);
561 unset($noscrape["locality"]);
562 unset($noscrape["region"]);
563 unset($noscrape["country-name"]);
564 unset($noscrape["contacts"]);
565 unset($noscrape["dfrn-request"]);
566 unset($noscrape["dfrn-confirm"]);
567 unset($noscrape["dfrn-notify"]);
568 unset($noscrape["dfrn-poll"]);
570 // Set the date of the last contact
571 /// @todo By now the function "update_gcontact" doesn't work with this field
572 //$contact["last_contact"] = datetime_convert();
574 $contact = array_merge($contact, $noscrape);
576 update_gcontact($contact);
578 if (trim($noscrape["updated"]) != "") {
579 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
580 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
582 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
584 return $noscrape["updated"];
591 // If we only can poll the feed, then we only do this once a while
592 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
593 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
595 update_gcontact($contact);
596 return $gcontacts[0]["updated"];
599 $data = Probe::uri($profile);
601 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
602 // Then check the other link and delete this one
603 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
604 (normalise_link($profile) == normalise_link($data["alias"])) AND
605 (normalise_link($profile) != normalise_link($data["url"]))) {
607 // Delete the old entry
608 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
609 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
611 $gcontact = array_merge($gcontacts[0], $data);
613 $gcontact["server_url"] = $data["baseurl"];
616 $gcontact = sanitize_gcontact($gcontact);
617 update_gcontact($gcontact);
619 poco_last_updated($data["url"], $force);
620 } catch (Exception $e) {
621 logger($e->getMessage(), LOGGER_DEBUG);
624 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
628 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
629 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
630 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
632 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
636 $contact = array_merge($contact, $data);
638 $contact["server_url"] = $data["baseurl"];
640 update_gcontact($contact);
642 $feedret = z_fetch_url($data["poll"]);
644 if (!$feedret["success"]) {
645 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
646 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
648 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
652 $doc = new DOMDocument();
653 @$doc->loadXML($feedret["body"]);
655 $xpath = new DomXPath($doc);
656 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
658 $entries = $xpath->query('/atom:feed/atom:entry');
662 foreach ($entries AS $entry) {
663 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
664 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
666 if ($last_updated < $published)
667 $last_updated = $published;
669 if ($last_updated < $updated)
670 $last_updated = $updated;
673 // Maybe there aren't any entries. Then check if it is a valid feed
674 if ($last_updated == "") {
675 if ($xpath->query('/atom:feed')->length > 0) {
676 $last_updated = NULL_DATE;
679 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
680 dbesc(dbm::date($last_updated)), dbesc(dbm::date()), dbesc(normalise_link($profile)));
682 if (($gcontacts[0]["generation"] == 0)) {
683 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
684 dbesc(normalise_link($profile)));
687 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
689 return($last_updated);
692 function poco_do_update($created, $updated, $last_failure, $last_contact) {
693 $now = strtotime(datetime_convert());
695 if ($updated > $last_contact)
696 $contact_time = strtotime($updated);
698 $contact_time = strtotime($last_contact);
700 $failure_time = strtotime($last_failure);
701 $created_time = strtotime($created);
703 // If there is no "created" time then use the current time
704 if ($created_time <= 0)
705 $created_time = $now;
707 // If the last contact was less than 24 hours then don't update
708 if (($now - $contact_time) < (60 * 60 * 24))
711 // If the last failure was less than 24 hours then don't update
712 if (($now - $failure_time) < (60 * 60 * 24))
715 // If the last contact was less than a week ago and the last failure is older than a week then don't update
716 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
719 // 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
720 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
723 // 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
724 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
730 function poco_to_boolean($val) {
731 if (($val == "true") OR ($val == 1))
733 if (($val == "false") OR ($val == 0))
740 * @brief Detect server type (Hubzilla or Friendica) via the poco data
742 * @param object $data POCO data
743 * @return array Server data
745 function poco_detect_poco_data($data) {
748 if (!isset($data->entry)) {
752 if (count($data->entry) == 0) {
756 if (!isset($data->entry[0]->urls)) {
760 if (count($data->entry[0]->urls) == 0) {
764 foreach ($data->entry[0]->urls AS $url) {
765 if ($url->type == 'zot') {
767 $server["platform"] = 'Hubzilla';
768 $server["network"] = NETWORK_DIASPORA;
776 * @brief Detect server type by using the nodeinfo data
778 * @param string $server_url address of the server
779 * @return array Server data
781 function poco_fetch_nodeinfo($server_url) {
782 $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
783 if (!$serverret["success"]) {
787 $nodeinfo = json_decode($serverret['body']);
789 if (!is_object($nodeinfo)) {
793 if (!is_array($nodeinfo->links)) {
799 foreach ($nodeinfo->links AS $link) {
800 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
801 $nodeinfo_url = $link->href;
805 if ($nodeinfo_url == '') {
809 $serverret = z_fetch_url($nodeinfo_url);
810 if (!$serverret["success"]) {
814 $nodeinfo = json_decode($serverret['body']);
816 if (!is_object($nodeinfo)) {
822 $server['register_policy'] = REGISTER_CLOSED;
824 if (is_bool($nodeinfo->openRegistrations) AND $nodeinfo->openRegistrations) {
825 $server['register_policy'] = REGISTER_OPEN;
828 if (is_object($nodeinfo->software)) {
829 if (isset($nodeinfo->software->name)) {
830 $server['platform'] = $nodeinfo->software->name;
833 if (isset($nodeinfo->software->version)) {
834 $server['version'] = $nodeinfo->software->version;
835 // Version numbers on Nodeinfo are presented with additional info, e.g.:
836 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
837 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
841 if (is_object($nodeinfo->metadata)) {
842 if (isset($nodeinfo->metadata->nodeName)) {
843 $server['site_name'] = $nodeinfo->metadata->nodeName;
851 if (is_array($nodeinfo->protocols->inbound)) {
852 foreach ($nodeinfo->protocols->inbound AS $inbound) {
853 if ($inbound == 'diaspora') {
856 if ($inbound == 'friendica') {
859 if ($inbound == 'gnusocial') {
866 $server['network'] = NETWORK_OSTATUS;
869 $server['network'] = NETWORK_DIASPORA;
872 $server['network'] = NETWORK_DFRN;
883 * @brief Detect server type (Hubzilla or Friendica) via the front page body
885 * @param string $body Front page of the server
886 * @return array Server data
888 function poco_detect_server_type($body) {
891 $doc = new \DOMDocument();
892 @$doc->loadHTML($body);
893 $xpath = new \DomXPath($doc);
895 $list = $xpath->query("//meta[@name]");
897 foreach ($list as $node) {
899 if ($node->attributes->length) {
900 foreach ($node->attributes as $attribute) {
901 $attr[$attribute->name] = $attribute->value;
904 if ($attr['name'] == 'generator') {
905 $version_part = explode(" ", $attr['content']);
906 if (count($version_part) == 2) {
907 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
909 $server["platform"] = $version_part[0];
910 $server["version"] = $version_part[1];
911 $server["network"] = NETWORK_DFRN;
918 $list = $xpath->query("//meta[@property]");
920 foreach ($list as $node) {
922 if ($node->attributes->length) {
923 foreach ($node->attributes as $attribute) {
924 $attr[$attribute->name] = $attribute->value;
927 if ($attr['property'] == 'generator') {
928 if (in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
930 $server["platform"] = $attr['content'];
931 $server["version"] = "";
932 $server["network"] = NETWORK_DIASPORA;
942 $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
946 function poco_check_server($server_url, $network = "", $force = false) {
948 // Unify the server address
949 $server_url = trim($server_url, "/");
950 $server_url = str_replace("/index.php", "", $server_url);
952 if ($server_url == "")
955 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
956 if (dbm::is_result($servers)) {
958 if ($servers[0]["created"] <= NULL_DATE) {
959 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
960 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
962 $poco = $servers[0]["poco"];
963 $noscrape = $servers[0]["noscrape"];
966 $network = $servers[0]["network"];
968 $last_contact = $servers[0]["last_contact"];
969 $last_failure = $servers[0]["last_failure"];
970 $version = $servers[0]["version"];
971 $platform = $servers[0]["platform"];
972 $site_name = $servers[0]["site_name"];
973 $info = $servers[0]["info"];
974 $register_policy = $servers[0]["register_policy"];
976 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
977 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
978 return ($last_contact >= $last_failure);
987 $register_policy = -1;
989 $last_contact = NULL_DATE;
990 $last_failure = NULL_DATE;
992 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
995 $possible_failure = false;
996 $orig_last_failure = $last_failure;
997 $orig_last_contact = $last_contact;
999 // Check if the page is accessible via SSL.
1000 $orig_server_url = $server_url;
1001 $server_url = str_replace("http://", "https://", $server_url);
1003 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1004 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1006 // Quit if there is a timeout.
1007 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1008 if (dbm::is_result($servers) AND ($orig_server_url == $server_url) AND
1009 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1010 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1014 // Maybe the page is unencrypted only?
1015 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1016 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1017 $server_url = str_replace("https://", "http://", $server_url);
1019 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1020 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1022 // Quit if there is a timeout
1023 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1024 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1028 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1031 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1032 // Workaround for bad configured servers (known nginx problem)
1033 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
1034 $last_failure = datetime_convert();
1037 $possible_failure = true;
1038 } elseif ($network == NETWORK_DIASPORA)
1039 $last_contact = datetime_convert();
1041 // If the server has no possible failure we reset the cached data
1042 if (!$possible_failure) {
1047 $register_policy = -1;
1052 $serverret = z_fetch_url($server_url."/poco");
1053 if ($serverret["success"]) {
1054 $data = json_decode($serverret["body"]);
1055 if (isset($data->totalResults)) {
1056 $poco = $server_url."/poco";
1057 $last_contact = datetime_convert();
1059 $server = poco_detect_poco_data($data);
1061 $platform = $server['platform'];
1062 $network = $server['network'];
1071 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1072 $serverret = z_fetch_url($server_url);
1074 if (!$serverret["success"] OR ($serverret["body"] == "")) {
1075 $last_failure = datetime_convert();
1078 $server = poco_detect_server_type($serverret["body"]);
1080 $platform = $server['platform'];
1081 $network = $server['network'];
1082 $version = $server['version'];
1083 $site_name = $server['site_name'];
1084 $last_contact = datetime_convert();
1087 $lines = explode("\n",$serverret["header"]);
1089 foreach($lines as $line) {
1090 $line = trim($line);
1091 if(stristr($line,'X-Diaspora-Version:')) {
1092 $platform = "Diaspora";
1093 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1094 $version = trim(str_replace("x-diaspora-version:", "", $version));
1095 $network = NETWORK_DIASPORA;
1096 $versionparts = explode("-", $version);
1097 $version = $versionparts[0];
1098 $last_contact = datetime_convert();
1101 if(stristr($line,'Server: Mastodon')) {
1102 $platform = "Mastodon";
1103 $network = NETWORK_OSTATUS;
1104 // Mastodon doesn't reveal version numbers
1106 $last_contact = datetime_convert();
1113 if (!$failure AND ($poco == "")) {
1114 // Test for Statusnet
1115 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1116 // The "not implemented" is a special treatment for really, really old Friendica versions
1117 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
1118 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1119 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1120 $platform = "StatusNet";
1121 // Remove junk that some GNU Social servers return
1122 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1123 $version = trim($version, '"');
1124 $network = NETWORK_OSTATUS;
1125 $last_contact = datetime_convert();
1128 // Test for GNU Social
1129 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1130 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1131 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1132 $platform = "GNU Social";
1133 // Remove junk that some GNU Social servers return
1134 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1135 $version = trim($version, '"');
1136 $network = NETWORK_OSTATUS;
1137 $last_contact = datetime_convert();
1142 // Test for Hubzilla, Redmatrix or Friendica
1143 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1144 if ($serverret["success"]) {
1145 $data = json_decode($serverret["body"]);
1146 if (isset($data->site->server)) {
1147 $last_contact = datetime_convert();
1149 if (isset($data->site->platform)) {
1150 $platform = $data->site->platform->PLATFORM_NAME;
1151 $version = $data->site->platform->STD_VERSION;
1152 $network = NETWORK_DIASPORA;
1154 if (isset($data->site->BlaBlaNet)) {
1155 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1156 $version = $data->site->BlaBlaNet->STD_VERSION;
1157 $network = NETWORK_DIASPORA;
1159 if (isset($data->site->hubzilla)) {
1160 $platform = $data->site->hubzilla->PLATFORM_NAME;
1161 $version = $data->site->hubzilla->RED_VERSION;
1162 $network = NETWORK_DIASPORA;
1164 if (isset($data->site->redmatrix)) {
1165 if (isset($data->site->redmatrix->PLATFORM_NAME))
1166 $platform = $data->site->redmatrix->PLATFORM_NAME;
1167 elseif (isset($data->site->redmatrix->RED_PLATFORM))
1168 $platform = $data->site->redmatrix->RED_PLATFORM;
1170 $version = $data->site->redmatrix->RED_VERSION;
1171 $network = NETWORK_DIASPORA;
1173 if (isset($data->site->friendica)) {
1174 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1175 $version = $data->site->friendica->FRIENDICA_VERSION;
1176 $network = NETWORK_DFRN;
1179 $site_name = $data->site->name;
1181 $data->site->closed = poco_to_boolean($data->site->closed);
1182 $data->site->private = poco_to_boolean($data->site->private);
1183 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
1185 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
1186 $register_policy = REGISTER_APPROVE;
1187 elseif (!$data->site->closed AND !$data->site->private)
1188 $register_policy = REGISTER_OPEN;
1190 $register_policy = REGISTER_CLOSED;
1196 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1198 $serverret = z_fetch_url($server_url."/statistics.json");
1199 if ($serverret["success"]) {
1200 $data = json_decode($serverret["body"]);
1201 if (isset($data->version)) {
1202 $version = $data->version;
1203 // Version numbers on statistics.json are presented with additional info, e.g.:
1204 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1205 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1208 $site_name = $data->name;
1210 if (isset($data->network)) {
1211 $platform = $data->network;
1214 if ($platform == "Diaspora") {
1215 $network = NETWORK_DIASPORA;
1218 if ($data->registrations_open) {
1219 $register_policy = REGISTER_OPEN;
1221 $register_policy = REGISTER_CLOSED;
1224 if (isset($data->version))
1225 $last_contact = datetime_convert();
1229 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1231 $server = poco_fetch_nodeinfo($server_url);
1233 $register_policy = $server['register_policy'];
1235 if (isset($server['platform'])) {
1236 $platform = $server['platform'];
1239 if (isset($server['network'])) {
1240 $network = $server['network'];
1243 if (isset($server['version'])) {
1244 $version = $server['version'];
1247 if (isset($server['site_name'])) {
1248 $site_name = $server['site_name'];
1251 $last_contact = datetime_convert();
1255 // Check for noscrape
1256 // Friendica servers could be detected as OStatus servers
1257 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1258 $serverret = z_fetch_url($server_url."/friendica/json");
1260 if (!$serverret["success"])
1261 $serverret = z_fetch_url($server_url."/friendika/json");
1263 if ($serverret["success"]) {
1264 $data = json_decode($serverret["body"]);
1266 if (isset($data->version)) {
1267 $last_contact = datetime_convert();
1268 $network = NETWORK_DFRN;
1270 $noscrape = $data->no_scrape_url;
1271 $version = $data->version;
1272 $site_name = $data->site_name;
1273 $info = $data->info;
1274 $register_policy_str = $data->register_policy;
1275 $platform = $data->platform;
1277 switch ($register_policy_str) {
1278 case "REGISTER_CLOSED":
1279 $register_policy = REGISTER_CLOSED;
1281 case "REGISTER_APPROVE":
1282 $register_policy = REGISTER_APPROVE;
1284 case "REGISTER_OPEN":
1285 $register_policy = REGISTER_OPEN;
1292 if ($possible_failure AND !$failure) {
1293 $last_failure = datetime_convert();
1298 $last_contact = $orig_last_contact;
1300 $last_failure = $orig_last_failure;
1303 if (($last_contact <= $last_failure) AND !$failure) {
1304 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1305 } else if (($last_contact >= $last_failure) AND $failure) {
1306 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1309 // Check again if the server exists
1310 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1312 $version = strip_tags($version);
1313 $site_name = strip_tags($site_name);
1314 $info = strip_tags($info);
1315 $platform = strip_tags($platform);
1318 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1319 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1324 intval($register_policy),
1329 dbesc($last_contact),
1330 dbesc($last_failure),
1331 dbesc(normalise_link($server_url))
1333 } elseif (!$failure) {
1334 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1335 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1337 dbesc(normalise_link($server_url)),
1341 intval($register_policy),
1346 dbesc(datetime_convert()),
1347 dbesc($last_contact),
1348 dbesc($last_failure),
1349 dbesc(datetime_convert())
1352 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
1357 function count_common_friends($uid,$cid) {
1359 $r = q("SELECT count(*) as `total`
1360 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1361 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1362 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1363 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1370 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1371 if (dbm::is_result($r))
1372 return $r[0]['total'];
1378 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1381 $sql_extra = " order by rand() ";
1383 $sql_extra = " order by `gcontact`.`name` asc ";
1385 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1387 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1388 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1389 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1390 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1391 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1392 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1393 $sql_extra LIMIT %d, %d",
1407 function count_common_friends_zcid($uid,$zcid) {
1409 $r = q("SELECT count(*) as `total`
1410 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1411 where `glink`.`zcid` = %d
1412 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1417 if (dbm::is_result($r))
1418 return $r[0]['total'];
1423 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1426 $sql_extra = " order by rand() ";
1428 $sql_extra = " order by `gcontact`.`name` asc ";
1430 $r = q("SELECT `gcontact`.*
1431 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1432 where `glink`.`zcid` = %d
1433 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1434 $sql_extra limit %d, %d",
1446 function count_all_friends($uid,$cid) {
1448 $r = q("SELECT count(*) as `total`
1449 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1450 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1451 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1456 if (dbm::is_result($r))
1457 return $r[0]['total'];
1463 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1465 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1467 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1468 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1469 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1470 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1471 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1484 function suggestion_query($uid, $start = 0, $limit = 80) {
1490 // Uncommented because the result of the queries are to big to store it in the cache.
1491 // We need to decide if we want to change the db column type or if we want to delete it.
1492 // $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1493 // if (!is_null($list)) {
1497 $network = array(NETWORK_DFRN);
1499 if (get_config('system','diaspora_enabled'))
1500 $network[] = NETWORK_DIASPORA;
1502 if (!get_config('system','ostatus_disabled'))
1503 $network[] = NETWORK_OSTATUS;
1505 $sql_network = implode("', '", $network);
1506 $sql_network = "'".$sql_network."'";
1508 /// @todo This query is really slow
1509 // By now we cache the data for five minutes
1510 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1511 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1512 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1513 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1514 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1515 AND `gcontact`.`updated` >= '%s'
1516 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1517 AND `gcontact`.`network` IN (%s)
1518 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1529 if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1530 // Uncommented because the result of the queries are to big to store it in the cache.
1531 // We need to decide if we want to change the db column type or if we want to delete it.
1532 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1537 $r2 = q("SELECT gcontact.* FROM gcontact
1538 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1539 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1540 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1541 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1542 AND `gcontact`.`updated` >= '%s'
1543 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1544 AND `gcontact`.`network` IN (%s)
1545 ORDER BY rand() LIMIT %d, %d",
1556 foreach ($r2 AS $suggestion)
1557 $list[$suggestion["nurl"]] = $suggestion;
1559 foreach ($r AS $suggestion)
1560 $list[$suggestion["nurl"]] = $suggestion;
1562 while (sizeof($list) > ($limit))
1565 // Uncommented because the result of the queries are to big to store it in the cache.
1566 // We need to decide if we want to change the db column type or if we want to delete it.
1567 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1571 function update_suggestions() {
1577 /// @TODO Check if it is really neccessary to poll the own server
1578 poco_load(0,0,0,App::get_baseurl() . '/poco');
1580 $done[] = App::get_baseurl() . '/poco';
1582 if (strlen(get_config('system','directory'))) {
1583 $x = fetch_url(get_server()."/pubsites");
1585 $j = json_decode($x);
1587 foreach ($j->entries as $entry) {
1589 poco_check_server($entry->url);
1591 $url = $entry->url . '/poco';
1592 if (! in_array($url,$done)) {
1593 poco_load(0,0,0,$entry->url . '/poco');
1600 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1601 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1602 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1605 if (dbm::is_result($r)) {
1606 foreach ($r as $rr) {
1607 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1608 if(! in_array($base,$done))
1609 poco_load(0,0,0,$base);
1615 * @brief Fetch server list from remote servers and adds them when they are new.
1617 * @param string $poco URL to the POCO endpoint
1619 function poco_fetch_serverlist($poco) {
1620 $serverret = z_fetch_url($poco."/@server");
1621 if (!$serverret["success"]) {
1624 $serverlist = json_decode($serverret['body']);
1626 if (!is_array($serverlist)) {
1630 foreach ($serverlist AS $server) {
1631 $server_url = str_replace("/index.php", "", $server->url);
1633 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1634 if (!dbm::is_result($r)) {
1635 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1636 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($server_url));
1641 function poco_discover_federation() {
1642 $last = get_config('poco','last_federation_discovery');
1645 $next = $last + (24 * 60 * 60);
1650 // Discover Friendica, Hubzilla and Diaspora servers
1651 $serverdata = fetch_url("http://the-federation.info/pods.json");
1654 $servers = json_decode($serverdata);
1656 foreach ($servers->pods AS $server) {
1657 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode("https://".$server->host));
1661 // Disvover Mastodon servers
1662 if (!Config::get('system','ostatus_disabled')) {
1663 $serverdata = fetch_url("https://instances.mastodon.xyz/instances.json");
1666 $servers = json_decode($serverdata);
1668 foreach ($servers AS $server) {
1669 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1670 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($url));
1675 // Currently disabled, since the service isn't available anymore.
1676 // It is not removed since I hope that there will be a successor.
1677 // Discover GNU Social Servers.
1678 //if (!get_config('system','ostatus_disabled')) {
1679 // $serverdata = "http://gstools.org/api/get_open_instances/";
1681 // $result = z_fetch_url($serverdata);
1682 // if ($result["success"]) {
1683 // $servers = json_decode($result["body"]);
1685 // foreach($servers->data AS $server)
1686 // poco_check_server($server->instance_address);
1690 set_config('poco','last_federation_discovery', time());
1693 function poco_discover_single_server($id) {
1694 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1695 if (!dbm::is_result($r)) {
1701 // Discover new servers out there (Works from Friendica version 3.5.2)
1702 poco_fetch_serverlist($server["poco"]);
1704 // Fetch all users from the other server
1705 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1707 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1709 $retdata = z_fetch_url($url);
1710 if ($retdata["success"]) {
1711 $data = json_decode($retdata["body"]);
1713 poco_discover_server($data, 2);
1715 if (get_config('system','poco_discovery') > 1) {
1717 $timeframe = get_config('system','poco_discovery_since');
1718 if ($timeframe == 0) {
1722 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1724 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1725 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1729 $retdata = z_fetch_url($url);
1730 if ($retdata["success"]) {
1731 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1732 $success = poco_discover_server(json_decode($retdata["body"]));
1735 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1736 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1737 poco_discover_server_users($data, $server);
1741 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1745 // If the server hadn't replied correctly, then force a sanity check
1746 poco_check_server($server["url"], $server["network"], true);
1748 // If we couldn't reach the server, we will try it some time later
1749 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1755 function poco_discover($complete = false) {
1757 // Update the server list
1758 poco_discover_federation();
1762 $requery_days = intval(get_config("system", "poco_requery_days"));
1764 if ($requery_days == 0) {
1767 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1769 $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));
1770 if (dbm::is_result($r)) {
1771 foreach ($r AS $server) {
1773 if (!poco_check_server($server["url"], $server["network"])) {
1774 // The server is not reachable? Okay, then we will try it later
1775 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1779 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1780 proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server_directory", intval($server['id']));
1782 if (!$complete AND (--$no_of_queries == 0)) {
1789 function poco_discover_server_users($data, $server) {
1791 if (!isset($data->entry))
1794 foreach ($data->entry AS $entry) {
1796 if (isset($entry->urls)) {
1797 foreach($entry->urls as $url)
1798 if ($url->type == 'profile') {
1799 $profile_url = $url->value;
1800 $urlparts = parse_url($profile_url);
1801 $username = end(explode("/", $urlparts["path"]));
1804 if ($username != "") {
1805 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1807 // Fetch all contacts from a given user from the other server
1808 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1810 $retdata = z_fetch_url($url);
1811 if ($retdata["success"])
1812 poco_discover_server(json_decode($retdata["body"]), 3);
1817 function poco_discover_server($data, $default_generation = 0) {
1819 if (!isset($data->entry) OR !count($data->entry))
1824 foreach ($data->entry AS $entry) {
1826 $profile_photo = '';
1830 $updated = NULL_DATE;
1836 $generation = $default_generation;
1838 $name = $entry->displayName;
1840 if (isset($entry->urls)) {
1841 foreach($entry->urls as $url) {
1842 if ($url->type == 'profile') {
1843 $profile_url = $url->value;
1846 if ($url->type == 'webfinger') {
1847 $connect_url = str_replace('acct:' , '', $url->value);
1853 if (isset($entry->photos)) {
1854 foreach ($entry->photos as $photo) {
1855 if ($photo->type == 'profile') {
1856 $profile_photo = $photo->value;
1862 if (isset($entry->updated)) {
1863 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1866 if(isset($entry->network)) {
1867 $network = $entry->network;
1870 if(isset($entry->currentLocation)) {
1871 $location = $entry->currentLocation;
1874 if(isset($entry->aboutMe)) {
1875 $about = html2bbcode($entry->aboutMe);
1878 if(isset($entry->gender)) {
1879 $gender = $entry->gender;
1882 if(isset($entry->generation) AND ($entry->generation > 0)) {
1883 $generation = ++$entry->generation;
1886 if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
1887 $contact_type = $entry->contactType;
1890 if(isset($entry->tags)) {
1891 foreach ($entry->tags as $tag) {
1892 $keywords = implode(", ", $tag);
1896 if ($generation > 0) {
1899 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1901 $gcontact = array("url" => $profile_url,
1903 "network" => $network,
1904 "photo" => $profile_photo,
1906 "location" => $location,
1907 "gender" => $gender,
1908 "keywords" => $keywords,
1909 "connect" => $connect_url,
1910 "updated" => $updated,
1911 "contact-type" => $contact_type,
1912 "generation" => $generation);
1915 $gcontact = sanitize_gcontact($gcontact);
1916 update_gcontact($gcontact);
1917 } catch (Exception $e) {
1918 logger($e->getMessage(), LOGGER_DEBUG);
1921 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1928 * @brief Removes unwanted parts from a contact url
1930 * @param string $url Contact url
1931 * @return string Contact url with the wanted parts
1933 function clean_contact_url($url) {
1934 $parts = parse_url($url);
1936 if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1939 $new_url = $parts["scheme"]."://".$parts["host"];
1941 if (isset($parts["port"]))
1942 $new_url .= ":".$parts["port"];
1944 if (isset($parts["path"]))
1945 $new_url .= $parts["path"];
1947 if ($new_url != $url)
1948 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1954 * @brief Replace alternate OStatus user format with the primary one
1956 * @param arr $contact contact array (called by reference)
1958 function fix_alternate_contact_address(&$contact) {
1959 if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1960 $data = probe_url($contact["url"]);
1961 if ($contact["network"] == NETWORK_OSTATUS) {
1962 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1963 $contact["url"] = $data["url"];
1964 $contact["addr"] = $data["addr"];
1965 $contact["alias"] = $data["alias"];
1966 $contact["server_url"] = $data["baseurl"];
1972 * @brief Fetch the gcontact id, add an entry if not existed
1974 * @param arr $contact contact array
1975 * @return bool|int Returns false if not found, integer if contact was found
1977 function get_gcontact_id($contact) {
1982 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1983 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1987 if ($contact["network"] == NETWORK_STATUSNET)
1988 $contact["network"] = NETWORK_OSTATUS;
1990 // All new contacts are hidden by default
1991 if (!isset($contact["hide"]))
1992 $contact["hide"] = true;
1994 // Replace alternate OStatus user format with the primary one
1995 fix_alternate_contact_address($contact);
1997 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1998 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1999 $contact["url"] = clean_contact_url($contact["url"]);
2001 $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
2002 dbesc(normalise_link($contact["url"])));
2005 $gcontact_id = $r[0]["id"];
2007 // Update every 90 days
2008 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
2009 $last_failure_str = $r[0]["last_failure"];
2010 $last_failure = strtotime($r[0]["last_failure"]);
2011 $last_contact_str = $r[0]["last_contact"];
2012 $last_contact = strtotime($r[0]["last_contact"]);
2013 $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
2016 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
2017 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
2018 dbesc($contact["name"]),
2019 dbesc($contact["nick"]),
2020 dbesc($contact["addr"]),
2021 dbesc($contact["network"]),
2022 dbesc($contact["url"]),
2023 dbesc(normalise_link($contact["url"])),
2024 dbesc($contact["photo"]),
2025 dbesc(datetime_convert()),
2026 dbesc(datetime_convert()),
2027 dbesc($contact["location"]),
2028 dbesc($contact["about"]),
2029 intval($contact["hide"]),
2030 intval($contact["generation"])
2033 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
2034 dbesc(normalise_link($contact["url"])));
2037 $gcontact_id = $r[0]["id"];
2039 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
2044 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
2045 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
2048 if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
2049 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
2050 dbesc(normalise_link($contact["url"])),
2051 intval($gcontact_id));
2053 return $gcontact_id;
2057 * @brief Updates the gcontact table from a given array
2059 * @param arr $contact contact array
2060 * @return bool|int Returns false if not found, integer if contact was found
2062 function update_gcontact($contact) {
2064 // Check for invalid "contact-type" value
2065 if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
2066 $contact['contact-type'] = 0;
2069 /// @todo update contact table as well
2071 $gcontact_id = get_gcontact_id($contact);
2076 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
2077 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
2078 FROM `gcontact` WHERE `id` = %d LIMIT 1",
2079 intval($gcontact_id));
2081 // Get all field names
2083 foreach ($r[0] AS $field => $data)
2084 $fields[$field] = $data;
2086 unset($fields["url"]);
2087 unset($fields["updated"]);
2088 unset($fields["hide"]);
2090 // Bugfix: We had an error in the storing of keywords which lead to the "0"
2091 // This value is still transmitted via poco.
2092 if ($contact["keywords"] == "0")
2093 unset($contact["keywords"]);
2095 if ($r[0]["keywords"] == "0")
2096 $r[0]["keywords"] = "";
2098 // assign all unassigned fields from the database entry
2099 foreach ($fields AS $field => $data)
2100 if (!isset($contact[$field]) OR ($contact[$field] == ""))
2101 $contact[$field] = $r[0][$field];
2103 if (!isset($contact["hide"]))
2104 $contact["hide"] = $r[0]["hide"];
2106 $fields["hide"] = $r[0]["hide"];
2108 if ($contact["network"] == NETWORK_STATUSNET)
2109 $contact["network"] = NETWORK_OSTATUS;
2111 // Replace alternate OStatus user format with the primary one
2112 fix_alternate_contact_address($contact);
2114 if (!isset($contact["updated"]))
2115 $contact["updated"] = dbm::date();
2117 if ($contact["server_url"] == "") {
2118 $server_url = $contact["url"];
2120 $server_url = matching_url($server_url, $contact["alias"]);
2121 if ($server_url != "")
2122 $contact["server_url"] = $server_url;
2124 $server_url = matching_url($server_url, $contact["photo"]);
2125 if ($server_url != "")
2126 $contact["server_url"] = $server_url;
2128 $server_url = matching_url($server_url, $contact["notify"]);
2129 if ($server_url != "")
2130 $contact["server_url"] = $server_url;
2132 $contact["server_url"] = normalise_link($contact["server_url"]);
2134 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
2135 $hostname = str_replace("http://", "", $contact["server_url"]);
2136 $contact["addr"] = $contact["nick"]."@".$hostname;
2139 // Check if any field changed
2141 unset($fields["generation"]);
2143 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
2144 foreach ($fields AS $field => $data)
2145 if ($contact[$field] != $r[0][$field]) {
2146 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
2150 if ($contact["generation"] < $r[0]["generation"]) {
2151 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
2157 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
2159 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
2160 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
2161 `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
2162 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
2163 `server_url` = '%s', `connect` = '%s'
2164 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
2165 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
2166 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
2167 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
2168 intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
2169 dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
2170 dbesc($contact["about"]), intval($contact["generation"]), dbesc(dbm::date($contact["updated"])),
2171 dbesc($contact["server_url"]), dbesc($contact["connect"]),
2172 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
2175 // Now update the contact entry with the user id "0" as well.
2176 // This is used for the shadow copies of public items.
2177 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
2178 dbesc(normalise_link($contact["url"])));
2181 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
2183 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
2185 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
2186 `network` = '%s', `bd` = '%s', `gender` = '%s',
2187 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
2188 `url` = '%s', `location` = '%s', `about` = '%s'
2190 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
2191 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
2192 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
2193 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
2194 intval($r[0]["id"]));
2198 return $gcontact_id;
2202 * @brief Updates the gcontact entry from probe
2204 * @param str $url profile link
2206 function update_gcontact_from_probe($url) {
2207 $data = probe_url($url);
2209 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
2210 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
2214 $data["server_url"] = $data["baseurl"];
2216 update_gcontact($data);
2220 * @brief Update the gcontact entry for a given user id
2222 * @param int $uid User ID
2224 function update_gcontact_for_user($uid) {
2225 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
2226 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
2227 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
2228 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
2229 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
2231 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
2232 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
2233 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
2236 $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
2237 "country-name" => $r[0]["country-name"]));
2239 // The "addr" field was added in 3.4.3 so it can be empty for older users
2240 if ($r[0]["addr"] != "")
2241 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
2243 $addr = $r[0]["addr"];
2245 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
2246 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
2247 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
2248 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
2249 "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
2250 "nick" => $r[0]["nickname"], "addr" => $addr,
2251 "connect" => $addr, "server_url" => App::get_baseurl(),
2252 "generation" => 1, "network" => NETWORK_DFRN);
2254 update_gcontact($gcontact);
2258 * @brief Fetches users of given GNU Social server
2260 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
2262 * @param str $server Server address
2264 function gs_fetch_users($server) {
2266 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
2268 $url = $server."/main/statistics";
2270 $result = z_fetch_url($url);
2271 if (!$result["success"])
2274 $statistics = json_decode($result["body"]);
2276 if (is_object($statistics->config)) {
2277 if ($statistics->config->instance_with_ssl)
2278 $server = "https://";
2280 $server = "http://";
2282 $server .= $statistics->config->instance_address;
2284 $hostname = $statistics->config->instance_address;
2286 if ($statistics->instance_with_ssl)
2287 $server = "https://";
2289 $server = "http://";
2291 $server .= $statistics->instance_address;
2293 $hostname = $statistics->instance_address;
2296 if (is_object($statistics->users))
2297 foreach ($statistics->users AS $nick => $user) {
2298 $profile_url = $server."/".$user->nickname;
2300 $contact = array("url" => $profile_url,
2301 "name" => $user->fullname,
2302 "addr" => $user->nickname."@".$hostname,
2303 "nick" => $user->nickname,
2304 "about" => $user->bio,
2305 "network" => NETWORK_OSTATUS,
2306 "photo" => App::get_baseurl()."/images/person-175.jpg");
2307 get_gcontact_id($contact);
2312 * @brief Asking GNU Social server on a regular base for their user data
2315 function gs_discover() {
2317 $requery_days = intval(get_config("system", "poco_requery_days"));
2319 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
2321 $r = q("SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
2322 dbesc(NETWORK_OSTATUS), dbesc($last_update));
2327 foreach ($r AS $server) {
2328 gs_fetch_users($server["url"]);
2329 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
2334 * @brief Returns a list of all known servers
2335 * @return array List of server urls
2337 function poco_serverlist() {
2338 $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
2339 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
2340 ORDER BY `last_contact`
2342 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
2343 if (!dbm::is_result($r)) {