3 * @file include/socgraph.php
5 * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6 * @todo Fetch profile data from profile page for Redmatrix users
7 * @todo Detect if it is a forum
10 require_once('include/datetime.php');
11 require_once("include/Scrape.php");
12 require_once("include/network.php");
13 require_once("include/html2bbcode.php");
14 require_once("include/Contact.php");
15 require_once("include/Photo.php");
20 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
21 * and add the entries to the gcontact (Global Contact) table, or update existing entries
22 * if anything (name or photo) has changed.
23 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
25 * Once the global contact is stored add (if necessary) the contact linkage which associates
26 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
27 * pointing to the same global contact id.
34 function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
39 if((! $url) || (! $uid)) {
40 $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
43 if (dbm::is_result($r)) {
55 $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') ;
57 logger('poco_load: ' . $url, LOGGER_DEBUG);
61 logger('poco_load: returns ' . $s, LOGGER_DATA);
63 logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
65 if(($a->get_curl_code() > 299) || (! $s))
70 logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
72 if(! isset($j->entry))
76 foreach($j->entry as $entry) {
84 $updated = '0000-00-00 00:00:00';
92 $name = $entry->displayName;
94 if (isset($entry->urls)) {
95 foreach ($entry->urls as $url) {
96 if ($url->type == 'profile') {
97 $profile_url = $url->value;
100 if ($url->type == 'webfinger') {
101 $connect_url = str_replace('acct:' , '', $url->value);
106 if (isset($entry->photos)) {
107 foreach ($entry->photos as $photo) {
108 if ($photo->type == 'profile') {
109 $profile_photo = $photo->value;
115 if (isset($entry->updated)) {
116 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
119 if (isset($entry->network)) {
120 $network = $entry->network;
123 if (isset($entry->currentLocation)) {
124 $location = $entry->currentLocation;
127 if (isset($entry->aboutMe)) {
128 $about = html2bbcode($entry->aboutMe);
131 if (isset($entry->gender)) {
132 $gender = $entry->gender;
135 if (isset($entry->generation) AND ($entry->generation > 0)) {
136 $generation = ++$entry->generation;
139 if (isset($entry->tags)) {
140 foreach($entry->tags as $tag) {
141 $keywords = implode(", ", $tag);
145 if (isset($entry->contactType) AND ($entry->contactType >= 0))
146 $contact_type = $entry->contactType;
148 // If you query a Friendica server for its profiles, the network has to be Friendica
149 /// TODO It could also be a Redmatrix server
151 // $network = NETWORK_DFRN;
153 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
155 $gcontact = array("url" => $profile_url, "contact-type" => $contact_type, "generation" => $generation);
156 update_gcontact($gcontact);
158 // Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
159 // Deactivated because we now update Friendica contacts in dfrn.php
160 //if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
161 // q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
162 // WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
167 // dbesc(normalise_link($profile_url)),
168 // dbesc(NETWORK_DFRN));
170 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
172 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
180 function poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid = 0, $uid = 0, $zcid = 0) {
184 // 1: Profiles on this server
185 // 2: Contacts of profiles on this server
186 // 3: Contacts of contacts of profiles on this server
191 if ($profile_url == "")
194 $urlparts = parse_url($profile_url);
195 if (!isset($urlparts["scheme"]))
198 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
199 "identi.ca", "alpha.app.net")))
202 // Don't store the statusnet connector as network
203 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
204 if ($network == NETWORK_STATUSNET)
207 // Assure that there are no parameter fragments in the profile url
208 if (in_array($network, array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
209 $profile_url = clean_contact_url($profile_url);
211 $alternate = poco_alternate_ostatus_url($profile_url);
213 $orig_updated = $updated;
215 // The global contacts should contain the original picture, not the cached one
216 if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link(App::get_baseurl()."/photo/"))) {
220 $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
221 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
223 if (dbm::is_result($r))
224 $network = $r[0]["network"];
226 if (($network == "") OR ($network == NETWORK_OSTATUS)) {
227 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
228 dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
230 if (dbm::is_result($r)) {
231 $network = $r[0]["network"];
232 //$profile_url = $r[0]["url"];
236 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
237 dbesc(normalise_link($profile_url))
241 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
242 $network = $x[0]["network"];
244 if ($updated == "0000-00-00 00:00:00")
245 $updated = $x[0]["updated"];
247 $created = $x[0]["created"];
248 $server_url = $x[0]["server_url"];
249 $nick = $x[0]["nick"];
250 $addr = $x[0]["addr"];
251 $alias = $x[0]["alias"];
252 $notify = $x[0]["notify"];
254 $created = "0000-00-00 00:00:00";
257 $urlparts = parse_url($profile_url);
258 $nick = end(explode("/", $urlparts["path"]));
264 if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
265 AND poco_reachable($profile_url, $server_url, $network, false)) {
266 $data = probe_url($profile_url);
268 $orig_profile = $profile_url;
270 $network = $data["network"];
271 $name = $data["name"];
272 $nick = $data["nick"];
273 $addr = $data["addr"];
274 $alias = $data["alias"];
275 $notify = $data["notify"];
276 $profile_url = $data["url"];
277 $profile_photo = $data["photo"];
278 $server_url = $data["baseurl"];
280 if ($alternate AND ($network == NETWORK_OSTATUS)) {
281 // Delete the old entry - if it exists
282 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
284 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
285 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
288 // possibly create a new entry
289 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
293 if ($alternate AND ($network == NETWORK_OSTATUS))
296 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
297 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
299 dbesc(normalise_link($profile_url))
303 if (($name == "") OR ($profile_photo == ""))
306 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
309 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
311 poco_check_server($server_url, $network);
313 $gcontact = array("url" => $profile_url,
317 "network" => $network,
318 "photo" => $profile_photo,
320 "location" => $location,
322 "keywords" => $keywords,
323 "server_url" => $server_url,
324 "connect" => $connect_url,
326 "updated" => $updated,
327 "generation" => $generation);
329 $gcid = update_gcontact($gcontact);
334 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
340 if (! dbm::is_result($r)) {
341 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
346 dbesc(datetime_convert())
349 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
350 dbesc(datetime_convert()),
361 function poco_reachable($profile, $server = "", $network = "", $force = false) {
364 $server = poco_detect_server($profile);
369 return poco_check_server($server, $network, $force);
372 function poco_detect_server($profile) {
374 // Try to detect the server path based upon some known standard paths
377 if ($server_url == "") {
378 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
379 if ($friendica != $profile) {
380 $server_url = $friendica;
381 $network = NETWORK_DFRN;
385 if ($server_url == "") {
386 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
387 if ($diaspora != $profile) {
388 $server_url = $diaspora;
389 $network = NETWORK_DIASPORA;
393 if ($server_url == "") {
394 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
395 if ($red != $profile) {
397 $network = NETWORK_DIASPORA;
402 if ($server_url == "") {
403 $red = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
404 if ($red != $profile) {
406 $network = NETWORK_OSTATUS;
413 function poco_alternate_ostatus_url($url) {
414 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
417 function poco_last_updated($profile, $force = false) {
419 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
420 dbesc(normalise_link($profile)));
422 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
423 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
424 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
426 if ($gcontacts[0]["server_url"] != "")
427 $server_url = $gcontacts[0]["server_url"];
429 $server_url = poco_detect_server($profile);
431 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
432 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
436 if ($server_url != "") {
437 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
440 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
441 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
443 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
447 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
448 dbesc($server_url), dbesc(normalise_link($profile)));
451 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
452 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
453 dbesc(normalise_link($server_url)));
456 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
457 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
462 // noscrape is really fast so we don't cache the call.
463 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
465 // Use noscrape if possible
466 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
469 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
471 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
473 $noscrape = json_decode($noscraperet["body"], true);
475 if (is_array($noscrape)) {
476 $contact = array("url" => $profile,
477 "network" => $server[0]["network"],
478 "generation" => $gcontacts[0]["generation"]);
480 if (isset($noscrape["fn"]))
481 $contact["name"] = $noscrape["fn"];
483 if (isset($noscrape["comm"]))
484 $contact["community"] = $noscrape["comm"];
486 if (isset($noscrape["tags"])) {
487 $keywords = implode(" ", $noscrape["tags"]);
489 $contact["keywords"] = $keywords;
492 $location = formatted_location($noscrape);
494 $contact["location"] = $location;
496 if (isset($noscrape["dfrn-notify"]))
497 $contact["notify"] = $noscrape["dfrn-notify"];
499 // Remove all fields that are not present in the gcontact table
500 unset($noscrape["fn"]);
501 unset($noscrape["key"]);
502 unset($noscrape["homepage"]);
503 unset($noscrape["comm"]);
504 unset($noscrape["tags"]);
505 unset($noscrape["locality"]);
506 unset($noscrape["region"]);
507 unset($noscrape["country-name"]);
508 unset($noscrape["contacts"]);
509 unset($noscrape["dfrn-request"]);
510 unset($noscrape["dfrn-confirm"]);
511 unset($noscrape["dfrn-notify"]);
512 unset($noscrape["dfrn-poll"]);
514 // Set the date of the last contact
515 /// @todo By now the function "update_gcontact" doesn't work with this field
516 //$contact["last_contact"] = datetime_convert();
518 $contact = array_merge($contact, $noscrape);
520 update_gcontact($contact);
522 if (trim($noscrape["updated"]) != "") {
523 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
524 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
526 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
528 return $noscrape["updated"];
535 // If we only can poll the feed, then we only do this once a while
536 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
537 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
538 return $gcontacts[0]["updated"];
541 $data = probe_url($profile);
543 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
544 // Then check the other link and delete this one
545 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
546 (normalise_link($profile) == normalise_link($data["alias"])) AND
547 (normalise_link($profile) != normalise_link($data["url"]))) {
549 // Delete the old entry
550 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
551 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
553 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
554 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
556 poco_last_updated($data["url"], $force);
558 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
562 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
563 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
564 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
566 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
570 $contact = array("generation" => $gcontacts[0]["generation"]);
572 $contact = array_merge($contact, $data);
574 $contact["server_url"] = $data["baseurl"];
576 unset($contact["batch"]);
577 unset($contact["poll"]);
578 unset($contact["request"]);
579 unset($contact["confirm"]);
580 unset($contact["poco"]);
581 unset($contact["priority"]);
582 unset($contact["pubkey"]);
583 unset($contact["baseurl"]);
585 update_gcontact($contact);
587 $feedret = z_fetch_url($data["poll"]);
589 if (!$feedret["success"]) {
590 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
591 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
593 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
597 $doc = new DOMDocument();
598 @$doc->loadXML($feedret["body"]);
600 $xpath = new DomXPath($doc);
601 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
603 $entries = $xpath->query('/atom:feed/atom:entry');
607 foreach ($entries AS $entry) {
608 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
609 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
611 if ($last_updated < $published)
612 $last_updated = $published;
614 if ($last_updated < $updated)
615 $last_updated = $updated;
618 // Maybe there aren't any entries. Then check if it is a valid feed
619 if ($last_updated == "")
620 if ($xpath->query('/atom:feed')->length > 0)
621 $last_updated = "0000-00-00 00:00:00";
623 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
624 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
626 if (($gcontacts[0]["generation"] == 0))
627 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
628 dbesc(normalise_link($profile)));
630 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
632 return($last_updated);
635 function poco_do_update($created, $updated, $last_failure, $last_contact) {
636 $now = strtotime(datetime_convert());
638 if ($updated > $last_contact)
639 $contact_time = strtotime($updated);
641 $contact_time = strtotime($last_contact);
643 $failure_time = strtotime($last_failure);
644 $created_time = strtotime($created);
646 // If there is no "created" time then use the current time
647 if ($created_time <= 0)
648 $created_time = $now;
650 // If the last contact was less than 24 hours then don't update
651 if (($now - $contact_time) < (60 * 60 * 24))
654 // If the last failure was less than 24 hours then don't update
655 if (($now - $failure_time) < (60 * 60 * 24))
658 // If the last contact was less than a week ago and the last failure is older than a week then don't update
659 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
662 // 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
663 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
666 // 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
667 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
673 function poco_to_boolean($val) {
674 if (($val == "true") OR ($val == 1))
676 if (($val == "false") OR ($val == 0))
682 function poco_check_server($server_url, $network = "", $force = false) {
684 // Unify the server address
685 $server_url = trim($server_url, "/");
686 $server_url = str_replace("/index.php", "", $server_url);
688 if ($server_url == "")
691 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
694 if ($servers[0]["created"] == "0000-00-00 00:00:00")
695 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
696 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
698 $poco = $servers[0]["poco"];
699 $noscrape = $servers[0]["noscrape"];
702 $network = $servers[0]["network"];
704 $last_contact = $servers[0]["last_contact"];
705 $last_failure = $servers[0]["last_failure"];
706 $version = $servers[0]["version"];
707 $platform = $servers[0]["platform"];
708 $site_name = $servers[0]["site_name"];
709 $info = $servers[0]["info"];
710 $register_policy = $servers[0]["register_policy"];
712 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
713 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
714 return ($last_contact >= $last_failure);
723 $register_policy = -1;
725 $last_contact = "0000-00-00 00:00:00";
726 $last_failure = "0000-00-00 00:00:00";
728 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
731 $orig_last_failure = $last_failure;
733 // Check if the page is accessible via SSL.
734 $server_url = str_replace("http://", "https://", $server_url);
735 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
737 // Maybe the page is unencrypted only?
738 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
739 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
740 $server_url = str_replace("https://", "http://", $server_url);
741 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
743 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
746 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
747 // Workaround for bad configured servers (known nginx problem)
748 if ($serverret["debug"]["http_code"] != "403") {
749 $last_failure = datetime_convert();
752 } elseif ($network == NETWORK_DIASPORA)
753 $last_contact = datetime_convert();
757 $serverret = z_fetch_url($server_url);
759 if (!$serverret["success"] OR ($serverret["body"] == ""))
762 $lines = explode("\n",$serverret["header"]);
764 foreach($lines as $line) {
766 if(stristr($line,'X-Diaspora-Version:')) {
767 $platform = "Diaspora";
768 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
769 $version = trim(str_replace("x-diaspora-version:", "", $version));
770 $network = NETWORK_DIASPORA;
771 $versionparts = explode("-", $version);
772 $version = $versionparts[0];
775 if(stristr($line,'Server: Mastodon')) {
776 $platform = "Mastodon";
777 $network = NETWORK_OSTATUS;
778 // Mastodon doesn't reveal version numbers
786 // Test for Statusnet
787 // Will also return data for Friendica and GNU Social - but it will be overwritten later
788 // The "not implemented" is a special treatment for really, really old Friendica versions
789 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
790 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
791 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
792 $platform = "StatusNet";
793 $version = trim($serverret["body"], '"');
794 $network = NETWORK_OSTATUS;
797 // Test for GNU Social
798 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
799 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
800 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
801 $platform = "GNU Social";
802 $version = trim($serverret["body"], '"');
803 $network = NETWORK_OSTATUS;
806 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
807 if ($serverret["success"]) {
808 $data = json_decode($serverret["body"]);
810 if (isset($data->site->server)) {
811 $last_contact = datetime_convert();
813 if (isset($data->site->hubzilla)) {
814 $platform = $data->site->hubzilla->PLATFORM_NAME;
815 $version = $data->site->hubzilla->RED_VERSION;
816 $network = NETWORK_DIASPORA;
818 if (isset($data->site->redmatrix)) {
819 if (isset($data->site->redmatrix->PLATFORM_NAME))
820 $platform = $data->site->redmatrix->PLATFORM_NAME;
821 elseif (isset($data->site->redmatrix->RED_PLATFORM))
822 $platform = $data->site->redmatrix->RED_PLATFORM;
824 $version = $data->site->redmatrix->RED_VERSION;
825 $network = NETWORK_DIASPORA;
827 if (isset($data->site->friendica)) {
828 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
829 $version = $data->site->friendica->FRIENDICA_VERSION;
830 $network = NETWORK_DFRN;
833 $site_name = $data->site->name;
835 $data->site->closed = poco_to_boolean($data->site->closed);
836 $data->site->private = poco_to_boolean($data->site->private);
837 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
839 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
840 $register_policy = REGISTER_APPROVE;
841 elseif (!$data->site->closed AND !$data->site->private)
842 $register_policy = REGISTER_OPEN;
844 $register_policy = REGISTER_CLOSED;
849 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
851 $serverret = z_fetch_url($server_url."/statistics.json");
852 if ($serverret["success"]) {
853 $data = json_decode($serverret["body"]);
855 $version = $data->version;
857 $site_name = $data->name;
859 if (isset($data->network) AND ($platform == ""))
860 $platform = $data->network;
862 if ($platform == "Diaspora")
863 $network = NETWORK_DIASPORA;
865 if ($data->registrations_open)
866 $register_policy = REGISTER_OPEN;
868 $register_policy = REGISTER_CLOSED;
870 if (isset($data->version))
871 $last_contact = datetime_convert();
875 // Check for noscrape
876 // Friendica servers could be detected as OStatus servers
877 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
878 $serverret = z_fetch_url($server_url."/friendica/json");
880 if (!$serverret["success"])
881 $serverret = z_fetch_url($server_url."/friendika/json");
883 if ($serverret["success"]) {
884 $data = json_decode($serverret["body"]);
886 if (isset($data->version)) {
887 $last_contact = datetime_convert();
888 $network = NETWORK_DFRN;
890 $noscrape = $data->no_scrape_url;
891 $version = $data->version;
892 $site_name = $data->site_name;
894 $register_policy_str = $data->register_policy;
895 $platform = $data->platform;
897 switch ($register_policy_str) {
898 case "REGISTER_CLOSED":
899 $register_policy = REGISTER_CLOSED;
901 case "REGISTER_APPROVE":
902 $register_policy = REGISTER_APPROVE;
904 case "REGISTER_OPEN":
905 $register_policy = REGISTER_OPEN;
914 $serverret = z_fetch_url($server_url."/poco");
915 if ($serverret["success"]) {
916 $data = json_decode($serverret["body"]);
917 if (isset($data->totalResults)) {
918 $poco = $server_url."/poco";
919 $last_contact = datetime_convert();
924 // Check again if the server exists
925 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
927 $version = strip_tags($version);
928 $site_name = strip_tags($site_name);
929 $info = strip_tags($info);
930 $platform = strip_tags($platform);
933 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
934 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
939 intval($register_policy),
944 dbesc($last_contact),
945 dbesc($last_failure),
946 dbesc(normalise_link($server_url))
949 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
950 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
952 dbesc(normalise_link($server_url)),
956 intval($register_policy),
961 dbesc(datetime_convert()),
962 dbesc($last_contact),
963 dbesc($last_failure),
964 dbesc(datetime_convert())
967 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
972 function count_common_friends($uid,$cid) {
974 $r = q("SELECT count(*) as `total`
975 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
976 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
977 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
978 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
985 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
986 if (dbm::is_result($r))
987 return $r[0]['total'];
993 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
996 $sql_extra = " order by rand() ";
998 $sql_extra = " order by `gcontact`.`name` asc ";
1000 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1002 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1003 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1004 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1005 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1006 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1007 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1008 $sql_extra LIMIT %d, %d",
1022 function count_common_friends_zcid($uid,$zcid) {
1024 $r = q("SELECT count(*) as `total`
1025 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1026 where `glink`.`zcid` = %d
1027 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1032 if (dbm::is_result($r))
1033 return $r[0]['total'];
1038 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1041 $sql_extra = " order by rand() ";
1043 $sql_extra = " order by `gcontact`.`name` asc ";
1045 $r = q("SELECT `gcontact`.*
1046 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1047 where `glink`.`zcid` = %d
1048 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1049 $sql_extra limit %d, %d",
1061 function count_all_friends($uid,$cid) {
1063 $r = q("SELECT count(*) as `total`
1064 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1065 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1066 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1071 if (dbm::is_result($r))
1072 return $r[0]['total'];
1078 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1080 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1082 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1083 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1084 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1085 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1086 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1099 function suggestion_query($uid, $start = 0, $limit = 80) {
1105 // Uncommented because the result of the queries are to big to store it in the cache.
1106 // We need to decide if we want to change the db column type or if we want to delete it.
1107 // $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1108 // if (!is_null($list)) {
1112 $network = array(NETWORK_DFRN);
1114 if (get_config('system','diaspora_enabled'))
1115 $network[] = NETWORK_DIASPORA;
1117 if (!get_config('system','ostatus_disabled'))
1118 $network[] = NETWORK_OSTATUS;
1120 $sql_network = implode("', '", $network);
1121 $sql_network = "'".$sql_network."'";
1123 /// @todo This query is really slow
1124 // By now we cache the data for five minutes
1125 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1126 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1127 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1128 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1129 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1130 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1131 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1132 AND `gcontact`.`network` IN (%s)
1133 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1143 if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1144 // Uncommented because the result of the queries are to big to store it in the cache.
1145 // We need to decide if we want to change the db column type or if we want to delete it.
1146 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1151 $r2 = q("SELECT gcontact.* FROM gcontact
1152 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1153 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1154 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1155 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1156 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1157 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1158 AND `gcontact`.`network` IN (%s)
1159 ORDER BY rand() LIMIT %d, %d",
1169 foreach ($r2 AS $suggestion)
1170 $list[$suggestion["nurl"]] = $suggestion;
1172 foreach ($r AS $suggestion)
1173 $list[$suggestion["nurl"]] = $suggestion;
1175 while (sizeof($list) > ($limit))
1178 // Uncommented because the result of the queries are to big to store it in the cache.
1179 // We need to decide if we want to change the db column type or if we want to delete it.
1180 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1184 function update_suggestions() {
1190 /// TODO Check if it is really neccessary to poll the own server
1191 poco_load(0,0,0,App::get_baseurl() . '/poco');
1193 $done[] = App::get_baseurl() . '/poco';
1195 if (strlen(get_config('system','directory'))) {
1196 $x = fetch_url(get_server()."/pubsites");
1198 $j = json_decode($x);
1200 foreach ($j->entries as $entry) {
1202 poco_check_server($entry->url);
1204 $url = $entry->url . '/poco';
1205 if (! in_array($url,$done)) {
1206 poco_load(0,0,0,$entry->url . '/poco');
1213 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1214 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1215 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1218 if (dbm::is_result($r)) {
1219 foreach ($r as $rr) {
1220 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1221 if(! in_array($base,$done))
1222 poco_load(0,0,0,$base);
1227 function poco_discover_federation() {
1228 $last = get_config('poco','last_federation_discovery');
1231 $next = $last + (24 * 60 * 60);
1236 // Discover Friendica, Hubzilla and Diaspora servers
1237 $serverdata = fetch_url("http://the-federation.info/pods.json");
1240 $servers = json_decode($serverdata);
1242 foreach($servers->pods AS $server)
1243 poco_check_server("https://".$server->host);
1246 // Discover GNU Social Servers
1247 if (!get_config('system','ostatus_disabled')) {
1248 $serverdata = "http://gstools.org/api/get_open_instances/";
1250 $result = z_fetch_url($serverdata);
1251 if ($result["success"]) {
1252 $servers = json_decode($result["body"]);
1254 foreach($servers->data AS $server)
1255 poco_check_server($server->instance_address);
1259 set_config('poco','last_federation_discovery', time());
1262 function poco_discover($complete = false) {
1264 // Update the server list
1265 poco_discover_federation();
1269 $requery_days = intval(get_config("system", "poco_requery_days"));
1271 if ($requery_days == 0)
1274 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1276 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `poco` != '' AND `last_poco_query` < '%s' ORDER BY RAND()", dbesc($last_update));
1278 foreach ($r AS $server) {
1280 if (!poco_check_server($server["url"], $server["network"])) {
1281 // The server is not reachable? Okay, then we will try it later
1282 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1286 // Fetch all users from the other server
1287 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1289 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1291 $retdata = z_fetch_url($url);
1292 if ($retdata["success"]) {
1293 $data = json_decode($retdata["body"]);
1295 poco_discover_server($data, 2);
1297 if (get_config('system','poco_discovery') > 1) {
1299 $timeframe = get_config('system','poco_discovery_since');
1300 if ($timeframe == 0)
1303 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1305 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1306 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1310 $retdata = z_fetch_url($url);
1311 if ($retdata["success"]) {
1312 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1313 $success = poco_discover_server(json_decode($retdata["body"]));
1316 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1317 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1318 poco_discover_server_users($data, $server);
1322 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1323 if (!$complete AND (--$no_of_queries == 0))
1326 // If the server hadn't replied correctly, then force a sanity check
1327 poco_check_server($server["url"], $server["network"], true);
1329 // If we couldn't reach the server, we will try it some time later
1330 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1335 function poco_discover_server_users($data, $server) {
1337 if (!isset($data->entry))
1340 foreach ($data->entry AS $entry) {
1342 if (isset($entry->urls)) {
1343 foreach($entry->urls as $url)
1344 if ($url->type == 'profile') {
1345 $profile_url = $url->value;
1346 $urlparts = parse_url($profile_url);
1347 $username = end(explode("/", $urlparts["path"]));
1350 if ($username != "") {
1351 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1353 // Fetch all contacts from a given user from the other server
1354 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1356 $retdata = z_fetch_url($url);
1357 if ($retdata["success"])
1358 poco_discover_server(json_decode($retdata["body"]), 3);
1363 function poco_discover_server($data, $default_generation = 0) {
1365 if (!isset($data->entry) OR !count($data->entry))
1370 foreach ($data->entry AS $entry) {
1372 $profile_photo = '';
1376 $updated = '0000-00-00 00:00:00';
1382 $generation = $default_generation;
1384 $name = $entry->displayName;
1386 if (isset($entry->urls)) {
1387 foreach($entry->urls as $url) {
1388 if ($url->type == 'profile') {
1389 $profile_url = $url->value;
1392 if ($url->type == 'webfinger') {
1393 $connect_url = str_replace('acct:' , '', $url->value);
1399 if (isset($entry->photos)) {
1400 foreach ($entry->photos as $photo) {
1401 if ($photo->type == 'profile') {
1402 $profile_photo = $photo->value;
1408 if (isset($entry->updated)) {
1409 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1412 if(isset($entry->network)) {
1413 $network = $entry->network;
1416 if(isset($entry->currentLocation)) {
1417 $location = $entry->currentLocation;
1420 if(isset($entry->aboutMe)) {
1421 $about = html2bbcode($entry->aboutMe);
1424 if(isset($entry->gender)) {
1425 $gender = $entry->gender;
1428 if(isset($entry->generation) AND ($entry->generation > 0)) {
1429 $generation = ++$entry->generation;
1432 if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
1433 $contact_type = $entry->contactType;
1436 if(isset($entry->tags)) {
1437 foreach ($entry->tags as $tag) {
1438 $keywords = implode(", ", $tag);
1442 if ($generation > 0) {
1445 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1446 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1448 $gcontact = array("url" => $profile_url, "contact-type" => $contact_type, "generation" => $generation);
1449 update_gcontact($gcontact);
1451 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1458 * @brief Removes unwanted parts from a contact url
1460 * @param string $url Contact url
1461 * @return string Contact url with the wanted parts
1463 function clean_contact_url($url) {
1464 $parts = parse_url($url);
1466 if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1469 $new_url = $parts["scheme"]."://".$parts["host"];
1471 if (isset($parts["port"]))
1472 $new_url .= ":".$parts["port"];
1474 if (isset($parts["path"]))
1475 $new_url .= $parts["path"];
1477 if ($new_url != $url)
1478 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1484 * @brief Replace alternate OStatus user format with the primary one
1486 * @param arr $contact contact array (called by reference)
1488 function fix_alternate_contact_address(&$contact) {
1489 if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1490 $data = probe_url($contact["url"]);
1491 if ($contact["network"] == NETWORK_OSTATUS) {
1492 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1493 $contact["url"] = $data["url"];
1494 $contact["addr"] = $data["addr"];
1495 $contact["alias"] = $data["alias"];
1496 $contact["server_url"] = $data["baseurl"];
1502 * @brief Fetch the gcontact id, add an entry if not existed
1504 * @param arr $contact contact array
1505 * @return bool|int Returns false if not found, integer if contact was found
1507 function get_gcontact_id($contact) {
1512 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1513 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1517 if ($contact["network"] == NETWORK_STATUSNET)
1518 $contact["network"] = NETWORK_OSTATUS;
1520 // All new contacts are hidden by default
1521 if (!isset($contact["hide"]))
1522 $contact["hide"] = true;
1524 // Replace alternate OStatus user format with the primary one
1525 fix_alternate_contact_address($contact);
1527 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1528 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1529 $contact["url"] = clean_contact_url($contact["url"]);
1531 $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1532 dbesc(normalise_link($contact["url"])));
1535 $gcontact_id = $r[0]["id"];
1537 // Update every 90 days
1538 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
1539 $last_failure_str = $r[0]["last_failure"];
1540 $last_failure = strtotime($r[0]["last_failure"]);
1541 $last_contact_str = $r[0]["last_contact"];
1542 $last_contact = strtotime($r[0]["last_contact"]);
1543 $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
1546 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
1547 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
1548 dbesc($contact["name"]),
1549 dbesc($contact["nick"]),
1550 dbesc($contact["addr"]),
1551 dbesc($contact["network"]),
1552 dbesc($contact["url"]),
1553 dbesc(normalise_link($contact["url"])),
1554 dbesc($contact["photo"]),
1555 dbesc(datetime_convert()),
1556 dbesc(datetime_convert()),
1557 dbesc($contact["location"]),
1558 dbesc($contact["about"]),
1559 intval($contact["hide"]),
1560 intval($contact["generation"])
1563 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1564 dbesc(normalise_link($contact["url"])));
1567 $gcontact_id = $r[0]["id"];
1569 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
1574 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
1575 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
1578 if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1579 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1580 dbesc(normalise_link($contact["url"])),
1581 intval($gcontact_id));
1583 return $gcontact_id;
1587 * @brief Updates the gcontact table from a given array
1589 * @param arr $contact contact array
1590 * @return bool|int Returns false if not found, integer if contact was found
1592 function update_gcontact($contact) {
1594 /// @todo update contact table as well
1596 $gcontact_id = get_gcontact_id($contact);
1601 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1602 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1603 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1604 intval($gcontact_id));
1606 // Get all field names
1608 foreach ($r[0] AS $field => $data)
1609 $fields[$field] = $data;
1611 unset($fields["url"]);
1612 unset($fields["updated"]);
1613 unset($fields["hide"]);
1615 // Bugfix: We had an error in the storing of keywords which lead to the "0"
1616 // This value is still transmitted via poco.
1617 if ($contact["keywords"] == "0")
1618 unset($contact["keywords"]);
1620 if ($r[0]["keywords"] == "0")
1621 $r[0]["keywords"] = "";
1623 // assign all unassigned fields from the database entry
1624 foreach ($fields AS $field => $data)
1625 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1626 $contact[$field] = $r[0][$field];
1628 if (!isset($contact["hide"]))
1629 $contact["hide"] = $r[0]["hide"];
1631 $fields["hide"] = $r[0]["hide"];
1633 if ($contact["network"] == NETWORK_STATUSNET)
1634 $contact["network"] = NETWORK_OSTATUS;
1636 // Replace alternate OStatus user format with the primary one
1637 fix_alternate_contact_address($contact);
1639 if (!isset($contact["updated"]))
1640 $contact["updated"] = datetime_convert();
1642 if ($contact["server_url"] == "") {
1643 $server_url = $contact["url"];
1645 $server_url = matching_url($server_url, $contact["alias"]);
1646 if ($server_url != "")
1647 $contact["server_url"] = $server_url;
1649 $server_url = matching_url($server_url, $contact["photo"]);
1650 if ($server_url != "")
1651 $contact["server_url"] = $server_url;
1653 $server_url = matching_url($server_url, $contact["notify"]);
1654 if ($server_url != "")
1655 $contact["server_url"] = $server_url;
1657 $contact["server_url"] = normalise_link($contact["server_url"]);
1659 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1660 $hostname = str_replace("http://", "", $contact["server_url"]);
1661 $contact["addr"] = $contact["nick"]."@".$hostname;
1664 // Check if any field changed
1666 unset($fields["generation"]);
1668 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1669 foreach ($fields AS $field => $data)
1670 if ($contact[$field] != $r[0][$field]) {
1671 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1675 if ($contact["generation"] < $r[0]["generation"]) {
1676 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1682 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
1684 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1685 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1686 `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
1687 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1688 `server_url` = '%s', `connect` = '%s'
1689 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1690 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1691 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1692 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1693 intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
1694 dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
1695 dbesc($contact["about"]), intval($contact["generation"]), dbesc($contact["updated"]),
1696 dbesc($contact["server_url"]), dbesc($contact["connect"]),
1697 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1700 // Now update the contact entry with the user id "0" as well.
1701 // This is used for the shadow copies of public items.
1702 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1703 dbesc(normalise_link($contact["url"])));
1706 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1708 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1710 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1711 `network` = '%s', `bd` = '%s', `gender` = '%s',
1712 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
1713 `url` = '%s', `location` = '%s', `about` = '%s'
1715 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1716 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1717 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
1718 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1719 intval($r[0]["id"]));
1723 return $gcontact_id;
1727 * @brief Updates the gcontact entry from probe
1729 * @param str $url profile link
1731 function update_gcontact_from_probe($url) {
1732 $data = probe_url($url);
1734 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
1735 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1739 update_gcontact($data);
1743 * @brief Update the gcontact entry for a given user id
1745 * @param int $uid User ID
1747 function update_gcontact_for_user($uid) {
1748 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
1749 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
1750 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
1751 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
1752 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
1754 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
1755 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
1756 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
1759 $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
1760 "country-name" => $r[0]["country-name"]));
1762 // The "addr" field was added in 3.4.3 so it can be empty for older users
1763 if ($r[0]["addr"] != "")
1764 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
1766 $addr = $r[0]["addr"];
1768 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
1769 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
1770 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
1771 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
1772 "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
1773 "nick" => $r[0]["nickname"], "addr" => $addr,
1774 "connect" => $addr, "server_url" => App::get_baseurl(),
1775 "generation" => 1, "network" => NETWORK_DFRN);
1777 update_gcontact($gcontact);
1781 * @brief Fetches users of given GNU Social server
1783 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1785 * @param str $server Server address
1787 function gs_fetch_users($server) {
1789 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1791 $url = $server."/main/statistics";
1793 $result = z_fetch_url($url);
1794 if (!$result["success"])
1797 $statistics = json_decode($result["body"]);
1799 if (is_object($statistics->config)) {
1800 if ($statistics->config->instance_with_ssl)
1801 $server = "https://";
1803 $server = "http://";
1805 $server .= $statistics->config->instance_address;
1807 $hostname = $statistics->config->instance_address;
1809 if ($statistics->instance_with_ssl)
1810 $server = "https://";
1812 $server = "http://";
1814 $server .= $statistics->instance_address;
1816 $hostname = $statistics->instance_address;
1819 if (is_object($statistics->users))
1820 foreach ($statistics->users AS $nick => $user) {
1821 $profile_url = $server."/".$user->nickname;
1823 $contact = array("url" => $profile_url,
1824 "name" => $user->fullname,
1825 "addr" => $user->nickname."@".$hostname,
1826 "nick" => $user->nickname,
1827 "about" => $user->bio,
1828 "network" => NETWORK_OSTATUS,
1829 "photo" => App::get_baseurl()."/images/person-175.jpg");
1830 get_gcontact_id($contact);
1835 * @brief Asking GNU Social server on a regular base for their user data
1838 function gs_discover() {
1840 $requery_days = intval(get_config("system", "poco_requery_days"));
1842 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1844 $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",
1845 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1850 foreach ($r AS $server) {
1851 gs_fetch_users($server["url"]);
1852 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));