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
11 use Friendica\Core\Config;
13 require_once('include/datetime.php');
14 require_once("include/Scrape.php");
15 require_once("include/network.php");
16 require_once("include/html2bbcode.php");
17 require_once("include/Contact.php");
18 require_once("include/Photo.php");
21 * @brief Fetch POCO data
23 * @param integer $cid Contact ID
24 * @param integer $uid User ID
25 * @param integer $zcid Global Contact ID
26 * @param integer $url POCO address that should be polled
28 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
29 * and add the entries to the gcontact (Global Contact) table, or update existing entries
30 * if anything (name or photo) has changed.
31 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
33 * Once the global contact is stored add (if necessary) the contact linkage which associates
34 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
35 * pointing to the same global contact id.
38 function poco_load($cid, $uid = 0, $zcid = 0, $url = null) {
39 // Call the function "poco_load_worker" via the worker
40 proc_run(PRIORITY_LOW, "include/discover_poco.php", "poco_load", intval($cid), intval($uid), intval($zcid), base64_encode($url));
44 * @brief Fetch POCO data from the worker
46 * @param integer $cid Contact ID
47 * @param integer $uid User ID
48 * @param integer $zcid Global Contact ID
49 * @param integer $url POCO address that should be polled
52 function poco_load_worker($cid, $uid, $zcid, $url) {
56 if((! $url) || (! $uid)) {
57 $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
60 if (dbm::is_result($r)) {
72 $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') ;
74 logger('poco_load: ' . $url, LOGGER_DEBUG);
78 logger('poco_load: returns ' . $s, LOGGER_DATA);
80 logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
82 if(($a->get_curl_code() > 299) || (! $s))
87 logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
89 if(! isset($j->entry))
93 foreach($j->entry as $entry) {
101 $updated = NULL_DATE;
109 $name = $entry->displayName;
111 if (isset($entry->urls)) {
112 foreach ($entry->urls as $url) {
113 if ($url->type == 'profile') {
114 $profile_url = $url->value;
117 if ($url->type == 'webfinger') {
118 $connect_url = str_replace('acct:' , '', $url->value);
123 if (isset($entry->photos)) {
124 foreach ($entry->photos as $photo) {
125 if ($photo->type == 'profile') {
126 $profile_photo = $photo->value;
132 if (isset($entry->updated)) {
133 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
136 if (isset($entry->network)) {
137 $network = $entry->network;
140 if (isset($entry->currentLocation)) {
141 $location = $entry->currentLocation;
144 if (isset($entry->aboutMe)) {
145 $about = html2bbcode($entry->aboutMe);
148 if (isset($entry->gender)) {
149 $gender = $entry->gender;
152 if (isset($entry->generation) AND ($entry->generation > 0)) {
153 $generation = ++$entry->generation;
156 if (isset($entry->tags)) {
157 foreach($entry->tags as $tag) {
158 $keywords = implode(", ", $tag);
162 if (isset($entry->contactType) AND ($entry->contactType >= 0))
163 $contact_type = $entry->contactType;
165 $gcontact = array("url" => $profile_url,
167 "network" => $network,
168 "photo" => $profile_photo,
170 "location" => $location,
172 "keywords" => $keywords,
173 "connect" => $connect_url,
174 "updated" => $updated,
175 "contact-type" => $contact_type,
176 "generation" => $generation);
179 $gcontact = sanitize_gcontact($gcontact);
180 $gcid = update_gcontact($gcontact);
182 link_gcontact($gcid, $uid, $cid, $zcid);
183 } catch (Exception $e) {
184 logger($e->getMessage(), LOGGER_DEBUG);
187 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
189 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
197 * @brief Sanitize the given gcontact data
199 * @param array $gcontact array with gcontact data
204 * 1: Profiles on this server
205 * 2: Contacts of profiles on this server
206 * 3: Contacts of contacts of profiles on this server
210 function sanitize_gcontact($gcontact) {
212 if ($gcontact['url'] == "") {
213 throw new Exception('URL is empty');
216 $urlparts = parse_url($gcontact['url']);
217 if (!isset($urlparts["scheme"])) {
218 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
221 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
222 "identi.ca", "alpha.app.net"))) {
223 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
226 // Don't store the statusnet connector as network
227 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
228 if ($gcontact['network'] == NETWORK_STATUSNET) {
229 $gcontact['network'] = "";
232 // Assure that there are no parameter fragments in the profile url
233 if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
234 $gcontact['url'] = clean_contact_url($gcontact['url']);
237 $alternate = poco_alternate_ostatus_url($gcontact['url']);
239 // The global contacts should contain the original picture, not the cached one
240 if (($gcontact['generation'] != 1) AND stristr(normalise_link($gcontact['photo']), normalise_link(App::get_baseurl()."/photo/"))) {
241 $gcontact['photo'] = "";
244 if (!isset($gcontact['network'])) {
245 $r = q("SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
246 dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
248 if (dbm::is_result($r)) {
249 $gcontact['network'] = $r[0]["network"];
252 if (($gcontact['network'] == "") OR ($gcontact['network'] == NETWORK_OSTATUS)) {
253 $r = q("SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
254 dbesc($gcontact['url']), dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
256 if (dbm::is_result($r)) {
257 $gcontact['network'] = $r[0]["network"];
262 $gcontact['server_url'] = '';
263 $gcontact['network'] = '';
265 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
266 dbesc(normalise_link($gcontact['url']))
270 if (!isset($gcontact['network']) AND ($x[0]["network"] != NETWORK_STATUSNET)) {
271 $gcontact['network'] = $x[0]["network"];
273 if ($gcontact['updated'] <= NULL_DATE) {
274 $gcontact['updated'] = $x[0]["updated"];
276 if (!isset($gcontact['server_url']) AND (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
277 $gcontact['server_url'] = $x[0]["server_url"];
279 if (!isset($gcontact['addr'])) {
280 $gcontact['addr'] = $x[0]["addr"];
284 if ((!isset($gcontact['network']) OR !isset($gcontact['name']) OR !isset($gcontact['addr']) OR !isset($gcontact['photo']) OR !isset($gcontact['server_url']) OR $alternate)
285 AND poco_reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)) {
286 $data = Probe::uri($gcontact['url']);
288 if ($data["network"] == NETWORK_PHANTOM) {
289 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
292 $orig_profile = $gcontact['url'];
294 $gcontact["server_url"] = $data["baseurl"];
296 $gcontact = array_merge($gcontact, $data);
298 if ($alternate AND ($gcontact['network'] == NETWORK_OSTATUS)) {
299 // Delete the old entry - if it exists
300 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
302 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
303 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
308 if (!isset($gcontact['name']) OR !isset($gcontact['photo'])) {
309 throw new Exception('No name and photo for URL '.$gcontact['url']);
312 if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
313 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
316 if (!isset($gcontact['server_url'])) {
317 // We check the server url to be sure that it is a real one
318 $server_url = poco_detect_server($gcontact['url']);
320 // We are now sure that it is a correct URL. So we use it in the future
321 if ($server_url != "") {
322 $gcontact['server_url'] = $server_url;
326 // The server URL doesn't seem to be valid, so we don't store it.
327 if (!poco_check_server($gcontact['server_url'], $gcontact['network'])) {
328 $gcontact['server_url'] = "";
335 * @brief Link the gcontact entry with user, contact and global contact
337 * @param integer $gcid Global contact ID
338 * @param integer $cid Contact ID
339 * @param integer $uid User ID
340 * @param integer $zcid Global Contact ID
343 function link_gcontact($gcid, $uid = 0, $cid = 0, $zcid = 0) {
349 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
355 if (!dbm::is_result($r)) {
356 q("INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
361 dbesc(datetime_convert())
364 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
365 dbesc(datetime_convert()),
374 function poco_reachable($profile, $server = "", $network = "", $force = false) {
377 $server = poco_detect_server($profile);
382 return poco_check_server($server, $network, $force);
385 function poco_detect_server($profile) {
387 // Try to detect the server path based upon some known standard paths
390 if ($server_url == "") {
391 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
392 if ($friendica != $profile) {
393 $server_url = $friendica;
394 $network = NETWORK_DFRN;
398 if ($server_url == "") {
399 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
400 if ($diaspora != $profile) {
401 $server_url = $diaspora;
402 $network = NETWORK_DIASPORA;
406 if ($server_url == "") {
407 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
408 if ($red != $profile) {
410 $network = NETWORK_DIASPORA;
415 if ($server_url == "") {
416 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
417 if ($mastodon != $profile) {
418 $server_url = $mastodon;
419 $network = NETWORK_OSTATUS;
423 // Numeric OStatus variant
424 if ($server_url == "") {
425 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
426 if ($ostatus != $profile) {
427 $server_url = $ostatus;
428 $network = NETWORK_OSTATUS;
433 if ($server_url == "") {
434 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
435 if ($base != $profile) {
437 $network = NETWORK_PHANTOM;
441 if ($server_url == "") {
445 $r = q("SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
446 dbesc(normalise_link($server_url)));
447 if (dbm::is_result($r)) {
451 // Fetch the host-meta to check if this really is a server
452 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
453 if (!$serverret["success"]) {
460 function poco_alternate_ostatus_url($url) {
461 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
464 function poco_last_updated($profile, $force = false) {
466 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
467 dbesc(normalise_link($profile)));
469 if (!dbm::is_result($gcontacts)) {
473 $contact = array("url" => $profile);
475 if ($gcontacts[0]["created"] <= NULL_DATE) {
476 $contact['created'] = datetime_convert();
480 $server_url = normalise_link(poco_detect_server($profile));
483 if (($server_url == '') AND ($gcontacts[0]["server_url"] != "")) {
484 $server_url = $gcontacts[0]["server_url"];
487 if (!$force AND (($server_url == '') OR ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
488 $server_url = normalise_link(poco_detect_server($profile));
491 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
492 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
496 if ($server_url != "") {
497 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
499 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
500 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
503 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
506 $contact['server_url'] = $server_url;
509 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
510 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
511 dbesc(normalise_link($server_url)));
514 $contact['network'] = $server[0]["network"];
520 // noscrape is really fast so we don't cache the call.
521 if (($server_url != "") AND ($gcontacts[0]["nick"] != "")) {
523 // Use noscrape if possible
524 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
527 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
529 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
531 $noscrape = json_decode($noscraperet["body"], true);
533 if (is_array($noscrape)) {
534 $contact["network"] = $server[0]["network"];
536 if (isset($noscrape["fn"])) {
537 $contact["name"] = $noscrape["fn"];
539 if (isset($noscrape["comm"])) {
540 $contact["community"] = $noscrape["comm"];
542 if (isset($noscrape["tags"])) {
543 $keywords = implode(" ", $noscrape["tags"]);
544 if ($keywords != "") {
545 $contact["keywords"] = $keywords;
549 $location = formatted_location($noscrape);
551 $contact["location"] = $location;
553 if (isset($noscrape["dfrn-notify"])) {
554 $contact["notify"] = $noscrape["dfrn-notify"];
556 // Remove all fields that are not present in the gcontact table
557 unset($noscrape["fn"]);
558 unset($noscrape["key"]);
559 unset($noscrape["homepage"]);
560 unset($noscrape["comm"]);
561 unset($noscrape["tags"]);
562 unset($noscrape["locality"]);
563 unset($noscrape["region"]);
564 unset($noscrape["country-name"]);
565 unset($noscrape["contacts"]);
566 unset($noscrape["dfrn-request"]);
567 unset($noscrape["dfrn-confirm"]);
568 unset($noscrape["dfrn-notify"]);
569 unset($noscrape["dfrn-poll"]);
571 // Set the date of the last contact
572 /// @todo By now the function "update_gcontact" doesn't work with this field
573 //$contact["last_contact"] = datetime_convert();
575 $contact = array_merge($contact, $noscrape);
577 update_gcontact($contact);
579 if (trim($noscrape["updated"]) != "") {
580 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
581 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
583 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
585 return $noscrape["updated"];
592 // If we only can poll the feed, then we only do this once a while
593 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
594 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
596 update_gcontact($contact);
597 return $gcontacts[0]["updated"];
600 $data = Probe::uri($profile);
602 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
603 // Then check the other link and delete this one
604 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
605 (normalise_link($profile) == normalise_link($data["alias"])) AND
606 (normalise_link($profile) != normalise_link($data["url"]))) {
608 // Delete the old entry
609 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
610 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
612 $gcontact = array_merge($gcontacts[0], $data);
614 $gcontact["server_url"] = $data["baseurl"];
617 $gcontact = sanitize_gcontact($gcontact);
618 update_gcontact($gcontact);
620 poco_last_updated($data["url"], $force);
621 } catch (Exception $e) {
622 logger($e->getMessage(), LOGGER_DEBUG);
625 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
629 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
630 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
631 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
633 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
637 $contact = array_merge($contact, $data);
639 $contact["server_url"] = $data["baseurl"];
641 update_gcontact($contact);
643 $feedret = z_fetch_url($data["poll"]);
645 if (!$feedret["success"]) {
646 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
647 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
649 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
653 $doc = new DOMDocument();
654 @$doc->loadXML($feedret["body"]);
656 $xpath = new DomXPath($doc);
657 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
659 $entries = $xpath->query('/atom:feed/atom:entry');
663 foreach ($entries AS $entry) {
664 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
665 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
667 if ($last_updated < $published)
668 $last_updated = $published;
670 if ($last_updated < $updated)
671 $last_updated = $updated;
674 // Maybe there aren't any entries. Then check if it is a valid feed
675 if ($last_updated == "") {
676 if ($xpath->query('/atom:feed')->length > 0) {
677 $last_updated = NULL_DATE;
680 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
681 dbesc(dbm::date($last_updated)), dbesc(dbm::date()), dbesc(normalise_link($profile)));
683 if (($gcontacts[0]["generation"] == 0)) {
684 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
685 dbesc(normalise_link($profile)));
688 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
690 return($last_updated);
693 function poco_do_update($created, $updated, $last_failure, $last_contact) {
694 $now = strtotime(datetime_convert());
696 if ($updated > $last_contact)
697 $contact_time = strtotime($updated);
699 $contact_time = strtotime($last_contact);
701 $failure_time = strtotime($last_failure);
702 $created_time = strtotime($created);
704 // If there is no "created" time then use the current time
705 if ($created_time <= 0)
706 $created_time = $now;
708 // If the last contact was less than 24 hours then don't update
709 if (($now - $contact_time) < (60 * 60 * 24))
712 // If the last failure was less than 24 hours then don't update
713 if (($now - $failure_time) < (60 * 60 * 24))
716 // If the last contact was less than a week ago and the last failure is older than a week then don't update
717 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
720 // 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
721 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
724 // 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
725 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
731 function poco_to_boolean($val) {
732 if (($val == "true") OR ($val == 1))
734 if (($val == "false") OR ($val == 0))
741 * @brief Detect server type (Hubzilla or Friendica) via the poco data
743 * @param object $data POCO data
744 * @return array Server data
746 function poco_detect_poco_data($data) {
749 if (!isset($data->entry)) {
753 if (count($data->entry) == 0) {
757 if (!isset($data->entry[0]->urls)) {
761 if (count($data->entry[0]->urls) == 0) {
765 foreach ($data->entry[0]->urls AS $url) {
766 if ($url->type == 'zot') {
768 $server["platform"] = 'Hubzilla';
769 $server["network"] = NETWORK_DIASPORA;
777 * @brief Detect server type by using the nodeinfo data
779 * @param string $server_url address of the server
780 * @return array Server data
782 function poco_fetch_nodeinfo($server_url) {
783 $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
784 if (!$serverret["success"]) {
788 $nodeinfo = json_decode($serverret['body']);
790 if (!is_object($nodeinfo)) {
794 if (!is_array($nodeinfo->links)) {
800 foreach ($nodeinfo->links AS $link) {
801 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
802 $nodeinfo_url = $link->href;
806 if ($nodeinfo_url == '') {
810 $serverret = z_fetch_url($nodeinfo_url);
811 if (!$serverret["success"]) {
815 $nodeinfo = json_decode($serverret['body']);
817 if (!is_object($nodeinfo)) {
823 $server['register_policy'] = REGISTER_CLOSED;
825 if (is_bool($nodeinfo->openRegistrations) AND $nodeinfo->openRegistrations) {
826 $server['register_policy'] = REGISTER_OPEN;
829 if (is_object($nodeinfo->software)) {
830 if (isset($nodeinfo->software->name)) {
831 $server['platform'] = $nodeinfo->software->name;
834 if (isset($nodeinfo->software->version)) {
835 $server['version'] = $nodeinfo->software->version;
836 // Version numbers on Nodeinfo are presented with additional info, e.g.:
837 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
838 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
842 if (is_object($nodeinfo->metadata)) {
843 if (isset($nodeinfo->metadata->nodeName)) {
844 $server['site_name'] = $nodeinfo->metadata->nodeName;
852 if (is_array($nodeinfo->protocols->inbound)) {
853 foreach ($nodeinfo->protocols->inbound AS $inbound) {
854 if ($inbound == 'diaspora') {
857 if ($inbound == 'friendica') {
860 if ($inbound == 'gnusocial') {
867 $server['network'] = NETWORK_OSTATUS;
870 $server['network'] = NETWORK_DIASPORA;
873 $server['network'] = NETWORK_DFRN;
884 * @brief Detect server type (Hubzilla or Friendica) via the front page body
886 * @param string $body Front page of the server
887 * @return array Server data
889 function poco_detect_server_type($body) {
892 $doc = new \DOMDocument();
893 @$doc->loadHTML($body);
894 $xpath = new \DomXPath($doc);
896 $list = $xpath->query("//meta[@name]");
898 foreach ($list as $node) {
900 if ($node->attributes->length) {
901 foreach ($node->attributes as $attribute) {
902 $attr[$attribute->name] = $attribute->value;
905 if ($attr['name'] == 'generator') {
906 $version_part = explode(" ", $attr['content']);
907 if (count($version_part) == 2) {
908 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
910 $server["platform"] = $version_part[0];
911 $server["version"] = $version_part[1];
912 $server["network"] = NETWORK_DFRN;
919 $list = $xpath->query("//meta[@property]");
921 foreach ($list as $node) {
923 if ($node->attributes->length) {
924 foreach ($node->attributes as $attribute) {
925 $attr[$attribute->name] = $attribute->value;
928 if ($attr['property'] == 'generator') {
929 if (in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
931 $server["platform"] = $attr['content'];
932 $server["version"] = "";
933 $server["network"] = NETWORK_DIASPORA;
943 $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
947 function poco_check_server($server_url, $network = "", $force = false) {
949 // Unify the server address
950 $server_url = trim($server_url, "/");
951 $server_url = str_replace("/index.php", "", $server_url);
953 if ($server_url == "")
956 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
957 if (dbm::is_result($servers)) {
959 if ($servers[0]["created"] <= NULL_DATE) {
960 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
961 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
963 $poco = $servers[0]["poco"];
964 $noscrape = $servers[0]["noscrape"];
967 $network = $servers[0]["network"];
969 $last_contact = $servers[0]["last_contact"];
970 $last_failure = $servers[0]["last_failure"];
971 $version = $servers[0]["version"];
972 $platform = $servers[0]["platform"];
973 $site_name = $servers[0]["site_name"];
974 $info = $servers[0]["info"];
975 $register_policy = $servers[0]["register_policy"];
977 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
978 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
979 return ($last_contact >= $last_failure);
988 $register_policy = -1;
990 $last_contact = NULL_DATE;
991 $last_failure = NULL_DATE;
993 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
996 $possible_failure = false;
997 $orig_last_failure = $last_failure;
998 $orig_last_contact = $last_contact;
1000 // Check if the page is accessible via SSL.
1001 $orig_server_url = $server_url;
1002 $server_url = str_replace("http://", "https://", $server_url);
1004 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1005 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1007 // Quit if there is a timeout.
1008 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1009 if (dbm::is_result($servers) AND ($orig_server_url == $server_url) AND
1010 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1011 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1015 // Maybe the page is unencrypted only?
1016 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1017 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1018 $server_url = str_replace("https://", "http://", $server_url);
1020 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1021 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1023 // Quit if there is a timeout
1024 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1025 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1029 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1032 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1033 // Workaround for bad configured servers (known nginx problem)
1034 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
1035 $last_failure = datetime_convert();
1038 $possible_failure = true;
1039 } elseif ($network == NETWORK_DIASPORA)
1040 $last_contact = datetime_convert();
1042 // If the server has no possible failure we reset the cached data
1043 if (!$possible_failure) {
1048 $register_policy = -1;
1053 $serverret = z_fetch_url($server_url."/poco");
1054 if ($serverret["success"]) {
1055 $data = json_decode($serverret["body"]);
1056 if (isset($data->totalResults)) {
1057 $poco = $server_url."/poco";
1058 $last_contact = datetime_convert();
1060 $server = poco_detect_poco_data($data);
1062 $platform = $server['platform'];
1063 $network = $server['network'];
1072 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1073 $serverret = z_fetch_url($server_url);
1075 if (!$serverret["success"] OR ($serverret["body"] == "")) {
1076 $last_failure = datetime_convert();
1079 $server = poco_detect_server_type($serverret["body"]);
1081 $platform = $server['platform'];
1082 $network = $server['network'];
1083 $version = $server['version'];
1084 $site_name = $server['site_name'];
1085 $last_contact = datetime_convert();
1088 $lines = explode("\n",$serverret["header"]);
1090 foreach($lines as $line) {
1091 $line = trim($line);
1092 if(stristr($line,'X-Diaspora-Version:')) {
1093 $platform = "Diaspora";
1094 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1095 $version = trim(str_replace("x-diaspora-version:", "", $version));
1096 $network = NETWORK_DIASPORA;
1097 $versionparts = explode("-", $version);
1098 $version = $versionparts[0];
1099 $last_contact = datetime_convert();
1102 if(stristr($line,'Server: Mastodon')) {
1103 $platform = "Mastodon";
1104 $network = NETWORK_OSTATUS;
1105 // Mastodon doesn't reveal version numbers
1107 $last_contact = datetime_convert();
1114 if (!$failure AND ($poco == "")) {
1115 // Test for Statusnet
1116 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1117 // The "not implemented" is a special treatment for really, really old Friendica versions
1118 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
1119 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1120 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1121 $platform = "StatusNet";
1122 // Remove junk that some GNU Social servers return
1123 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1124 $version = trim($version, '"');
1125 $network = NETWORK_OSTATUS;
1126 $last_contact = datetime_convert();
1129 // Test for GNU Social
1130 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1131 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1132 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1133 $platform = "GNU Social";
1134 // Remove junk that some GNU Social servers return
1135 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1136 $version = trim($version, '"');
1137 $network = NETWORK_OSTATUS;
1138 $last_contact = datetime_convert();
1143 // Test for Hubzilla, Redmatrix or Friendica
1144 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1145 if ($serverret["success"]) {
1146 $data = json_decode($serverret["body"]);
1147 if (isset($data->site->server)) {
1148 $last_contact = datetime_convert();
1150 if (isset($data->site->platform)) {
1151 $platform = $data->site->platform->PLATFORM_NAME;
1152 $version = $data->site->platform->STD_VERSION;
1153 $network = NETWORK_DIASPORA;
1155 if (isset($data->site->BlaBlaNet)) {
1156 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1157 $version = $data->site->BlaBlaNet->STD_VERSION;
1158 $network = NETWORK_DIASPORA;
1160 if (isset($data->site->hubzilla)) {
1161 $platform = $data->site->hubzilla->PLATFORM_NAME;
1162 $version = $data->site->hubzilla->RED_VERSION;
1163 $network = NETWORK_DIASPORA;
1165 if (isset($data->site->redmatrix)) {
1166 if (isset($data->site->redmatrix->PLATFORM_NAME))
1167 $platform = $data->site->redmatrix->PLATFORM_NAME;
1168 elseif (isset($data->site->redmatrix->RED_PLATFORM))
1169 $platform = $data->site->redmatrix->RED_PLATFORM;
1171 $version = $data->site->redmatrix->RED_VERSION;
1172 $network = NETWORK_DIASPORA;
1174 if (isset($data->site->friendica)) {
1175 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1176 $version = $data->site->friendica->FRIENDICA_VERSION;
1177 $network = NETWORK_DFRN;
1180 $site_name = $data->site->name;
1182 $data->site->closed = poco_to_boolean($data->site->closed);
1183 $data->site->private = poco_to_boolean($data->site->private);
1184 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
1186 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
1187 $register_policy = REGISTER_APPROVE;
1188 elseif (!$data->site->closed AND !$data->site->private)
1189 $register_policy = REGISTER_OPEN;
1191 $register_policy = REGISTER_CLOSED;
1197 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1199 $serverret = z_fetch_url($server_url."/statistics.json");
1200 if ($serverret["success"]) {
1201 $data = json_decode($serverret["body"]);
1202 if (isset($data->version)) {
1203 $version = $data->version;
1204 // Version numbers on statistics.json are presented with additional info, e.g.:
1205 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1206 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1209 $site_name = $data->name;
1211 if (isset($data->network)) {
1212 $platform = $data->network;
1215 if ($platform == "Diaspora") {
1216 $network = NETWORK_DIASPORA;
1219 if ($data->registrations_open) {
1220 $register_policy = REGISTER_OPEN;
1222 $register_policy = REGISTER_CLOSED;
1225 if (isset($data->version))
1226 $last_contact = datetime_convert();
1230 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1232 $server = poco_fetch_nodeinfo($server_url);
1234 $register_policy = $server['register_policy'];
1236 if (isset($server['platform'])) {
1237 $platform = $server['platform'];
1240 if (isset($server['network'])) {
1241 $network = $server['network'];
1244 if (isset($server['version'])) {
1245 $version = $server['version'];
1248 if (isset($server['site_name'])) {
1249 $site_name = $server['site_name'];
1252 $last_contact = datetime_convert();
1256 // Check for noscrape
1257 // Friendica servers could be detected as OStatus servers
1258 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1259 $serverret = z_fetch_url($server_url."/friendica/json");
1261 if (!$serverret["success"])
1262 $serverret = z_fetch_url($server_url."/friendika/json");
1264 if ($serverret["success"]) {
1265 $data = json_decode($serverret["body"]);
1267 if (isset($data->version)) {
1268 $last_contact = datetime_convert();
1269 $network = NETWORK_DFRN;
1271 $noscrape = $data->no_scrape_url;
1272 $version = $data->version;
1273 $site_name = $data->site_name;
1274 $info = $data->info;
1275 $register_policy_str = $data->register_policy;
1276 $platform = $data->platform;
1278 switch ($register_policy_str) {
1279 case "REGISTER_CLOSED":
1280 $register_policy = REGISTER_CLOSED;
1282 case "REGISTER_APPROVE":
1283 $register_policy = REGISTER_APPROVE;
1285 case "REGISTER_OPEN":
1286 $register_policy = REGISTER_OPEN;
1293 if ($possible_failure AND !$failure) {
1294 $last_failure = datetime_convert();
1299 $last_contact = $orig_last_contact;
1301 $last_failure = $orig_last_failure;
1304 if (($last_contact <= $last_failure) AND !$failure) {
1305 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1306 } else if (($last_contact >= $last_failure) AND $failure) {
1307 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1310 // Check again if the server exists
1311 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1313 $version = strip_tags($version);
1314 $site_name = strip_tags($site_name);
1315 $info = strip_tags($info);
1316 $platform = strip_tags($platform);
1319 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1320 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1325 intval($register_policy),
1330 dbesc($last_contact),
1331 dbesc($last_failure),
1332 dbesc(normalise_link($server_url))
1334 } elseif (!$failure) {
1335 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1336 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1338 dbesc(normalise_link($server_url)),
1342 intval($register_policy),
1347 dbesc(datetime_convert()),
1348 dbesc($last_contact),
1349 dbesc($last_failure),
1350 dbesc(datetime_convert())
1353 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
1358 function count_common_friends($uid,$cid) {
1360 $r = q("SELECT count(*) as `total`
1361 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1362 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1363 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1364 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1371 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1372 if (dbm::is_result($r))
1373 return $r[0]['total'];
1379 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1382 $sql_extra = " order by rand() ";
1384 $sql_extra = " order by `gcontact`.`name` asc ";
1386 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1388 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1389 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1390 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1391 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1392 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1393 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1394 $sql_extra LIMIT %d, %d",
1408 function count_common_friends_zcid($uid,$zcid) {
1410 $r = q("SELECT count(*) as `total`
1411 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1412 where `glink`.`zcid` = %d
1413 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1418 if (dbm::is_result($r))
1419 return $r[0]['total'];
1424 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1427 $sql_extra = " order by rand() ";
1429 $sql_extra = " order by `gcontact`.`name` asc ";
1431 $r = q("SELECT `gcontact`.*
1432 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1433 where `glink`.`zcid` = %d
1434 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1435 $sql_extra limit %d, %d",
1447 function count_all_friends($uid,$cid) {
1449 $r = q("SELECT count(*) as `total`
1450 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1451 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1452 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1457 if (dbm::is_result($r))
1458 return $r[0]['total'];
1464 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1466 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1468 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1469 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1470 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1471 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1472 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1485 function suggestion_query($uid, $start = 0, $limit = 80) {
1491 // Uncommented because the result of the queries are to big to store it in the cache.
1492 // We need to decide if we want to change the db column type or if we want to delete it.
1493 // $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1494 // if (!is_null($list)) {
1498 $network = array(NETWORK_DFRN);
1500 if (get_config('system','diaspora_enabled'))
1501 $network[] = NETWORK_DIASPORA;
1503 if (!get_config('system','ostatus_disabled'))
1504 $network[] = NETWORK_OSTATUS;
1506 $sql_network = implode("', '", $network);
1507 $sql_network = "'".$sql_network."'";
1509 /// @todo This query is really slow
1510 // By now we cache the data for five minutes
1511 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1512 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1513 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1514 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1515 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1516 AND `gcontact`.`updated` >= '%s'
1517 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1518 AND `gcontact`.`network` IN (%s)
1519 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1530 if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1531 // Uncommented because the result of the queries are to big to store it in the cache.
1532 // We need to decide if we want to change the db column type or if we want to delete it.
1533 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1538 $r2 = q("SELECT gcontact.* FROM gcontact
1539 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1540 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1541 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1542 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1543 AND `gcontact`.`updated` >= '%s'
1544 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1545 AND `gcontact`.`network` IN (%s)
1546 ORDER BY rand() LIMIT %d, %d",
1557 foreach ($r2 AS $suggestion)
1558 $list[$suggestion["nurl"]] = $suggestion;
1560 foreach ($r AS $suggestion)
1561 $list[$suggestion["nurl"]] = $suggestion;
1563 while (sizeof($list) > ($limit))
1566 // Uncommented because the result of the queries are to big to store it in the cache.
1567 // We need to decide if we want to change the db column type or if we want to delete it.
1568 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1572 function update_suggestions() {
1578 /// @TODO Check if it is really neccessary to poll the own server
1579 poco_load(0,0,0,App::get_baseurl() . '/poco');
1581 $done[] = App::get_baseurl() . '/poco';
1583 if (strlen(get_config('system','directory'))) {
1584 $x = fetch_url(get_server()."/pubsites");
1586 $j = json_decode($x);
1588 foreach ($j->entries as $entry) {
1590 poco_check_server($entry->url);
1592 $url = $entry->url . '/poco';
1593 if (! in_array($url,$done)) {
1594 poco_load(0,0,0,$entry->url . '/poco');
1601 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1602 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1603 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1606 if (dbm::is_result($r)) {
1607 foreach ($r as $rr) {
1608 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1609 if(! in_array($base,$done))
1610 poco_load(0,0,0,$base);
1616 * @brief Fetch server list from remote servers and adds them when they are new.
1618 * @param string $poco URL to the POCO endpoint
1620 function poco_fetch_serverlist($poco) {
1621 $serverret = z_fetch_url($poco."/@server");
1622 if (!$serverret["success"]) {
1625 $serverlist = json_decode($serverret['body']);
1627 if (!is_array($serverlist)) {
1631 foreach ($serverlist AS $server) {
1632 $server_url = str_replace("/index.php", "", $server->url);
1634 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1635 if (!dbm::is_result($r)) {
1636 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1637 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($server_url));
1642 function poco_discover_federation() {
1643 $last = get_config('poco','last_federation_discovery');
1646 $next = $last + (24 * 60 * 60);
1651 // Discover Friendica, Hubzilla and Diaspora servers
1652 $serverdata = fetch_url("http://the-federation.info/pods.json");
1655 $servers = json_decode($serverdata);
1657 foreach ($servers->pods AS $server) {
1658 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode("https://".$server->host));
1662 // Disvover Mastodon servers
1663 if (!Config::get('system','ostatus_disabled')) {
1664 $serverdata = fetch_url("https://instances.mastodon.xyz/instances.json");
1667 $servers = json_decode($serverdata);
1669 foreach ($servers AS $server) {
1670 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1671 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($url));
1676 // Currently disabled, since the service isn't available anymore.
1677 // It is not removed since I hope that there will be a successor.
1678 // Discover GNU Social Servers.
1679 //if (!get_config('system','ostatus_disabled')) {
1680 // $serverdata = "http://gstools.org/api/get_open_instances/";
1682 // $result = z_fetch_url($serverdata);
1683 // if ($result["success"]) {
1684 // $servers = json_decode($result["body"]);
1686 // foreach($servers->data AS $server)
1687 // poco_check_server($server->instance_address);
1691 set_config('poco','last_federation_discovery', time());
1694 function poco_discover_single_server($id) {
1695 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1696 if (!dbm::is_result($r)) {
1702 // Discover new servers out there (Works from Friendica version 3.5.2)
1703 poco_fetch_serverlist($server["poco"]);
1705 // Fetch all users from the other server
1706 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1708 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1710 $retdata = z_fetch_url($url);
1711 if ($retdata["success"]) {
1712 $data = json_decode($retdata["body"]);
1714 poco_discover_server($data, 2);
1716 if (get_config('system','poco_discovery') > 1) {
1718 $timeframe = get_config('system','poco_discovery_since');
1719 if ($timeframe == 0) {
1723 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1725 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1726 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1730 $retdata = z_fetch_url($url);
1731 if ($retdata["success"]) {
1732 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1733 $success = poco_discover_server(json_decode($retdata["body"]));
1736 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1737 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1738 poco_discover_server_users($data, $server);
1742 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1746 // If the server hadn't replied correctly, then force a sanity check
1747 poco_check_server($server["url"], $server["network"], true);
1749 // If we couldn't reach the server, we will try it some time later
1750 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1756 function poco_discover($complete = false) {
1758 // Update the server list
1759 poco_discover_federation();
1763 $requery_days = intval(get_config("system", "poco_requery_days"));
1765 if ($requery_days == 0) {
1768 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1770 $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));
1771 if (dbm::is_result($r)) {
1772 foreach ($r AS $server) {
1774 if (!poco_check_server($server["url"], $server["network"])) {
1775 // The server is not reachable? Okay, then we will try it later
1776 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1780 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1781 proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server_directory", intval($server['id']));
1783 if (!$complete AND (--$no_of_queries == 0)) {
1790 function poco_discover_server_users($data, $server) {
1792 if (!isset($data->entry))
1795 foreach ($data->entry AS $entry) {
1797 if (isset($entry->urls)) {
1798 foreach($entry->urls as $url)
1799 if ($url->type == 'profile') {
1800 $profile_url = $url->value;
1801 $urlparts = parse_url($profile_url);
1802 $username = end(explode("/", $urlparts["path"]));
1805 if ($username != "") {
1806 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1808 // Fetch all contacts from a given user from the other server
1809 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1811 $retdata = z_fetch_url($url);
1812 if ($retdata["success"])
1813 poco_discover_server(json_decode($retdata["body"]), 3);
1818 function poco_discover_server($data, $default_generation = 0) {
1820 if (!isset($data->entry) OR !count($data->entry))
1825 foreach ($data->entry AS $entry) {
1827 $profile_photo = '';
1831 $updated = NULL_DATE;
1837 $generation = $default_generation;
1839 $name = $entry->displayName;
1841 if (isset($entry->urls)) {
1842 foreach($entry->urls as $url) {
1843 if ($url->type == 'profile') {
1844 $profile_url = $url->value;
1847 if ($url->type == 'webfinger') {
1848 $connect_url = str_replace('acct:' , '', $url->value);
1854 if (isset($entry->photos)) {
1855 foreach ($entry->photos as $photo) {
1856 if ($photo->type == 'profile') {
1857 $profile_photo = $photo->value;
1863 if (isset($entry->updated)) {
1864 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1867 if(isset($entry->network)) {
1868 $network = $entry->network;
1871 if(isset($entry->currentLocation)) {
1872 $location = $entry->currentLocation;
1875 if(isset($entry->aboutMe)) {
1876 $about = html2bbcode($entry->aboutMe);
1879 if(isset($entry->gender)) {
1880 $gender = $entry->gender;
1883 if(isset($entry->generation) AND ($entry->generation > 0)) {
1884 $generation = ++$entry->generation;
1887 if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
1888 $contact_type = $entry->contactType;
1891 if(isset($entry->tags)) {
1892 foreach ($entry->tags as $tag) {
1893 $keywords = implode(", ", $tag);
1897 if ($generation > 0) {
1900 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1902 $gcontact = array("url" => $profile_url,
1904 "network" => $network,
1905 "photo" => $profile_photo,
1907 "location" => $location,
1908 "gender" => $gender,
1909 "keywords" => $keywords,
1910 "connect" => $connect_url,
1911 "updated" => $updated,
1912 "contact-type" => $contact_type,
1913 "generation" => $generation);
1916 $gcontact = sanitize_gcontact($gcontact);
1917 update_gcontact($gcontact);
1918 } catch (Exception $e) {
1919 logger($e->getMessage(), LOGGER_DEBUG);
1922 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1929 * @brief Removes unwanted parts from a contact url
1931 * @param string $url Contact url
1932 * @return string Contact url with the wanted parts
1934 function clean_contact_url($url) {
1935 $parts = parse_url($url);
1937 if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1940 $new_url = $parts["scheme"]."://".$parts["host"];
1942 if (isset($parts["port"]))
1943 $new_url .= ":".$parts["port"];
1945 if (isset($parts["path"]))
1946 $new_url .= $parts["path"];
1948 if ($new_url != $url)
1949 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1955 * @brief Replace alternate OStatus user format with the primary one
1957 * @param arr $contact contact array (called by reference)
1959 function fix_alternate_contact_address(&$contact) {
1960 if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1961 $data = probe_url($contact["url"]);
1962 if ($contact["network"] == NETWORK_OSTATUS) {
1963 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1964 $contact["url"] = $data["url"];
1965 $contact["addr"] = $data["addr"];
1966 $contact["alias"] = $data["alias"];
1967 $contact["server_url"] = $data["baseurl"];
1973 * @brief Fetch the gcontact id, add an entry if not existed
1975 * @param arr $contact contact array
1976 * @return bool|int Returns false if not found, integer if contact was found
1978 function get_gcontact_id($contact) {
1983 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1984 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1988 if ($contact["network"] == NETWORK_STATUSNET)
1989 $contact["network"] = NETWORK_OSTATUS;
1991 // All new contacts are hidden by default
1992 if (!isset($contact["hide"]))
1993 $contact["hide"] = true;
1995 // Replace alternate OStatus user format with the primary one
1996 fix_alternate_contact_address($contact);
1998 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1999 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
2000 $contact["url"] = clean_contact_url($contact["url"]);
2002 $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
2003 dbesc(normalise_link($contact["url"])));
2006 $gcontact_id = $r[0]["id"];
2008 // Update every 90 days
2009 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
2010 $last_failure_str = $r[0]["last_failure"];
2011 $last_failure = strtotime($r[0]["last_failure"]);
2012 $last_contact_str = $r[0]["last_contact"];
2013 $last_contact = strtotime($r[0]["last_contact"]);
2014 $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
2017 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
2018 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
2019 dbesc($contact["name"]),
2020 dbesc($contact["nick"]),
2021 dbesc($contact["addr"]),
2022 dbesc($contact["network"]),
2023 dbesc($contact["url"]),
2024 dbesc(normalise_link($contact["url"])),
2025 dbesc($contact["photo"]),
2026 dbesc(datetime_convert()),
2027 dbesc(datetime_convert()),
2028 dbesc($contact["location"]),
2029 dbesc($contact["about"]),
2030 intval($contact["hide"]),
2031 intval($contact["generation"])
2034 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
2035 dbesc(normalise_link($contact["url"])));
2038 $gcontact_id = $r[0]["id"];
2040 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
2045 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
2046 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
2049 if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
2050 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
2051 dbesc(normalise_link($contact["url"])),
2052 intval($gcontact_id));
2054 return $gcontact_id;
2058 * @brief Updates the gcontact table from a given array
2060 * @param arr $contact contact array
2061 * @return bool|int Returns false if not found, integer if contact was found
2063 function update_gcontact($contact) {
2065 // Check for invalid "contact-type" value
2066 if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
2067 $contact['contact-type'] = 0;
2070 /// @todo update contact table as well
2072 $gcontact_id = get_gcontact_id($contact);
2077 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
2078 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
2079 FROM `gcontact` WHERE `id` = %d LIMIT 1",
2080 intval($gcontact_id));
2082 // Get all field names
2084 foreach ($r[0] AS $field => $data)
2085 $fields[$field] = $data;
2087 unset($fields["url"]);
2088 unset($fields["updated"]);
2089 unset($fields["hide"]);
2091 // Bugfix: We had an error in the storing of keywords which lead to the "0"
2092 // This value is still transmitted via poco.
2093 if ($contact["keywords"] == "0")
2094 unset($contact["keywords"]);
2096 if ($r[0]["keywords"] == "0")
2097 $r[0]["keywords"] = "";
2099 // assign all unassigned fields from the database entry
2100 foreach ($fields AS $field => $data)
2101 if (!isset($contact[$field]) OR ($contact[$field] == ""))
2102 $contact[$field] = $r[0][$field];
2104 if (!isset($contact["hide"]))
2105 $contact["hide"] = $r[0]["hide"];
2107 $fields["hide"] = $r[0]["hide"];
2109 if ($contact["network"] == NETWORK_STATUSNET)
2110 $contact["network"] = NETWORK_OSTATUS;
2112 // Replace alternate OStatus user format with the primary one
2113 fix_alternate_contact_address($contact);
2115 if (!isset($contact["updated"]))
2116 $contact["updated"] = dbm::date();
2118 if ($contact["server_url"] == "") {
2119 $server_url = $contact["url"];
2121 $server_url = matching_url($server_url, $contact["alias"]);
2122 if ($server_url != "")
2123 $contact["server_url"] = $server_url;
2125 $server_url = matching_url($server_url, $contact["photo"]);
2126 if ($server_url != "")
2127 $contact["server_url"] = $server_url;
2129 $server_url = matching_url($server_url, $contact["notify"]);
2130 if ($server_url != "")
2131 $contact["server_url"] = $server_url;
2133 $contact["server_url"] = normalise_link($contact["server_url"]);
2135 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
2136 $hostname = str_replace("http://", "", $contact["server_url"]);
2137 $contact["addr"] = $contact["nick"]."@".$hostname;
2140 // Check if any field changed
2142 unset($fields["generation"]);
2144 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
2145 foreach ($fields AS $field => $data)
2146 if ($contact[$field] != $r[0][$field]) {
2147 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
2151 if ($contact["generation"] < $r[0]["generation"]) {
2152 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
2158 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
2160 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
2161 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
2162 `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
2163 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
2164 `server_url` = '%s', `connect` = '%s'
2165 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
2166 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
2167 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
2168 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
2169 intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
2170 dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
2171 dbesc($contact["about"]), intval($contact["generation"]), dbesc(dbm::date($contact["updated"])),
2172 dbesc($contact["server_url"]), dbesc($contact["connect"]),
2173 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
2176 // Now update the contact entry with the user id "0" as well.
2177 // This is used for the shadow copies of public items.
2178 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
2179 dbesc(normalise_link($contact["url"])));
2182 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
2184 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
2186 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
2187 `network` = '%s', `bd` = '%s', `gender` = '%s',
2188 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
2189 `url` = '%s', `location` = '%s', `about` = '%s'
2191 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
2192 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
2193 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
2194 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
2195 intval($r[0]["id"]));
2199 return $gcontact_id;
2203 * @brief Updates the gcontact entry from probe
2205 * @param str $url profile link
2207 function update_gcontact_from_probe($url) {
2208 $data = probe_url($url);
2210 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
2211 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
2215 $data["server_url"] = $data["baseurl"];
2217 update_gcontact($data);
2221 * @brief Update the gcontact entry for a given user id
2223 * @param int $uid User ID
2225 function update_gcontact_for_user($uid) {
2226 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
2227 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
2228 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
2229 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
2230 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
2232 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
2233 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
2234 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
2237 $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
2238 "country-name" => $r[0]["country-name"]));
2240 // The "addr" field was added in 3.4.3 so it can be empty for older users
2241 if ($r[0]["addr"] != "")
2242 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
2244 $addr = $r[0]["addr"];
2246 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
2247 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
2248 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
2249 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
2250 "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
2251 "nick" => $r[0]["nickname"], "addr" => $addr,
2252 "connect" => $addr, "server_url" => App::get_baseurl(),
2253 "generation" => 1, "network" => NETWORK_DFRN);
2255 update_gcontact($gcontact);
2259 * @brief Fetches users of given GNU Social server
2261 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
2263 * @param str $server Server address
2265 function gs_fetch_users($server) {
2267 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
2269 $url = $server."/main/statistics";
2271 $result = z_fetch_url($url);
2272 if (!$result["success"])
2275 $statistics = json_decode($result["body"]);
2277 if (is_object($statistics->config)) {
2278 if ($statistics->config->instance_with_ssl)
2279 $server = "https://";
2281 $server = "http://";
2283 $server .= $statistics->config->instance_address;
2285 $hostname = $statistics->config->instance_address;
2287 if ($statistics->instance_with_ssl)
2288 $server = "https://";
2290 $server = "http://";
2292 $server .= $statistics->instance_address;
2294 $hostname = $statistics->instance_address;
2297 if (is_object($statistics->users))
2298 foreach ($statistics->users AS $nick => $user) {
2299 $profile_url = $server."/".$user->nickname;
2301 $contact = array("url" => $profile_url,
2302 "name" => $user->fullname,
2303 "addr" => $user->nickname."@".$hostname,
2304 "nick" => $user->nickname,
2305 "about" => $user->bio,
2306 "network" => NETWORK_OSTATUS,
2307 "photo" => App::get_baseurl()."/images/person-175.jpg");
2308 get_gcontact_id($contact);
2313 * @brief Asking GNU Social server on a regular base for their user data
2316 function gs_discover() {
2318 $requery_days = intval(get_config("system", "poco_requery_days"));
2320 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
2322 $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",
2323 dbesc(NETWORK_OSTATUS), dbesc($last_update));
2328 foreach ($r AS $server) {
2329 gs_fetch_users($server["url"]);
2330 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
2335 * @brief Returns a list of all known servers
2336 * @return array List of server urls
2338 function poco_serverlist() {
2339 $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
2340 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
2341 ORDER BY `last_contact`
2343 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
2344 if (!dbm::is_result($r)) {