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\System;
12 use Friendica\Core\Config;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBM;
15 use Friendica\Network\Probe;
17 require_once 'include/datetime.php';
18 require_once 'include/network.php';
19 require_once 'include/html2bbcode.php';
20 require_once 'include/Contact.php';
21 require_once 'include/Photo.php';
24 * @brief Fetch POCO data
26 * @param integer $cid Contact ID
27 * @param integer $uid User ID
28 * @param integer $zcid Global Contact ID
29 * @param integer $url POCO address that should be polled
31 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
32 * and add the entries to the gcontact (Global Contact) table, or update existing entries
33 * if anything (name or photo) has changed.
34 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
36 * Once the global contact is stored add (if necessary) the contact linkage which associates
37 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
38 * pointing to the same global contact id.
41 function poco_load($cid, $uid = 0, $zcid = 0, $url = null) {
42 // Call the function "poco_load_worker" via the worker
43 Worker::add(PRIORITY_LOW, "discover_poco", "poco_load", (int)$cid, (int)$uid, (int)$zcid, $url);
47 * @brief Fetch POCO data from the worker
49 * @param integer $cid Contact ID
50 * @param integer $uid User ID
51 * @param integer $zcid Global Contact ID
52 * @param integer $url POCO address that should be polled
55 function poco_load_worker($cid, $uid, $zcid, $url) {
59 if ((! $url) || (! $uid)) {
60 $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
63 if (DBM::is_result($r)) {
77 $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') ;
79 logger('poco_load: ' . $url, LOGGER_DEBUG);
83 logger('poco_load: returns ' . $s, LOGGER_DATA);
85 logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
87 if (($a->get_curl_code() > 299) || (! $s)) {
93 logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
95 if (! isset($j->entry)) {
100 foreach ($j->entry as $entry) {
108 $updated = NULL_DATE;
116 $name = $entry->displayName;
118 if (isset($entry->urls)) {
119 foreach ($entry->urls as $url) {
120 if ($url->type == 'profile') {
121 $profile_url = $url->value;
124 if ($url->type == 'webfinger') {
125 $connect_url = str_replace('acct:' , '', $url->value);
130 if (isset($entry->photos)) {
131 foreach ($entry->photos as $photo) {
132 if ($photo->type == 'profile') {
133 $profile_photo = $photo->value;
139 if (isset($entry->updated)) {
140 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
143 if (isset($entry->network)) {
144 $network = $entry->network;
147 if (isset($entry->currentLocation)) {
148 $location = $entry->currentLocation;
151 if (isset($entry->aboutMe)) {
152 $about = html2bbcode($entry->aboutMe);
155 if (isset($entry->gender)) {
156 $gender = $entry->gender;
159 if (isset($entry->generation) && ($entry->generation > 0)) {
160 $generation = ++$entry->generation;
163 if (isset($entry->tags)) {
164 foreach ($entry->tags as $tag) {
165 $keywords = implode(", ", $tag);
169 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
170 $contact_type = $entry->contactType;
173 $gcontact = array("url" => $profile_url,
175 "network" => $network,
176 "photo" => $profile_photo,
178 "location" => $location,
180 "keywords" => $keywords,
181 "connect" => $connect_url,
182 "updated" => $updated,
183 "contact-type" => $contact_type,
184 "generation" => $generation);
187 $gcontact = sanitize_gcontact($gcontact);
188 $gcid = update_gcontact($gcontact);
190 link_gcontact($gcid, $uid, $cid, $zcid);
191 } catch (Exception $e) {
192 logger($e->getMessage(), LOGGER_DEBUG);
195 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
197 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
205 * @brief Sanitize the given gcontact data
207 * @param array $gcontact array with gcontact data
212 * 1: Profiles on this server
213 * 2: Contacts of profiles on this server
214 * 3: Contacts of contacts of profiles on this server
218 function sanitize_gcontact($gcontact) {
220 if ($gcontact['url'] == "") {
221 throw new Exception('URL is empty');
224 $urlparts = parse_url($gcontact['url']);
225 if (!isset($urlparts["scheme"])) {
226 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
229 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
230 "identi.ca", "alpha.app.net"))) {
231 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
234 // Don't store the statusnet connector as network
235 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
236 if ($gcontact['network'] == NETWORK_STATUSNET) {
237 $gcontact['network'] = "";
240 // Assure that there are no parameter fragments in the profile url
241 if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
242 $gcontact['url'] = clean_contact_url($gcontact['url']);
245 $alternate = poco_alternate_ostatus_url($gcontact['url']);
247 // The global contacts should contain the original picture, not the cached one
248 if (($gcontact['generation'] != 1) && stristr(normalise_link($gcontact['photo']), normalise_link(System::baseUrl()."/photo/"))) {
249 $gcontact['photo'] = "";
252 if (!isset($gcontact['network'])) {
253 $r = q("SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
254 dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
256 if (DBM::is_result($r)) {
257 $gcontact['network'] = $r[0]["network"];
260 if (($gcontact['network'] == "") || ($gcontact['network'] == NETWORK_OSTATUS)) {
261 $r = q("SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
262 dbesc($gcontact['url']), dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
264 if (DBM::is_result($r)) {
265 $gcontact['network'] = $r[0]["network"];
270 $gcontact['server_url'] = '';
271 $gcontact['network'] = '';
273 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
274 dbesc(normalise_link($gcontact['url']))
277 if (DBM::is_result($x)) {
278 if (!isset($gcontact['network']) && ($x[0]["network"] != NETWORK_STATUSNET)) {
279 $gcontact['network'] = $x[0]["network"];
281 if ($gcontact['updated'] <= NULL_DATE) {
282 $gcontact['updated'] = $x[0]["updated"];
284 if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
285 $gcontact['server_url'] = $x[0]["server_url"];
287 if (!isset($gcontact['addr'])) {
288 $gcontact['addr'] = $x[0]["addr"];
292 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
293 && poco_reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)) {
294 $data = Probe::uri($gcontact['url']);
296 if ($data["network"] == NETWORK_PHANTOM) {
297 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
300 $orig_profile = $gcontact['url'];
302 $gcontact["server_url"] = $data["baseurl"];
304 $gcontact = array_merge($gcontact, $data);
306 if ($alternate && ($gcontact['network'] == NETWORK_OSTATUS)) {
307 // Delete the old entry - if it exists
308 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
309 if (DBM::is_result($r)) {
310 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
311 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
316 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
317 throw new Exception('No name and photo for URL '.$gcontact['url']);
320 if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
321 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
324 if (!isset($gcontact['server_url'])) {
325 // We check the server url to be sure that it is a real one
326 $server_url = poco_detect_server($gcontact['url']);
328 // We are now sure that it is a correct URL. So we use it in the future
329 if ($server_url != "") {
330 $gcontact['server_url'] = $server_url;
334 // The server URL doesn't seem to be valid, so we don't store it.
335 if (!poco_check_server($gcontact['server_url'], $gcontact['network'])) {
336 $gcontact['server_url'] = "";
343 * @brief Link the gcontact entry with user, contact and global contact
345 * @param integer $gcid Global contact ID
346 * @param integer $cid Contact ID
347 * @param integer $uid User ID
348 * @param integer $zcid Global Contact ID
351 function link_gcontact($gcid, $uid = 0, $cid = 0, $zcid = 0) {
357 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
364 if (!DBM::is_result($r)) {
365 q("INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
370 dbesc(datetime_convert())
373 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
374 dbesc(datetime_convert()),
383 function poco_reachable($profile, $server = "", $network = "", $force = false) {
386 $server = poco_detect_server($profile);
393 return poco_check_server($server, $network, $force);
396 function poco_detect_server($profile) {
398 // Try to detect the server path based upon some known standard paths
401 if ($server_url == "") {
402 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
403 if ($friendica != $profile) {
404 $server_url = $friendica;
405 $network = NETWORK_DFRN;
409 if ($server_url == "") {
410 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
411 if ($diaspora != $profile) {
412 $server_url = $diaspora;
413 $network = NETWORK_DIASPORA;
417 if ($server_url == "") {
418 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
419 if ($red != $profile) {
421 $network = NETWORK_DIASPORA;
426 if ($server_url == "") {
427 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
428 if ($mastodon != $profile) {
429 $server_url = $mastodon;
430 $network = NETWORK_OSTATUS;
434 // Numeric OStatus variant
435 if ($server_url == "") {
436 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
437 if ($ostatus != $profile) {
438 $server_url = $ostatus;
439 $network = NETWORK_OSTATUS;
444 if ($server_url == "") {
445 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
446 if ($base != $profile) {
448 $network = NETWORK_PHANTOM;
452 if ($server_url == "") {
456 $r = q("SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
457 dbesc(normalise_link($server_url)));
458 if (DBM::is_result($r)) {
462 // Fetch the host-meta to check if this really is a server
463 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
464 if (!$serverret["success"]) {
471 function poco_alternate_ostatus_url($url) {
472 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
475 function poco_last_updated($profile, $force = false) {
477 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
478 dbesc(normalise_link($profile)));
480 if (!DBM::is_result($gcontacts)) {
484 $contact = array("url" => $profile);
486 if ($gcontacts[0]["created"] <= NULL_DATE) {
487 $contact['created'] = datetime_convert();
491 $server_url = normalise_link(poco_detect_server($profile));
494 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
495 $server_url = $gcontacts[0]["server_url"];
498 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
499 $server_url = normalise_link(poco_detect_server($profile));
502 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
503 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
507 if ($server_url != "") {
508 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
510 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
511 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
514 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
517 $contact['server_url'] = $server_url;
520 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
521 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
522 dbesc(normalise_link($server_url)));
525 $contact['network'] = $server[0]["network"];
531 // noscrape is really fast so we don't cache the call.
532 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
534 // Use noscrape if possible
535 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
538 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
540 if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
542 $noscrape = json_decode($noscraperet["body"], true);
544 if (is_array($noscrape)) {
545 $contact["network"] = $server[0]["network"];
547 if (isset($noscrape["fn"])) {
548 $contact["name"] = $noscrape["fn"];
550 if (isset($noscrape["comm"])) {
551 $contact["community"] = $noscrape["comm"];
553 if (isset($noscrape["tags"])) {
554 $keywords = implode(" ", $noscrape["tags"]);
555 if ($keywords != "") {
556 $contact["keywords"] = $keywords;
560 $location = formatted_location($noscrape);
562 $contact["location"] = $location;
564 if (isset($noscrape["dfrn-notify"])) {
565 $contact["notify"] = $noscrape["dfrn-notify"];
567 // Remove all fields that are not present in the gcontact table
568 unset($noscrape["fn"]);
569 unset($noscrape["key"]);
570 unset($noscrape["homepage"]);
571 unset($noscrape["comm"]);
572 unset($noscrape["tags"]);
573 unset($noscrape["locality"]);
574 unset($noscrape["region"]);
575 unset($noscrape["country-name"]);
576 unset($noscrape["contacts"]);
577 unset($noscrape["dfrn-request"]);
578 unset($noscrape["dfrn-confirm"]);
579 unset($noscrape["dfrn-notify"]);
580 unset($noscrape["dfrn-poll"]);
582 // Set the date of the last contact
583 /// @todo By now the function "update_gcontact" doesn't work with this field
584 //$contact["last_contact"] = datetime_convert();
586 $contact = array_merge($contact, $noscrape);
588 update_gcontact($contact);
590 if (trim($noscrape["updated"]) != "") {
591 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
592 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
594 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
596 return $noscrape["updated"];
603 // If we only can poll the feed, then we only do this once a while
604 if (!$force && !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
605 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
607 update_gcontact($contact);
608 return $gcontacts[0]["updated"];
611 $data = Probe::uri($profile);
613 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
614 // Then check the other link and delete this one
615 if (($data["network"] == NETWORK_OSTATUS) && poco_alternate_ostatus_url($profile) &&
616 (normalise_link($profile) == normalise_link($data["alias"])) &&
617 (normalise_link($profile) != normalise_link($data["url"]))) {
619 // Delete the old entry
620 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
621 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
623 $gcontact = array_merge($gcontacts[0], $data);
625 $gcontact["server_url"] = $data["baseurl"];
628 $gcontact = sanitize_gcontact($gcontact);
629 update_gcontact($gcontact);
631 poco_last_updated($data["url"], $force);
632 } catch (Exception $e) {
633 logger($e->getMessage(), LOGGER_DEBUG);
636 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
640 if (($data["poll"] == "") || (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
641 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
642 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
644 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
648 $contact = array_merge($contact, $data);
650 $contact["server_url"] = $data["baseurl"];
652 update_gcontact($contact);
654 $feedret = z_fetch_url($data["poll"]);
656 if (!$feedret["success"]) {
657 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
658 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
660 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
664 $doc = new DOMDocument();
665 @$doc->loadXML($feedret["body"]);
667 $xpath = new DomXPath($doc);
668 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
670 $entries = $xpath->query('/atom:feed/atom:entry');
674 foreach ($entries as $entry) {
675 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
676 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
678 if ($last_updated < $published)
679 $last_updated = $published;
681 if ($last_updated < $updated)
682 $last_updated = $updated;
685 // Maybe there aren't any entries. Then check if it is a valid feed
686 if ($last_updated == "") {
687 if ($xpath->query('/atom:feed')->length > 0) {
688 $last_updated = NULL_DATE;
691 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
692 dbesc(DBM::date($last_updated)), dbesc(DBM::date()), dbesc(normalise_link($profile)));
694 if (($gcontacts[0]["generation"] == 0)) {
695 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
696 dbesc(normalise_link($profile)));
699 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
701 return($last_updated);
704 function poco_do_update($created, $updated, $last_failure, $last_contact) {
705 $now = strtotime(datetime_convert());
707 if ($updated > $last_contact) {
708 $contact_time = strtotime($updated);
710 $contact_time = strtotime($last_contact);
713 $failure_time = strtotime($last_failure);
714 $created_time = strtotime($created);
716 // If there is no "created" time then use the current time
717 if ($created_time <= 0) {
718 $created_time = $now;
721 // If the last contact was less than 24 hours then don't update
722 if (($now - $contact_time) < (60 * 60 * 24)) {
726 // If the last failure was less than 24 hours then don't update
727 if (($now - $failure_time) < (60 * 60 * 24)) {
731 // If the last contact was less than a week ago and the last failure is older than a week then don't update
732 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
735 // 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
736 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
740 // 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
741 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
748 function poco_to_boolean($val) {
749 if (($val == "true") || ($val == 1)) {
751 } elseif (($val == "false") || ($val == 0)) {
759 * @brief Detect server type (Hubzilla or Friendica) via the poco data
761 * @param object $data POCO data
762 * @return array Server data
764 function poco_detect_poco_data($data) {
767 if (!isset($data->entry)) {
771 if (count($data->entry) == 0) {
775 if (!isset($data->entry[0]->urls)) {
779 if (count($data->entry[0]->urls) == 0) {
783 foreach ($data->entry[0]->urls as $url) {
784 if ($url->type == 'zot') {
786 $server["platform"] = 'Hubzilla';
787 $server["network"] = NETWORK_DIASPORA;
795 * @brief Detect server type by using the nodeinfo data
797 * @param string $server_url address of the server
798 * @return array Server data
800 function poco_fetch_nodeinfo($server_url) {
801 $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
802 if (!$serverret["success"]) {
806 $nodeinfo = json_decode($serverret['body']);
808 if (!is_object($nodeinfo)) {
812 if (!is_array($nodeinfo->links)) {
818 foreach ($nodeinfo->links as $link) {
819 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
820 $nodeinfo_url = $link->href;
824 if ($nodeinfo_url == '') {
828 $serverret = z_fetch_url($nodeinfo_url);
829 if (!$serverret["success"]) {
833 $nodeinfo = json_decode($serverret['body']);
835 if (!is_object($nodeinfo)) {
841 $server['register_policy'] = REGISTER_CLOSED;
843 if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
844 $server['register_policy'] = REGISTER_OPEN;
847 if (is_object($nodeinfo->software)) {
848 if (isset($nodeinfo->software->name)) {
849 $server['platform'] = $nodeinfo->software->name;
852 if (isset($nodeinfo->software->version)) {
853 $server['version'] = $nodeinfo->software->version;
854 // Version numbers on Nodeinfo are presented with additional info, e.g.:
855 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
856 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
860 if (is_object($nodeinfo->metadata)) {
861 if (isset($nodeinfo->metadata->nodeName)) {
862 $server['site_name'] = $nodeinfo->metadata->nodeName;
870 if (is_array($nodeinfo->protocols->inbound)) {
871 foreach ($nodeinfo->protocols->inbound as $inbound) {
872 if ($inbound == 'diaspora') {
875 if ($inbound == 'friendica') {
878 if ($inbound == 'gnusocial') {
885 $server['network'] = NETWORK_OSTATUS;
888 $server['network'] = NETWORK_DIASPORA;
891 $server['network'] = NETWORK_DFRN;
902 * @brief Detect server type (Hubzilla or Friendica) via the front page body
904 * @param string $body Front page of the server
905 * @return array Server data
907 function poco_detect_server_type($body) {
910 $doc = new DOMDocument();
911 @$doc->loadHTML($body);
912 $xpath = new DomXPath($doc);
914 $list = $xpath->query("//meta[@name]");
916 foreach ($list as $node) {
918 if ($node->attributes->length) {
919 foreach ($node->attributes as $attribute) {
920 $attr[$attribute->name] = $attribute->value;
923 if ($attr['name'] == 'generator') {
924 $version_part = explode(" ", $attr['content']);
925 if (count($version_part) == 2) {
926 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
928 $server["platform"] = $version_part[0];
929 $server["version"] = $version_part[1];
930 $server["network"] = NETWORK_DFRN;
937 $list = $xpath->query("//meta[@property]");
939 foreach ($list as $node) {
941 if ($node->attributes->length) {
942 foreach ($node->attributes as $attribute) {
943 $attr[$attribute->name] = $attribute->value;
946 if ($attr['property'] == 'generator' && in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
948 $server["platform"] = $attr['content'];
949 $server["version"] = "";
950 $server["network"] = NETWORK_DIASPORA;
959 $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
963 function poco_check_server($server_url, $network = "", $force = false) {
965 // Unify the server address
966 $server_url = trim($server_url, "/");
967 $server_url = str_replace("/index.php", "", $server_url);
969 if ($server_url == "") {
973 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
974 if (DBM::is_result($servers)) {
976 if ($servers[0]["created"] <= NULL_DATE) {
977 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
978 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
980 $poco = $servers[0]["poco"];
981 $noscrape = $servers[0]["noscrape"];
983 if ($network == "") {
984 $network = $servers[0]["network"];
987 $last_contact = $servers[0]["last_contact"];
988 $last_failure = $servers[0]["last_failure"];
989 $version = $servers[0]["version"];
990 $platform = $servers[0]["platform"];
991 $site_name = $servers[0]["site_name"];
992 $info = $servers[0]["info"];
993 $register_policy = $servers[0]["register_policy"];
995 if (!$force && !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
996 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
997 return ($last_contact >= $last_failure);
1006 $register_policy = -1;
1008 $last_contact = NULL_DATE;
1009 $last_failure = NULL_DATE;
1011 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
1014 $possible_failure = false;
1015 $orig_last_failure = $last_failure;
1016 $orig_last_contact = $last_contact;
1018 // Check if the page is accessible via SSL.
1019 $orig_server_url = $server_url;
1020 $server_url = str_replace("http://", "https://", $server_url);
1022 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1023 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1025 // Quit if there is a timeout.
1026 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1027 if (DBM::is_result($servers) && ($orig_server_url == $server_url) &&
1028 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1029 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1030 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
1034 // Maybe the page is unencrypted only?
1035 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1036 if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
1037 $server_url = str_replace("https://", "http://", $server_url);
1039 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1040 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1042 // Quit if there is a timeout
1043 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1044 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1045 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
1049 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1052 if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
1053 // Workaround for bad configured servers (known nginx problem)
1054 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
1057 $possible_failure = true;
1060 // If the server has no possible failure we reset the cached data
1061 if (!$possible_failure) {
1066 $register_policy = -1;
1071 $serverret = z_fetch_url($server_url."/poco");
1072 if ($serverret["success"]) {
1073 $data = json_decode($serverret["body"]);
1074 if (isset($data->totalResults)) {
1075 $poco = $server_url."/poco";
1076 $server = poco_detect_poco_data($data);
1078 $platform = $server['platform'];
1079 $network = $server['network'];
1088 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1089 $serverret = z_fetch_url($server_url);
1091 if (!$serverret["success"] || ($serverret["body"] == "")) {
1094 $server = poco_detect_server_type($serverret["body"]);
1096 $platform = $server['platform'];
1097 $network = $server['network'];
1098 $version = $server['version'];
1099 $site_name = $server['site_name'];
1102 $lines = explode("\n",$serverret["header"]);
1103 if (count($lines)) {
1104 foreach($lines as $line) {
1105 $line = trim($line);
1106 if (stristr($line,'X-Diaspora-Version:')) {
1107 $platform = "Diaspora";
1108 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1109 $version = trim(str_replace("x-diaspora-version:", "", $version));
1110 $network = NETWORK_DIASPORA;
1111 $versionparts = explode("-", $version);
1112 $version = $versionparts[0];
1115 if (stristr($line,'Server: Mastodon')) {
1116 $platform = "Mastodon";
1117 $network = NETWORK_OSTATUS;
1124 if (!$failure && ($poco == "")) {
1125 // Test for Statusnet
1126 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1127 // The "not implemented" is a special treatment for really, really old Friendica versions
1128 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
1129 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1130 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1131 $platform = "StatusNet";
1132 // Remove junk that some GNU Social servers return
1133 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1134 $version = trim($version, '"');
1135 $network = NETWORK_OSTATUS;
1138 // Test for GNU Social
1139 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1140 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1141 ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1142 $platform = "GNU Social";
1143 // Remove junk that some GNU Social servers return
1144 $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1145 $version = trim($version, '"');
1146 $network = NETWORK_OSTATUS;
1149 // Test for Mastodon
1150 $orig_version = $version;
1151 $serverret = z_fetch_url($server_url."/api/v1/instance");
1152 if ($serverret["success"] && ($serverret["body"] != '')) {
1153 $data = json_decode($serverret["body"]);
1154 if (isset($data->version)) {
1155 $platform = "Mastodon";
1156 $version = $data->version;
1157 $site_name = $data->title;
1158 $info = $data->description;
1159 $network = NETWORK_OSTATUS;
1162 if (strstr($orig_version.$version, 'Pleroma')) {
1163 $platform = 'Pleroma';
1164 $version = trim(str_replace('Pleroma', '', $version));
1169 // Test for Hubzilla and Red
1170 $serverret = z_fetch_url($server_url."/siteinfo.json");
1171 if ($serverret["success"]) {
1172 $data = json_decode($serverret["body"]);
1173 if (isset($data->url)) {
1174 $platform = $data->platform;
1175 $version = $data->version;
1176 $network = NETWORK_DIASPORA;
1178 if (!empty($data->site_name)) {
1179 $site_name = $data->site_name;
1181 switch ($data->register_policy) {
1182 case "REGISTER_OPEN":
1183 $register_policy = REGISTER_OPEN;
1185 case "REGISTER_APPROVE":
1186 $register_policy = REGISTER_APPROVE;
1188 case "REGISTER_CLOSED":
1190 $register_policy = REGISTER_CLOSED;
1194 // Test for Hubzilla, Redmatrix or Friendica
1195 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1196 if ($serverret["success"]) {
1197 $data = json_decode($serverret["body"]);
1198 if (isset($data->site->server)) {
1199 if (isset($data->site->platform)) {
1200 $platform = $data->site->platform->PLATFORM_NAME;
1201 $version = $data->site->platform->STD_VERSION;
1202 $network = NETWORK_DIASPORA;
1204 if (isset($data->site->BlaBlaNet)) {
1205 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1206 $version = $data->site->BlaBlaNet->STD_VERSION;
1207 $network = NETWORK_DIASPORA;
1209 if (isset($data->site->hubzilla)) {
1210 $platform = $data->site->hubzilla->PLATFORM_NAME;
1211 $version = $data->site->hubzilla->RED_VERSION;
1212 $network = NETWORK_DIASPORA;
1214 if (isset($data->site->redmatrix)) {
1215 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1216 $platform = $data->site->redmatrix->PLATFORM_NAME;
1217 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1218 $platform = $data->site->redmatrix->RED_PLATFORM;
1221 $version = $data->site->redmatrix->RED_VERSION;
1222 $network = NETWORK_DIASPORA;
1224 if (isset($data->site->friendica)) {
1225 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1226 $version = $data->site->friendica->FRIENDICA_VERSION;
1227 $network = NETWORK_DFRN;
1230 $site_name = $data->site->name;
1232 $data->site->closed = poco_to_boolean($data->site->closed);
1233 $data->site->private = poco_to_boolean($data->site->private);
1234 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
1236 if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1237 $register_policy = REGISTER_APPROVE;
1238 } elseif (!$data->site->closed && !$data->site->private) {
1239 $register_policy = REGISTER_OPEN;
1241 $register_policy = REGISTER_CLOSED;
1248 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1250 $serverret = z_fetch_url($server_url."/statistics.json");
1251 if ($serverret["success"]) {
1252 $data = json_decode($serverret["body"]);
1253 if (isset($data->version)) {
1254 $version = $data->version;
1255 // Version numbers on statistics.json are presented with additional info, e.g.:
1256 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1257 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1260 if (!empty($data->name)) {
1261 $site_name = $data->name;
1264 if (!empty($data->network)) {
1265 $platform = $data->network;
1268 if ($platform == "Diaspora") {
1269 $network = NETWORK_DIASPORA;
1272 if ($data->registrations_open) {
1273 $register_policy = REGISTER_OPEN;
1275 $register_policy = REGISTER_CLOSED;
1280 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1282 $server = poco_fetch_nodeinfo($server_url);
1284 $register_policy = $server['register_policy'];
1286 if (isset($server['platform'])) {
1287 $platform = $server['platform'];
1290 if (isset($server['network'])) {
1291 $network = $server['network'];
1294 if (isset($server['version'])) {
1295 $version = $server['version'];
1298 if (isset($server['site_name'])) {
1299 $site_name = $server['site_name'];
1304 // Check for noscrape
1305 // Friendica servers could be detected as OStatus servers
1306 if (!$failure && in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1307 $serverret = z_fetch_url($server_url."/friendica/json");
1309 if (!$serverret["success"]) {
1310 $serverret = z_fetch_url($server_url."/friendika/json");
1313 if ($serverret["success"]) {
1314 $data = json_decode($serverret["body"]);
1316 if (isset($data->version)) {
1317 $network = NETWORK_DFRN;
1319 $noscrape = $data->no_scrape_url;
1320 $version = $data->version;
1321 $site_name = $data->site_name;
1322 $info = $data->info;
1323 $register_policy_str = $data->register_policy;
1324 $platform = $data->platform;
1326 switch ($register_policy_str) {
1327 case "REGISTER_CLOSED":
1328 $register_policy = REGISTER_CLOSED;
1330 case "REGISTER_APPROVE":
1331 $register_policy = REGISTER_APPROVE;
1333 case "REGISTER_OPEN":
1334 $register_policy = REGISTER_OPEN;
1341 if ($possible_failure && !$failure) {
1346 $last_contact = $orig_last_contact;
1347 $last_failure = datetime_convert();
1349 $last_contact = datetime_convert();
1350 $last_failure = $orig_last_failure;
1353 if (($last_contact <= $last_failure) && !$failure) {
1354 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1355 } elseif (($last_contact >= $last_failure) && $failure) {
1356 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1359 // Check again if the server exists
1360 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1362 $version = strip_tags($version);
1363 $site_name = strip_tags($site_name);
1364 $info = strip_tags($info);
1365 $platform = strip_tags($platform);
1368 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1369 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1374 intval($register_policy),
1379 dbesc($last_contact),
1380 dbesc($last_failure),
1381 dbesc(normalise_link($server_url))
1383 } elseif (!$failure) {
1384 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1385 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1387 dbesc(normalise_link($server_url)),
1391 intval($register_policy),
1396 dbesc(datetime_convert()),
1397 dbesc($last_contact),
1398 dbesc($last_failure),
1399 dbesc(datetime_convert())
1402 logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1407 function count_common_friends($uid, $cid) {
1409 $r = q("SELECT count(*) as `total`
1410 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1411 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1412 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1413 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1420 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1421 if (DBM::is_result($r)) {
1422 return $r[0]['total'];
1429 function common_friends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false) {
1432 $sql_extra = " order by rand() ";
1434 $sql_extra = " order by `gcontact`.`name` asc ";
1437 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1439 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1440 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1441 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1442 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1443 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1444 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1445 $sql_extra LIMIT %d, %d",
1454 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
1460 function count_common_friends_zcid($uid, $zcid) {
1462 $r = q("SELECT count(*) as `total`
1463 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1464 where `glink`.`zcid` = %d
1465 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1470 if (DBM::is_result($r)) {
1471 return $r[0]['total'];
1477 function common_friends_zcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false) {
1480 $sql_extra = " order by rand() ";
1482 $sql_extra = " order by `gcontact`.`name` asc ";
1485 $r = q("SELECT `gcontact`.*
1486 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1487 where `glink`.`zcid` = %d
1488 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1489 $sql_extra limit %d, %d",
1496 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
1502 function count_all_friends($uid, $cid) {
1504 $r = q("SELECT count(*) as `total`
1505 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1506 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1507 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1512 if (DBM::is_result($r)) {
1513 return $r[0]['total'];
1520 function all_friends($uid, $cid, $start = 0, $limit = 80) {
1522 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1524 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1525 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1526 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1527 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1528 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1536 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
1542 function suggestion_query($uid, $start = 0, $limit = 80) {
1549 * Uncommented because the result of the queries are to big to store it in the cache.
1550 * We need to decide if we want to change the db column type or if we want to delete it.
1552 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1553 //if (!is_null($list)) {
1557 $network = array(NETWORK_DFRN);
1559 if (Config::get('system','diaspora_enabled')) {
1560 $network[] = NETWORK_DIASPORA;
1563 if (!Config::get('system','ostatus_disabled')) {
1564 $network[] = NETWORK_OSTATUS;
1567 $sql_network = implode("', '", $network);
1568 $sql_network = "'".$sql_network."'";
1570 /// @todo This query is really slow
1571 // By now we cache the data for five minutes
1572 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1573 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1574 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1575 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1576 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1577 AND `gcontact`.`updated` >= '%s'
1578 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1579 AND `gcontact`.`network` IN (%s)
1580 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1591 if (DBM::is_result($r) && count($r) >= ($limit -1)) {
1593 * Uncommented because the result of the queries are to big to store it in the cache.
1594 * We need to decide if we want to change the db column type or if we want to delete it.
1596 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1601 $r2 = q("SELECT gcontact.* FROM gcontact
1602 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1603 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1604 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1605 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1606 AND `gcontact`.`updated` >= '%s'
1607 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1608 AND `gcontact`.`network` IN (%s)
1609 ORDER BY rand() LIMIT %d, %d",
1620 foreach ($r2 as $suggestion) {
1621 $list[$suggestion["nurl"]] = $suggestion;
1624 foreach ($r as $suggestion) {
1625 $list[$suggestion["nurl"]] = $suggestion;
1628 while (sizeof($list) > ($limit)) {
1633 * Uncommented because the result of the queries are to big to store it in the cache.
1634 * We need to decide if we want to change the db column type or if we want to delete it.
1636 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1640 function update_suggestions() {
1646 /// @TODO Check if it is really neccessary to poll the own server
1647 poco_load(0, 0, 0, System::baseUrl() . '/poco');
1649 $done[] = System::baseUrl() . '/poco';
1651 if (strlen(Config::get('system','directory'))) {
1652 $x = fetch_url(get_server()."/pubsites");
1654 $j = json_decode($x);
1656 foreach ($j->entries as $entry) {
1658 poco_check_server($entry->url);
1660 $url = $entry->url . '/poco';
1661 if (! in_array($url,$done)) {
1662 poco_load(0,0,0,$entry->url . '/poco');
1669 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1670 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1671 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1674 if (DBM::is_result($r)) {
1675 foreach ($r as $rr) {
1676 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1677 if (! in_array($base,$done)) {
1678 poco_load(0,0,0,$base);
1685 * @brief Fetch server list from remote servers and adds them when they are new.
1687 * @param string $poco URL to the POCO endpoint
1689 function poco_fetch_serverlist($poco) {
1690 $serverret = z_fetch_url($poco."/@server");
1691 if (!$serverret["success"]) {
1694 $serverlist = json_decode($serverret['body']);
1696 if (!is_array($serverlist)) {
1700 foreach ($serverlist as $server) {
1701 $server_url = str_replace("/index.php", "", $server->url);
1703 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1704 if (!DBM::is_result($r)) {
1705 logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1706 Worker::add(PRIORITY_LOW, "discover_poco", "server", $server_url);
1711 function poco_discover_federation() {
1712 $last = Config::get('poco','last_federation_discovery');
1715 $next = $last + (24 * 60 * 60);
1716 if ($next > time()) {
1721 // Discover Friendica, Hubzilla and Diaspora servers
1722 $serverdata = fetch_url("http://the-federation.info/pods.json");
1725 $servers = json_decode($serverdata);
1727 foreach ($servers->pods as $server) {
1728 Worker::add(PRIORITY_LOW, "discover_poco", "server", "https://".$server->host);
1732 // Disvover Mastodon servers
1733 if (!Config::get('system','ostatus_disabled')) {
1734 $serverdata = fetch_url("https://instances.mastodon.xyz/instances.json");
1737 $servers = json_decode($serverdata);
1739 foreach ($servers as $server) {
1740 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1741 Worker::add(PRIORITY_LOW, "discover_poco", "server", $url);
1746 // Currently disabled, since the service isn't available anymore.
1747 // It is not removed since I hope that there will be a successor.
1748 // Discover GNU Social Servers.
1749 //if (!Config::get('system','ostatus_disabled')) {
1750 // $serverdata = "http://gstools.org/api/get_open_instances/";
1752 // $result = z_fetch_url($serverdata);
1753 // if ($result["success"]) {
1754 // $servers = json_decode($result["body"]);
1756 // foreach($servers->data as $server)
1757 // poco_check_server($server->instance_address);
1761 Config::set('poco','last_federation_discovery', time());
1764 function poco_discover_single_server($id) {
1765 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1766 if (!DBM::is_result($r)) {
1772 // Discover new servers out there (Works from Friendica version 3.5.2)
1773 poco_fetch_serverlist($server["poco"]);
1775 // Fetch all users from the other server
1776 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1778 logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1780 $retdata = z_fetch_url($url);
1781 if ($retdata["success"]) {
1782 $data = json_decode($retdata["body"]);
1784 poco_discover_server($data, 2);
1786 if (Config::get('system','poco_discovery') > 1) {
1788 $timeframe = Config::get('system','poco_discovery_since');
1789 if ($timeframe == 0) {
1793 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1795 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1796 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1800 $retdata = z_fetch_url($url);
1801 if ($retdata["success"]) {
1802 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1803 $success = poco_discover_server(json_decode($retdata["body"]));
1806 if (!$success && (Config::get('system','poco_discovery') > 2)) {
1807 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1808 poco_discover_server_users($data, $server);
1812 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1816 // If the server hadn't replied correctly, then force a sanity check
1817 poco_check_server($server["url"], $server["network"], true);
1819 // If we couldn't reach the server, we will try it some time later
1820 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1826 function poco_discover($complete = false) {
1828 // Update the server list
1829 poco_discover_federation();
1833 $requery_days = intval(Config::get("system", "poco_requery_days"));
1835 if ($requery_days == 0) {
1838 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1840 $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));
1841 if (DBM::is_result($r)) {
1842 foreach ($r as $server) {
1844 if (!poco_check_server($server["url"], $server["network"])) {
1845 // The server is not reachable? Okay, then we will try it later
1846 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1850 logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1851 Worker::add(PRIORITY_LOW, "discover_poco", "update_server_directory", (int)$server['id']);
1853 if (!$complete && (--$no_of_queries == 0)) {
1860 function poco_discover_server_users($data, $server) {
1862 if (!isset($data->entry)) {
1866 foreach ($data->entry as $entry) {
1868 if (isset($entry->urls)) {
1869 foreach ($entry->urls as $url) {
1870 if ($url->type == 'profile') {
1871 $profile_url = $url->value;
1872 $urlparts = parse_url($profile_url);
1873 $username = end(explode("/", $urlparts["path"]));
1877 if ($username != "") {
1878 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1880 // Fetch all contacts from a given user from the other server
1881 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1883 $retdata = z_fetch_url($url);
1884 if ($retdata["success"]) {
1885 poco_discover_server(json_decode($retdata["body"]), 3);
1891 function poco_discover_server($data, $default_generation = 0) {
1893 if (!isset($data->entry) || !count($data->entry)) {
1899 foreach ($data->entry as $entry) {
1901 $profile_photo = '';
1905 $updated = NULL_DATE;
1911 $generation = $default_generation;
1913 $name = $entry->displayName;
1915 if (isset($entry->urls)) {
1916 foreach ($entry->urls as $url) {
1917 if ($url->type == 'profile') {
1918 $profile_url = $url->value;
1921 if ($url->type == 'webfinger') {
1922 $connect_url = str_replace('acct:' , '', $url->value);
1928 if (isset($entry->photos)) {
1929 foreach ($entry->photos as $photo) {
1930 if ($photo->type == 'profile') {
1931 $profile_photo = $photo->value;
1937 if (isset($entry->updated)) {
1938 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1941 if (isset($entry->network)) {
1942 $network = $entry->network;
1945 if (isset($entry->currentLocation)) {
1946 $location = $entry->currentLocation;
1949 if (isset($entry->aboutMe)) {
1950 $about = html2bbcode($entry->aboutMe);
1953 if (isset($entry->gender)) {
1954 $gender = $entry->gender;
1957 if(isset($entry->generation) && ($entry->generation > 0)) {
1958 $generation = ++$entry->generation;
1961 if(isset($entry->contactType) && ($entry->contactType >= 0)) {
1962 $contact_type = $entry->contactType;
1965 if (isset($entry->tags)) {
1966 foreach ($entry->tags as $tag) {
1967 $keywords = implode(", ", $tag);
1971 if ($generation > 0) {
1974 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1976 $gcontact = array("url" => $profile_url,
1978 "network" => $network,
1979 "photo" => $profile_photo,
1981 "location" => $location,
1982 "gender" => $gender,
1983 "keywords" => $keywords,
1984 "connect" => $connect_url,
1985 "updated" => $updated,
1986 "contact-type" => $contact_type,
1987 "generation" => $generation);
1990 $gcontact = sanitize_gcontact($gcontact);
1991 update_gcontact($gcontact);
1992 } catch (Exception $e) {
1993 logger($e->getMessage(), LOGGER_DEBUG);
1996 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
2003 * @brief Removes unwanted parts from a contact url
2005 * @param string $url Contact url
2006 * @return string Contact url with the wanted parts
2008 function clean_contact_url($url) {
2009 $parts = parse_url($url);
2011 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
2015 $new_url = $parts["scheme"]."://".$parts["host"];
2017 if (isset($parts["port"])) {
2018 $new_url .= ":".$parts["port"];
2021 if (isset($parts["path"])) {
2022 $new_url .= $parts["path"];
2025 if ($new_url != $url) {
2026 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), LOGGER_DEBUG);
2033 * @brief Replace alternate OStatus user format with the primary one
2035 * @param arr $contact contact array (called by reference)
2037 function fix_alternate_contact_address(&$contact) {
2038 if (($contact["network"] == NETWORK_OSTATUS) && poco_alternate_ostatus_url($contact["url"])) {
2039 $data = Probe::uri($contact["url"]);
2040 if ($contact["network"] == NETWORK_OSTATUS) {
2041 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
2042 $contact["url"] = $data["url"];
2043 $contact["addr"] = $data["addr"];
2044 $contact["alias"] = $data["alias"];
2045 $contact["server_url"] = $data["baseurl"];
2051 * @brief Fetch the gcontact id, add an entry if not existed
2053 * @param arr $contact contact array
2054 * @return bool|int Returns false if not found, integer if contact was found
2056 function get_gcontact_id($contact) {
2061 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
2062 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
2066 if ($contact["network"] == NETWORK_STATUSNET) {
2067 $contact["network"] = NETWORK_OSTATUS;
2070 // All new contacts are hidden by default
2071 if (!isset($contact["hide"])) {
2072 $contact["hide"] = true;
2075 // Replace alternate OStatus user format with the primary one
2076 fix_alternate_contact_address($contact);
2078 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
2079 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
2080 $contact["url"] = clean_contact_url($contact["url"]);
2083 dba::lock('gcontact');
2084 $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
2085 dbesc(normalise_link($contact["url"])));
2087 if (DBM::is_result($r)) {
2088 $gcontact_id = $r[0]["id"];
2090 // Update every 90 days
2091 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
2092 $last_failure_str = $r[0]["last_failure"];
2093 $last_failure = strtotime($r[0]["last_failure"]);
2094 $last_contact_str = $r[0]["last_contact"];
2095 $last_contact = strtotime($r[0]["last_contact"]);
2096 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
2099 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
2100 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
2101 dbesc($contact["name"]),
2102 dbesc($contact["nick"]),
2103 dbesc($contact["addr"]),
2104 dbesc($contact["network"]),
2105 dbesc($contact["url"]),
2106 dbesc(normalise_link($contact["url"])),
2107 dbesc($contact["photo"]),
2108 dbesc(datetime_convert()),
2109 dbesc(datetime_convert()),
2110 dbesc($contact["location"]),
2111 dbesc($contact["about"]),
2112 intval($contact["hide"]),
2113 intval($contact["generation"])
2116 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
2117 dbesc(normalise_link($contact["url"])));
2119 if (DBM::is_result($r)) {
2120 $gcontact_id = $r[0]["id"];
2122 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
2128 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
2129 Worker::add(PRIORITY_LOW, 'gprobe', $contact["url"]);
2132 return $gcontact_id;
2136 * @brief Updates the gcontact table from a given array
2138 * @param arr $contact contact array
2139 * @return bool|int Returns false if not found, integer if contact was found
2141 function update_gcontact($contact) {
2143 // Check for invalid "contact-type" value
2144 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
2145 $contact['contact-type'] = 0;
2148 /// @todo update contact table as well
2150 $gcontact_id = get_gcontact_id($contact);
2152 if (!$gcontact_id) {
2156 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
2157 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
2158 FROM `gcontact` WHERE `id` = %d LIMIT 1",
2159 intval($gcontact_id));
2161 // Get all field names
2163 foreach ($r[0] as $field => $data) {
2164 $fields[$field] = $data;
2167 unset($fields["url"]);
2168 unset($fields["updated"]);
2169 unset($fields["hide"]);
2171 // Bugfix: We had an error in the storing of keywords which lead to the "0"
2172 // This value is still transmitted via poco.
2173 if ($contact["keywords"] == "0") {
2174 unset($contact["keywords"]);
2177 if ($r[0]["keywords"] == "0") {
2178 $r[0]["keywords"] = "";
2181 // assign all unassigned fields from the database entry
2182 foreach ($fields as $field => $data) {
2183 if (!isset($contact[$field]) || ($contact[$field] == "")) {
2184 $contact[$field] = $r[0][$field];
2188 if (!isset($contact["hide"])) {
2189 $contact["hide"] = $r[0]["hide"];
2192 $fields["hide"] = $r[0]["hide"];
2194 if ($contact["network"] == NETWORK_STATUSNET) {
2195 $contact["network"] = NETWORK_OSTATUS;
2198 // Replace alternate OStatus user format with the primary one
2199 fix_alternate_contact_address($contact);
2201 if (!isset($contact["updated"])) {
2202 $contact["updated"] = DBM::date();
2205 if ($contact["network"] == NETWORK_TWITTER) {
2206 $contact["server_url"] = 'http://twitter.com';
2209 if ($contact["server_url"] == "") {
2210 $data = Probe::uri($contact["url"]);
2211 if ($data["network"] != NETWORK_PHANTOM) {
2212 $contact["server_url"] = $data['baseurl'];
2215 $contact["server_url"] = normalise_link($contact["server_url"]);
2218 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
2219 $hostname = str_replace("http://", "", $contact["server_url"]);
2220 $contact["addr"] = $contact["nick"]."@".$hostname;
2223 // Check if any field changed
2225 unset($fields["generation"]);
2227 if ((($contact["generation"] > 0) && ($contact["generation"] <= $r[0]["generation"])) || ($r[0]["generation"] == 0)) {
2228 foreach ($fields as $field => $data) {
2229 if ($contact[$field] != $r[0][$field]) {
2230 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
2235 if ($contact["generation"] < $r[0]["generation"]) {
2236 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
2242 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
2243 $condition = array('`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
2244 normalise_link($contact["url"]), $contact["generation"]);
2245 $contact["updated"] = DBM::date($contact["updated"]);
2247 $updated = array('photo' => $contact['photo'], 'name' => $contact['name'],
2248 'nick' => $contact['nick'], 'addr' => $contact['addr'],
2249 'network' => $contact['network'], 'birthday' => $contact['birthday'],
2250 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
2251 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
2252 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
2253 'notify' => $contact['notify'], 'url' => $contact['url'],
2254 'location' => $contact['location'], 'about' => $contact['about'],
2255 'generation' => $contact['generation'], 'updated' => $contact['updated'],
2256 'server_url' => $contact['server_url'], 'connect' => $contact['connect']);
2258 dba::update('gcontact', $updated, $condition, $fields);
2260 // Now update the contact entry with the user id "0" as well.
2261 // This is used for the shadow copies of public items.
2262 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
2263 dbesc(normalise_link($contact["url"])));
2265 if (DBM::is_result($r)) {
2266 logger("Update public contact ".$r[0]["id"], LOGGER_DEBUG);
2268 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
2270 $fields = array('name', 'nick', 'addr',
2271 'network', 'bd', 'gender',
2272 'keywords', 'alias', 'contact-type',
2273 'url', 'location', 'about');
2274 $old_contact = dba::select('contact', $fields, array('id' => $r[0]["id"]), array('limit' => 1));
2276 // Update it with the current values
2277 $fields = array('name' => $contact['name'], 'nick' => $contact['nick'],
2278 'addr' => $contact['addr'], 'network' => $contact['network'],
2279 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
2280 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
2281 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
2282 'location' => $contact['location'], 'about' => $contact['about']);
2284 dba::update('contact', $fields, array('id' => $r[0]["id"]), $old_contact);
2288 return $gcontact_id;
2292 * @brief Updates the gcontact entry from probe
2294 * @param str $url profile link
2296 function update_gcontact_from_probe($url) {
2297 $data = Probe::uri($url);
2299 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
2300 logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
2304 $data["server_url"] = $data["baseurl"];
2306 update_gcontact($data);
2310 * @brief Update the gcontact entry for a given user id
2312 * @param int $uid User ID
2314 function update_gcontact_for_user($uid) {
2315 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
2316 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
2317 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
2318 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
2319 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
2321 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
2322 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
2323 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
2326 $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
2327 "country-name" => $r[0]["country-name"]));
2329 // The "addr" field was added in 3.4.3 so it can be empty for older users
2330 if ($r[0]["addr"] != "") {
2331 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", System::baseUrl());
2333 $addr = $r[0]["addr"];
2336 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
2337 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
2338 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
2339 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
2340 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
2341 "nick" => $r[0]["nickname"], "addr" => $addr,
2342 "connect" => $addr, "server_url" => System::baseUrl(),
2343 "generation" => 1, "network" => NETWORK_DFRN);
2345 update_gcontact($gcontact);
2349 * @brief Fetches users of given GNU Social server
2351 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
2353 * @param str $server Server address
2355 function gs_fetch_users($server) {
2357 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
2359 $url = $server."/main/statistics";
2361 $result = z_fetch_url($url);
2362 if (!$result["success"]) {
2366 $statistics = json_decode($result["body"]);
2368 if (is_object($statistics->config)) {
2369 if ($statistics->config->instance_with_ssl) {
2370 $server = "https://";
2372 $server = "http://";
2375 $server .= $statistics->config->instance_address;
2377 $hostname = $statistics->config->instance_address;
2379 /// @TODO is_object() above means here no object, still $statistics is being used as object
2380 if ($statistics->instance_with_ssl) {
2381 $server = "https://";
2383 $server = "http://";
2386 $server .= $statistics->instance_address;
2388 $hostname = $statistics->instance_address;
2391 if (is_object($statistics->users)) {
2392 foreach ($statistics->users as $nick => $user) {
2393 $profile_url = $server."/".$user->nickname;
2395 $contact = array("url" => $profile_url,
2396 "name" => $user->fullname,
2397 "addr" => $user->nickname."@".$hostname,
2398 "nick" => $user->nickname,
2399 "about" => $user->bio,
2400 "network" => NETWORK_OSTATUS,
2401 "photo" => System::baseUrl()."/images/person-175.jpg");
2402 get_gcontact_id($contact);
2408 * @brief Asking GNU Social server on a regular base for their user data
2411 function gs_discover() {
2413 $requery_days = intval(Config::get("system", "poco_requery_days"));
2415 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
2417 $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",
2418 dbesc(NETWORK_OSTATUS), dbesc($last_update));
2420 if (!DBM::is_result($r)) {
2424 foreach ($r as $server) {
2425 gs_fetch_users($server["url"]);
2426 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
2431 * @brief Returns a list of all known servers
2432 * @return array List of server urls
2434 function poco_serverlist() {
2435 $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
2436 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
2437 ORDER BY `last_contact`
2439 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
2440 if (!DBM::is_result($r)) {