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;
12 require_once("include/Scrape.php");
14 require_once 'include/datetime.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);
1012 dba::p("UPDATE `gserver` SET `last_failure` = ? WHERE `nurl` = ?", datetime_convert(), normalise_link($server_url));
1016 // Maybe the page is unencrypted only?
1017 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1018 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1019 $server_url = str_replace("https://", "http://", $server_url);
1021 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1022 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1024 // Quit if there is a timeout
1025 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1026 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1027 dba::p("UPDATE `gserver` SET `last_failure` = ? WHERE `nurl` = ?", datetime_convert(), normalise_link($server_url));
1031 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1034 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1035 // Workaround for bad configured servers (known nginx problem)
1036 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
1039 $possible_failure = true;
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 $server = poco_detect_poco_data($data);
1060 $platform = $server['platform'];
1061 $network = $server['network'];
1070 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1071 $serverret = z_fetch_url($server_url);
1073 if (!$serverret["success"] OR ($serverret["body"] == "")) {
1076 $server = poco_detect_server_type($serverret["body"]);
1078 $platform = $server['platform'];
1079 $network = $server['network'];
1080 $version = $server['version'];
1081 $site_name = $server['site_name'];
1084 $lines = explode("\n",$serverret["header"]);
1086 foreach($lines as $line) {
1087 $line = trim($line);
1088 if(stristr($line,'X-Diaspora-Version:')) {
1089 $platform = "Diaspora";
1090 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1091 $version = trim(str_replace("x-diaspora-version:", "", $version));
1092 $network = NETWORK_DIASPORA;
1093 $versionparts = explode("-", $version);
1094 $version = $versionparts[0];
1097 if(stristr($line,'Server: Mastodon')) {
1098 $platform = "Mastodon";
1099 $network = NETWORK_OSTATUS;
1106 if (!$failure AND ($poco == "")) {
1107 // Test for Statusnet
1108 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1109 // The "not implemented" is a special treatment for really, really old Friendica versions
1110 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
1111 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1112 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1113 $platform = "StatusNet";
1114 // Remove junk that some GNU Social servers return
1115 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1116 $version = trim($version, '"');
1117 $network = NETWORK_OSTATUS;
1120 // Test for GNU Social
1121 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1122 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1123 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1124 $platform = "GNU Social";
1125 // Remove junk that some GNU Social servers return
1126 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1127 $version = trim($version, '"');
1128 $network = NETWORK_OSTATUS;
1131 // Test for Mastodon
1132 $serverret = z_fetch_url($server_url."/api/v1/instance");
1133 if ($serverret["success"] AND ($serverret["body"] != '')) {
1134 $data = json_decode($serverret["body"]);
1135 if (isset($data->version)) {
1136 $platform = "Mastodon";
1137 $version = $data->version;
1138 $site_name = $data->title;
1139 $info = $data->description;
1140 $network = NETWORK_OSTATUS;
1146 // Test for Hubzilla, Redmatrix or Friendica
1147 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1148 if ($serverret["success"]) {
1149 $data = json_decode($serverret["body"]);
1150 if (isset($data->site->server)) {
1151 if (isset($data->site->platform)) {
1152 $platform = $data->site->platform->PLATFORM_NAME;
1153 $version = $data->site->platform->STD_VERSION;
1154 $network = NETWORK_DIASPORA;
1156 if (isset($data->site->BlaBlaNet)) {
1157 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1158 $version = $data->site->BlaBlaNet->STD_VERSION;
1159 $network = NETWORK_DIASPORA;
1161 if (isset($data->site->hubzilla)) {
1162 $platform = $data->site->hubzilla->PLATFORM_NAME;
1163 $version = $data->site->hubzilla->RED_VERSION;
1164 $network = NETWORK_DIASPORA;
1166 if (isset($data->site->redmatrix)) {
1167 if (isset($data->site->redmatrix->PLATFORM_NAME))
1168 $platform = $data->site->redmatrix->PLATFORM_NAME;
1169 elseif (isset($data->site->redmatrix->RED_PLATFORM))
1170 $platform = $data->site->redmatrix->RED_PLATFORM;
1172 $version = $data->site->redmatrix->RED_VERSION;
1173 $network = NETWORK_DIASPORA;
1175 if (isset($data->site->friendica)) {
1176 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1177 $version = $data->site->friendica->FRIENDICA_VERSION;
1178 $network = NETWORK_DFRN;
1181 $site_name = $data->site->name;
1183 $data->site->closed = poco_to_boolean($data->site->closed);
1184 $data->site->private = poco_to_boolean($data->site->private);
1185 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
1187 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
1188 $register_policy = REGISTER_APPROVE;
1189 elseif (!$data->site->closed AND !$data->site->private)
1190 $register_policy = REGISTER_OPEN;
1192 $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;
1227 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1229 $server = poco_fetch_nodeinfo($server_url);
1231 $register_policy = $server['register_policy'];
1233 if (isset($server['platform'])) {
1234 $platform = $server['platform'];
1237 if (isset($server['network'])) {
1238 $network = $server['network'];
1241 if (isset($server['version'])) {
1242 $version = $server['version'];
1245 if (isset($server['site_name'])) {
1246 $site_name = $server['site_name'];
1251 // Check for noscrape
1252 // Friendica servers could be detected as OStatus servers
1253 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1254 $serverret = z_fetch_url($server_url."/friendica/json");
1256 if (!$serverret["success"])
1257 $serverret = z_fetch_url($server_url."/friendika/json");
1259 if ($serverret["success"]) {
1260 $data = json_decode($serverret["body"]);
1262 if (isset($data->version)) {
1263 $network = NETWORK_DFRN;
1265 $noscrape = $data->no_scrape_url;
1266 $version = $data->version;
1267 $site_name = $data->site_name;
1268 $info = $data->info;
1269 $register_policy_str = $data->register_policy;
1270 $platform = $data->platform;
1272 switch ($register_policy_str) {
1273 case "REGISTER_CLOSED":
1274 $register_policy = REGISTER_CLOSED;
1276 case "REGISTER_APPROVE":
1277 $register_policy = REGISTER_APPROVE;
1279 case "REGISTER_OPEN":
1280 $register_policy = REGISTER_OPEN;
1287 if ($possible_failure AND !$failure) {
1292 $last_contact = $orig_last_contact;
1293 $last_failure = datetime_convert();
1295 $last_contact = datetime_convert();
1296 $last_failure = $orig_last_failure;
1299 if (($last_contact <= $last_failure) AND !$failure) {
1300 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1301 } else if (($last_contact >= $last_failure) AND $failure) {
1302 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1305 // Check again if the server exists
1306 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1308 $version = strip_tags($version);
1309 $site_name = strip_tags($site_name);
1310 $info = strip_tags($info);
1311 $platform = strip_tags($platform);
1314 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1315 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1320 intval($register_policy),
1325 dbesc($last_contact),
1326 dbesc($last_failure),
1327 dbesc(normalise_link($server_url))
1329 } elseif (!$failure) {
1330 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1331 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1333 dbesc(normalise_link($server_url)),
1337 intval($register_policy),
1342 dbesc(datetime_convert()),
1343 dbesc($last_contact),
1344 dbesc($last_failure),
1345 dbesc(datetime_convert())
1348 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
1353 function count_common_friends($uid,$cid) {
1355 $r = q("SELECT count(*) as `total`
1356 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1357 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1358 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1359 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1366 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1367 if (dbm::is_result($r))
1368 return $r[0]['total'];
1374 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1377 $sql_extra = " order by rand() ";
1379 $sql_extra = " order by `gcontact`.`name` asc ";
1381 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1383 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1384 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1385 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1386 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1387 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1388 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1389 $sql_extra LIMIT %d, %d",
1403 function count_common_friends_zcid($uid,$zcid) {
1405 $r = q("SELECT count(*) as `total`
1406 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1407 where `glink`.`zcid` = %d
1408 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1413 if (dbm::is_result($r))
1414 return $r[0]['total'];
1419 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1422 $sql_extra = " order by rand() ";
1424 $sql_extra = " order by `gcontact`.`name` asc ";
1426 $r = q("SELECT `gcontact`.*
1427 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1428 where `glink`.`zcid` = %d
1429 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1430 $sql_extra limit %d, %d",
1442 function count_all_friends($uid,$cid) {
1444 $r = q("SELECT count(*) as `total`
1445 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1446 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1447 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1452 if (dbm::is_result($r))
1453 return $r[0]['total'];
1459 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1461 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1463 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1464 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1465 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1466 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1467 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1480 function suggestion_query($uid, $start = 0, $limit = 80) {
1486 // Uncommented because the result of the queries are to big to store it in the cache.
1487 // We need to decide if we want to change the db column type or if we want to delete it.
1488 // $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1489 // if (!is_null($list)) {
1493 $network = array(NETWORK_DFRN);
1495 if (get_config('system','diaspora_enabled'))
1496 $network[] = NETWORK_DIASPORA;
1498 if (!get_config('system','ostatus_disabled'))
1499 $network[] = NETWORK_OSTATUS;
1501 $sql_network = implode("', '", $network);
1502 $sql_network = "'".$sql_network."'";
1504 /// @todo This query is really slow
1505 // By now we cache the data for five minutes
1506 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1507 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1508 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1509 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1510 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1511 AND `gcontact`.`updated` >= '%s'
1512 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1513 AND `gcontact`.`network` IN (%s)
1514 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1525 if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1526 // Uncommented because the result of the queries are to big to store it in the cache.
1527 // We need to decide if we want to change the db column type or if we want to delete it.
1528 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1533 $r2 = q("SELECT gcontact.* FROM gcontact
1534 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1535 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1536 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1537 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1538 AND `gcontact`.`updated` >= '%s'
1539 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1540 AND `gcontact`.`network` IN (%s)
1541 ORDER BY rand() LIMIT %d, %d",
1552 foreach ($r2 AS $suggestion)
1553 $list[$suggestion["nurl"]] = $suggestion;
1555 foreach ($r AS $suggestion)
1556 $list[$suggestion["nurl"]] = $suggestion;
1558 while (sizeof($list) > ($limit))
1561 // Uncommented because the result of the queries are to big to store it in the cache.
1562 // We need to decide if we want to change the db column type or if we want to delete it.
1563 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1567 function update_suggestions() {
1573 /// @TODO Check if it is really neccessary to poll the own server
1574 poco_load(0,0,0,App::get_baseurl() . '/poco');
1576 $done[] = App::get_baseurl() . '/poco';
1578 if (strlen(get_config('system','directory'))) {
1579 $x = fetch_url(get_server()."/pubsites");
1581 $j = json_decode($x);
1583 foreach ($j->entries as $entry) {
1585 poco_check_server($entry->url);
1587 $url = $entry->url . '/poco';
1588 if (! in_array($url,$done)) {
1589 poco_load(0,0,0,$entry->url . '/poco');
1596 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1597 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1598 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1601 if (dbm::is_result($r)) {
1602 foreach ($r as $rr) {
1603 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1604 if(! in_array($base,$done))
1605 poco_load(0,0,0,$base);
1611 * @brief Fetch server list from remote servers and adds them when they are new.
1613 * @param string $poco URL to the POCO endpoint
1615 function poco_fetch_serverlist($poco) {
1616 $serverret = z_fetch_url($poco."/@server");
1617 if (!$serverret["success"]) {
1620 $serverlist = json_decode($serverret['body']);
1622 if (!is_array($serverlist)) {
1626 foreach ($serverlist AS $server) {
1627 $server_url = str_replace("/index.php", "", $server->url);
1629 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1630 if (!dbm::is_result($r)) {
1631 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1632 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($server_url));
1637 function poco_discover_federation() {
1638 $last = get_config('poco','last_federation_discovery');
1641 $next = $last + (24 * 60 * 60);
1646 // Discover Friendica, Hubzilla and Diaspora servers
1647 $serverdata = fetch_url("http://the-federation.info/pods.json");
1650 $servers = json_decode($serverdata);
1652 foreach ($servers->pods AS $server) {
1653 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode("https://".$server->host));
1657 // Disvover Mastodon servers
1658 if (!Config::get('system','ostatus_disabled')) {
1659 $serverdata = fetch_url("https://instances.mastodon.xyz/instances.json");
1662 $servers = json_decode($serverdata);
1664 foreach ($servers AS $server) {
1665 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1666 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($url));
1671 // Currently disabled, since the service isn't available anymore.
1672 // It is not removed since I hope that there will be a successor.
1673 // Discover GNU Social Servers.
1674 //if (!get_config('system','ostatus_disabled')) {
1675 // $serverdata = "http://gstools.org/api/get_open_instances/";
1677 // $result = z_fetch_url($serverdata);
1678 // if ($result["success"]) {
1679 // $servers = json_decode($result["body"]);
1681 // foreach($servers->data AS $server)
1682 // poco_check_server($server->instance_address);
1686 set_config('poco','last_federation_discovery', time());
1689 function poco_discover_single_server($id) {
1690 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1691 if (!dbm::is_result($r)) {
1697 // Discover new servers out there (Works from Friendica version 3.5.2)
1698 poco_fetch_serverlist($server["poco"]);
1700 // Fetch all users from the other server
1701 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1703 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1705 $retdata = z_fetch_url($url);
1706 if ($retdata["success"]) {
1707 $data = json_decode($retdata["body"]);
1709 poco_discover_server($data, 2);
1711 if (get_config('system','poco_discovery') > 1) {
1713 $timeframe = get_config('system','poco_discovery_since');
1714 if ($timeframe == 0) {
1718 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1720 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1721 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1725 $retdata = z_fetch_url($url);
1726 if ($retdata["success"]) {
1727 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1728 $success = poco_discover_server(json_decode($retdata["body"]));
1731 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1732 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1733 poco_discover_server_users($data, $server);
1737 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1741 // If the server hadn't replied correctly, then force a sanity check
1742 poco_check_server($server["url"], $server["network"], true);
1744 // If we couldn't reach the server, we will try it some time later
1745 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1751 function poco_discover($complete = false) {
1753 // Update the server list
1754 poco_discover_federation();
1758 $requery_days = intval(get_config("system", "poco_requery_days"));
1760 if ($requery_days == 0) {
1763 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1765 $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));
1766 if (dbm::is_result($r)) {
1767 foreach ($r AS $server) {
1769 if (!poco_check_server($server["url"], $server["network"])) {
1770 // The server is not reachable? Okay, then we will try it later
1771 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1775 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1776 proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server_directory", intval($server['id']));
1778 if (!$complete AND (--$no_of_queries == 0)) {
1785 function poco_discover_server_users($data, $server) {
1787 if (!isset($data->entry))
1790 foreach ($data->entry AS $entry) {
1792 if (isset($entry->urls)) {
1793 foreach($entry->urls as $url)
1794 if ($url->type == 'profile') {
1795 $profile_url = $url->value;
1796 $urlparts = parse_url($profile_url);
1797 $username = end(explode("/", $urlparts["path"]));
1800 if ($username != "") {
1801 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1803 // Fetch all contacts from a given user from the other server
1804 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1806 $retdata = z_fetch_url($url);
1807 if ($retdata["success"])
1808 poco_discover_server(json_decode($retdata["body"]), 3);
1813 function poco_discover_server($data, $default_generation = 0) {
1815 if (!isset($data->entry) OR !count($data->entry))
1820 foreach ($data->entry AS $entry) {
1822 $profile_photo = '';
1826 $updated = NULL_DATE;
1832 $generation = $default_generation;
1834 $name = $entry->displayName;
1836 if (isset($entry->urls)) {
1837 foreach($entry->urls as $url) {
1838 if ($url->type == 'profile') {
1839 $profile_url = $url->value;
1842 if ($url->type == 'webfinger') {
1843 $connect_url = str_replace('acct:' , '', $url->value);
1849 if (isset($entry->photos)) {
1850 foreach ($entry->photos as $photo) {
1851 if ($photo->type == 'profile') {
1852 $profile_photo = $photo->value;
1858 if (isset($entry->updated)) {
1859 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1862 if(isset($entry->network)) {
1863 $network = $entry->network;
1866 if(isset($entry->currentLocation)) {
1867 $location = $entry->currentLocation;
1870 if(isset($entry->aboutMe)) {
1871 $about = html2bbcode($entry->aboutMe);
1874 if(isset($entry->gender)) {
1875 $gender = $entry->gender;
1878 if(isset($entry->generation) AND ($entry->generation > 0)) {
1879 $generation = ++$entry->generation;
1882 if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
1883 $contact_type = $entry->contactType;
1886 if(isset($entry->tags)) {
1887 foreach ($entry->tags as $tag) {
1888 $keywords = implode(", ", $tag);
1892 if ($generation > 0) {
1895 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1897 $gcontact = array("url" => $profile_url,
1899 "network" => $network,
1900 "photo" => $profile_photo,
1902 "location" => $location,
1903 "gender" => $gender,
1904 "keywords" => $keywords,
1905 "connect" => $connect_url,
1906 "updated" => $updated,
1907 "contact-type" => $contact_type,
1908 "generation" => $generation);
1911 $gcontact = sanitize_gcontact($gcontact);
1912 update_gcontact($gcontact);
1913 } catch (Exception $e) {
1914 logger($e->getMessage(), LOGGER_DEBUG);
1917 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1924 * @brief Removes unwanted parts from a contact url
1926 * @param string $url Contact url
1927 * @return string Contact url with the wanted parts
1929 function clean_contact_url($url) {
1930 $parts = parse_url($url);
1932 if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1935 $new_url = $parts["scheme"]."://".$parts["host"];
1937 if (isset($parts["port"]))
1938 $new_url .= ":".$parts["port"];
1940 if (isset($parts["path"]))
1941 $new_url .= $parts["path"];
1943 if ($new_url != $url)
1944 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1950 * @brief Replace alternate OStatus user format with the primary one
1952 * @param arr $contact contact array (called by reference)
1954 function fix_alternate_contact_address(&$contact) {
1955 if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1956 $data = probe_url($contact["url"]);
1957 if ($contact["network"] == NETWORK_OSTATUS) {
1958 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1959 $contact["url"] = $data["url"];
1960 $contact["addr"] = $data["addr"];
1961 $contact["alias"] = $data["alias"];
1962 $contact["server_url"] = $data["baseurl"];
1968 * @brief Fetch the gcontact id, add an entry if not existed
1970 * @param arr $contact contact array
1971 * @return bool|int Returns false if not found, integer if contact was found
1973 function get_gcontact_id($contact) {
1978 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1979 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1983 if ($contact["network"] == NETWORK_STATUSNET)
1984 $contact["network"] = NETWORK_OSTATUS;
1986 // All new contacts are hidden by default
1987 if (!isset($contact["hide"]))
1988 $contact["hide"] = true;
1990 // Replace alternate OStatus user format with the primary one
1991 fix_alternate_contact_address($contact);
1993 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1994 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1995 $contact["url"] = clean_contact_url($contact["url"]);
1997 $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
1998 dbesc(normalise_link($contact["url"])));
2001 $gcontact_id = $r[0]["id"];
2003 // Update every 90 days
2004 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
2005 $last_failure_str = $r[0]["last_failure"];
2006 $last_failure = strtotime($r[0]["last_failure"]);
2007 $last_contact_str = $r[0]["last_contact"];
2008 $last_contact = strtotime($r[0]["last_contact"]);
2009 $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
2012 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
2013 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
2014 dbesc($contact["name"]),
2015 dbesc($contact["nick"]),
2016 dbesc($contact["addr"]),
2017 dbesc($contact["network"]),
2018 dbesc($contact["url"]),
2019 dbesc(normalise_link($contact["url"])),
2020 dbesc($contact["photo"]),
2021 dbesc(datetime_convert()),
2022 dbesc(datetime_convert()),
2023 dbesc($contact["location"]),
2024 dbesc($contact["about"]),
2025 intval($contact["hide"]),
2026 intval($contact["generation"])
2029 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
2030 dbesc(normalise_link($contact["url"])));
2033 $gcontact_id = $r[0]["id"];
2035 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
2040 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
2041 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
2044 if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
2045 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
2046 dbesc(normalise_link($contact["url"])),
2047 intval($gcontact_id));
2049 return $gcontact_id;
2053 * @brief Updates the gcontact table from a given array
2055 * @param arr $contact contact array
2056 * @return bool|int Returns false if not found, integer if contact was found
2058 function update_gcontact($contact) {
2060 // Check for invalid "contact-type" value
2061 if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
2062 $contact['contact-type'] = 0;
2065 /// @todo update contact table as well
2067 $gcontact_id = get_gcontact_id($contact);
2072 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
2073 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
2074 FROM `gcontact` WHERE `id` = %d LIMIT 1",
2075 intval($gcontact_id));
2077 // Get all field names
2079 foreach ($r[0] AS $field => $data)
2080 $fields[$field] = $data;
2082 unset($fields["url"]);
2083 unset($fields["updated"]);
2084 unset($fields["hide"]);
2086 // Bugfix: We had an error in the storing of keywords which lead to the "0"
2087 // This value is still transmitted via poco.
2088 if ($contact["keywords"] == "0")
2089 unset($contact["keywords"]);
2091 if ($r[0]["keywords"] == "0")
2092 $r[0]["keywords"] = "";
2094 // assign all unassigned fields from the database entry
2095 foreach ($fields AS $field => $data)
2096 if (!isset($contact[$field]) OR ($contact[$field] == ""))
2097 $contact[$field] = $r[0][$field];
2099 if (!isset($contact["hide"]))
2100 $contact["hide"] = $r[0]["hide"];
2102 $fields["hide"] = $r[0]["hide"];
2104 if ($contact["network"] == NETWORK_STATUSNET)
2105 $contact["network"] = NETWORK_OSTATUS;
2107 // Replace alternate OStatus user format with the primary one
2108 fix_alternate_contact_address($contact);
2110 if (!isset($contact["updated"]))
2111 $contact["updated"] = dbm::date();
2113 if ($contact["server_url"] == "") {
2114 $server_url = $contact["url"];
2116 $server_url = matching_url($server_url, $contact["alias"]);
2117 if ($server_url != "")
2118 $contact["server_url"] = $server_url;
2120 $server_url = matching_url($server_url, $contact["photo"]);
2121 if ($server_url != "")
2122 $contact["server_url"] = $server_url;
2124 $server_url = matching_url($server_url, $contact["notify"]);
2125 if ($server_url != "")
2126 $contact["server_url"] = $server_url;
2128 $contact["server_url"] = normalise_link($contact["server_url"]);
2130 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
2131 $hostname = str_replace("http://", "", $contact["server_url"]);
2132 $contact["addr"] = $contact["nick"]."@".$hostname;
2135 // Check if any field changed
2137 unset($fields["generation"]);
2139 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
2140 foreach ($fields AS $field => $data)
2141 if ($contact[$field] != $r[0][$field]) {
2142 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
2146 if ($contact["generation"] < $r[0]["generation"]) {
2147 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
2153 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
2155 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
2156 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
2157 `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
2158 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
2159 `server_url` = '%s', `connect` = '%s'
2160 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
2161 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
2162 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
2163 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
2164 intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
2165 dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
2166 dbesc($contact["about"]), intval($contact["generation"]), dbesc(dbm::date($contact["updated"])),
2167 dbesc($contact["server_url"]), dbesc($contact["connect"]),
2168 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
2171 // Now update the contact entry with the user id "0" as well.
2172 // This is used for the shadow copies of public items.
2173 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
2174 dbesc(normalise_link($contact["url"])));
2177 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
2179 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
2181 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
2182 `network` = '%s', `bd` = '%s', `gender` = '%s',
2183 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
2184 `url` = '%s', `location` = '%s', `about` = '%s'
2186 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
2187 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
2188 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
2189 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
2190 intval($r[0]["id"]));
2194 return $gcontact_id;
2198 * @brief Updates the gcontact entry from probe
2200 * @param str $url profile link
2202 function update_gcontact_from_probe($url) {
2203 $data = probe_url($url);
2205 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
2206 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
2210 $data["server_url"] = $data["baseurl"];
2212 update_gcontact($data);
2216 * @brief Update the gcontact entry for a given user id
2218 * @param int $uid User ID
2220 function update_gcontact_for_user($uid) {
2221 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
2222 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
2223 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
2224 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
2225 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
2227 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
2228 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
2229 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
2232 $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
2233 "country-name" => $r[0]["country-name"]));
2235 // The "addr" field was added in 3.4.3 so it can be empty for older users
2236 if ($r[0]["addr"] != "")
2237 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
2239 $addr = $r[0]["addr"];
2241 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
2242 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
2243 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
2244 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
2245 "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
2246 "nick" => $r[0]["nickname"], "addr" => $addr,
2247 "connect" => $addr, "server_url" => App::get_baseurl(),
2248 "generation" => 1, "network" => NETWORK_DFRN);
2250 update_gcontact($gcontact);
2254 * @brief Fetches users of given GNU Social server
2256 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
2258 * @param str $server Server address
2260 function gs_fetch_users($server) {
2262 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
2264 $url = $server."/main/statistics";
2266 $result = z_fetch_url($url);
2267 if (!$result["success"])
2270 $statistics = json_decode($result["body"]);
2272 if (is_object($statistics->config)) {
2273 if ($statistics->config->instance_with_ssl)
2274 $server = "https://";
2276 $server = "http://";
2278 $server .= $statistics->config->instance_address;
2280 $hostname = $statistics->config->instance_address;
2282 if ($statistics->instance_with_ssl)
2283 $server = "https://";
2285 $server = "http://";
2287 $server .= $statistics->instance_address;
2289 $hostname = $statistics->instance_address;
2292 if (is_object($statistics->users))
2293 foreach ($statistics->users AS $nick => $user) {
2294 $profile_url = $server."/".$user->nickname;
2296 $contact = array("url" => $profile_url,
2297 "name" => $user->fullname,
2298 "addr" => $user->nickname."@".$hostname,
2299 "nick" => $user->nickname,
2300 "about" => $user->bio,
2301 "network" => NETWORK_OSTATUS,
2302 "photo" => App::get_baseurl()."/images/person-175.jpg");
2303 get_gcontact_id($contact);
2308 * @brief Asking GNU Social server on a regular base for their user data
2311 function gs_discover() {
2313 $requery_days = intval(get_config("system", "poco_requery_days"));
2315 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
2317 $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",
2318 dbesc(NETWORK_OSTATUS), dbesc($last_update));
2323 foreach ($r AS $server) {
2324 gs_fetch_users($server["url"]);
2325 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
2330 * @brief Returns a list of all known servers
2331 * @return array List of server urls
2333 function poco_serverlist() {
2334 $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
2335 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
2336 ORDER BY `last_contact`
2338 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
2339 if (!dbm::is_result($r)) {