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));
118 if(isset($entry->network))
119 $network = $entry->network;
121 if(isset($entry->currentLocation))
122 $location = $entry->currentLocation;
124 if(isset($entry->aboutMe))
125 $about = html2bbcode($entry->aboutMe);
127 if(isset($entry->gender))
128 $gender = $entry->gender;
130 if(isset($entry->generation) AND ($entry->generation > 0))
131 $generation = ++$entry->generation;
133 if(isset($entry->tags))
134 foreach($entry->tags as $tag)
135 $keywords = implode(", ", $tag);
137 if(isset($entry->contactType) AND ($entry->contactType >= 0))
138 $contact_type = $entry->contactType;
140 // If you query a Friendica server for its profiles, the network has to be Friendica
141 /// TODO It could also be a Redmatrix server
143 // $network = NETWORK_DFRN;
145 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
147 $gcontact = array("url" => $profile_url, "contact-type" => $contact_type, "generation" => $generation);
148 update_gcontact($gcontact);
150 // Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
151 // Deactivated because we now update Friendica contacts in dfrn.php
152 //if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
153 // q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
154 // WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
159 // dbesc(normalise_link($profile_url)),
160 // dbesc(NETWORK_DFRN));
162 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
164 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
172 function poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid = 0, $uid = 0, $zcid = 0) {
178 // 1: Profiles on this server
179 // 2: Contacts of profiles on this server
180 // 3: Contacts of contacts of profiles on this server
185 if ($profile_url == "")
188 $urlparts = parse_url($profile_url);
189 if (!isset($urlparts["scheme"]))
192 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
193 "identi.ca", "alpha.app.net")))
196 // Don't store the statusnet connector as network
197 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
198 if ($network == NETWORK_STATUSNET)
201 // Assure that there are no parameter fragments in the profile url
202 if (in_array($network, array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
203 $profile_url = clean_contact_url($profile_url);
205 $alternate = poco_alternate_ostatus_url($profile_url);
207 $orig_updated = $updated;
209 // The global contacts should contain the original picture, not the cached one
210 if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link(App::get_baseurl()."/photo/"))) {
214 $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
215 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
217 if (dbm::is_result($r))
218 $network = $r[0]["network"];
220 if (($network == "") OR ($network == NETWORK_OSTATUS)) {
221 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
222 dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
224 if (dbm::is_result($r)) {
225 $network = $r[0]["network"];
226 //$profile_url = $r[0]["url"];
230 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
231 dbesc(normalise_link($profile_url))
235 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
236 $network = $x[0]["network"];
238 if ($updated == "0000-00-00 00:00:00")
239 $updated = $x[0]["updated"];
241 $created = $x[0]["created"];
242 $server_url = $x[0]["server_url"];
243 $nick = $x[0]["nick"];
244 $addr = $x[0]["addr"];
245 $alias = $x[0]["alias"];
246 $notify = $x[0]["notify"];
248 $created = "0000-00-00 00:00:00";
251 $urlparts = parse_url($profile_url);
252 $nick = end(explode("/", $urlparts["path"]));
258 if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
259 AND poco_reachable($profile_url, $server_url, $network, false)) {
260 $data = probe_url($profile_url);
262 $orig_profile = $profile_url;
264 $network = $data["network"];
265 $name = $data["name"];
266 $nick = $data["nick"];
267 $addr = $data["addr"];
268 $alias = $data["alias"];
269 $notify = $data["notify"];
270 $profile_url = $data["url"];
271 $profile_photo = $data["photo"];
272 $server_url = $data["baseurl"];
274 if ($alternate AND ($network == NETWORK_OSTATUS)) {
275 // Delete the old entry - if it exists
276 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
278 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
279 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
282 // possibly create a new entry
283 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
287 if ($alternate AND ($network == NETWORK_OSTATUS))
290 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
291 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
293 dbesc(normalise_link($profile_url))
297 if (($name == "") OR ($profile_photo == ""))
300 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
303 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
305 poco_check_server($server_url, $network);
307 $gcontact = array("url" => $profile_url,
311 "network" => $network,
312 "photo" => $profile_photo,
314 "location" => $location,
316 "keywords" => $keywords,
317 "server_url" => $server_url,
318 "connect" => $connect_url,
320 "updated" => $updated,
321 "generation" => $generation);
323 $gcid = update_gcontact($gcontact);
328 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
334 if (! dbm::is_result($r)) {
335 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
340 dbesc(datetime_convert())
343 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
344 dbesc(datetime_convert()),
355 function poco_reachable($profile, $server = "", $network = "", $force = false) {
358 $server = poco_detect_server($profile);
363 return poco_check_server($server, $network, $force);
366 function poco_detect_server($profile) {
368 // Try to detect the server path based upon some known standard paths
371 if ($server_url == "") {
372 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
373 if ($friendica != $profile) {
374 $server_url = $friendica;
375 $network = NETWORK_DFRN;
379 if ($server_url == "") {
380 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
381 if ($diaspora != $profile) {
382 $server_url = $diaspora;
383 $network = NETWORK_DIASPORA;
387 if ($server_url == "") {
388 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
389 if ($red != $profile) {
391 $network = NETWORK_DIASPORA;
396 if ($server_url == "") {
397 $red = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
398 if ($red != $profile) {
400 $network = NETWORK_OSTATUS;
407 function poco_alternate_ostatus_url($url) {
408 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
411 function poco_last_updated($profile, $force = false) {
413 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
414 dbesc(normalise_link($profile)));
416 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
417 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
418 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
420 if ($gcontacts[0]["server_url"] != "")
421 $server_url = $gcontacts[0]["server_url"];
423 $server_url = poco_detect_server($profile);
425 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
426 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
430 if ($server_url != "") {
431 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
434 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
435 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
437 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
441 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
442 dbesc($server_url), dbesc(normalise_link($profile)));
445 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
446 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
447 dbesc(normalise_link($server_url)));
450 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
451 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
456 // noscrape is really fast so we don't cache the call.
457 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
459 // Use noscrape if possible
460 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
463 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
465 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
467 $noscrape = json_decode($noscraperet["body"], true);
469 if (is_array($noscrape)) {
470 $contact = array("url" => $profile,
471 "network" => $server[0]["network"],
472 "generation" => $gcontacts[0]["generation"]);
474 if (isset($noscrape["fn"]))
475 $contact["name"] = $noscrape["fn"];
477 if (isset($noscrape["comm"]))
478 $contact["community"] = $noscrape["comm"];
480 if (isset($noscrape["tags"])) {
481 $keywords = implode(" ", $noscrape["tags"]);
483 $contact["keywords"] = $keywords;
486 $location = formatted_location($noscrape);
488 $contact["location"] = $location;
490 if (isset($noscrape["dfrn-notify"]))
491 $contact["notify"] = $noscrape["dfrn-notify"];
493 // Remove all fields that are not present in the gcontact table
494 unset($noscrape["fn"]);
495 unset($noscrape["key"]);
496 unset($noscrape["homepage"]);
497 unset($noscrape["comm"]);
498 unset($noscrape["tags"]);
499 unset($noscrape["locality"]);
500 unset($noscrape["region"]);
501 unset($noscrape["country-name"]);
502 unset($noscrape["contacts"]);
503 unset($noscrape["dfrn-request"]);
504 unset($noscrape["dfrn-confirm"]);
505 unset($noscrape["dfrn-notify"]);
506 unset($noscrape["dfrn-poll"]);
508 // Set the date of the last contact
509 /// @todo By now the function "update_gcontact" doesn't work with this field
510 //$contact["last_contact"] = datetime_convert();
512 $contact = array_merge($contact, $noscrape);
514 update_gcontact($contact);
516 if (trim($noscrape["updated"]) != "") {
517 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
518 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
520 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
522 return $noscrape["updated"];
529 // If we only can poll the feed, then we only do this once a while
530 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
531 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
532 return $gcontacts[0]["updated"];
535 $data = probe_url($profile);
537 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
538 // Then check the other link and delete this one
539 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
540 (normalise_link($profile) == normalise_link($data["alias"])) AND
541 (normalise_link($profile) != normalise_link($data["url"]))) {
543 // Delete the old entry
544 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
545 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
547 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
548 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
550 poco_last_updated($data["url"], $force);
552 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
556 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
557 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
558 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
560 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
564 $contact = array("generation" => $gcontacts[0]["generation"]);
566 $contact = array_merge($contact, $data);
568 $contact["server_url"] = $data["baseurl"];
570 unset($contact["batch"]);
571 unset($contact["poll"]);
572 unset($contact["request"]);
573 unset($contact["confirm"]);
574 unset($contact["poco"]);
575 unset($contact["priority"]);
576 unset($contact["pubkey"]);
577 unset($contact["baseurl"]);
579 update_gcontact($contact);
581 $feedret = z_fetch_url($data["poll"]);
583 if (!$feedret["success"]) {
584 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
585 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
587 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
591 $doc = new DOMDocument();
592 @$doc->loadXML($feedret["body"]);
594 $xpath = new DomXPath($doc);
595 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
597 $entries = $xpath->query('/atom:feed/atom:entry');
601 foreach ($entries AS $entry) {
602 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
603 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
605 if ($last_updated < $published)
606 $last_updated = $published;
608 if ($last_updated < $updated)
609 $last_updated = $updated;
612 // Maybe there aren't any entries. Then check if it is a valid feed
613 if ($last_updated == "")
614 if ($xpath->query('/atom:feed')->length > 0)
615 $last_updated = "0000-00-00 00:00:00";
617 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
618 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
620 if (($gcontacts[0]["generation"] == 0))
621 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
622 dbesc(normalise_link($profile)));
624 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
626 return($last_updated);
629 function poco_do_update($created, $updated, $last_failure, $last_contact) {
630 $now = strtotime(datetime_convert());
632 if ($updated > $last_contact)
633 $contact_time = strtotime($updated);
635 $contact_time = strtotime($last_contact);
637 $failure_time = strtotime($last_failure);
638 $created_time = strtotime($created);
640 // If there is no "created" time then use the current time
641 if ($created_time <= 0)
642 $created_time = $now;
644 // If the last contact was less than 24 hours then don't update
645 if (($now - $contact_time) < (60 * 60 * 24))
648 // If the last failure was less than 24 hours then don't update
649 if (($now - $failure_time) < (60 * 60 * 24))
652 // If the last contact was less than a week ago and the last failure is older than a week then don't update
653 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
656 // 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
657 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
660 // 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
661 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
667 function poco_to_boolean($val) {
668 if (($val == "true") OR ($val == 1))
670 if (($val == "false") OR ($val == 0))
676 function poco_check_server($server_url, $network = "", $force = false) {
678 // Unify the server address
679 $server_url = trim($server_url, "/");
680 $server_url = str_replace("/index.php", "", $server_url);
682 if ($server_url == "")
685 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
688 if ($servers[0]["created"] == "0000-00-00 00:00:00")
689 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
690 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
692 $poco = $servers[0]["poco"];
693 $noscrape = $servers[0]["noscrape"];
696 $network = $servers[0]["network"];
698 $last_contact = $servers[0]["last_contact"];
699 $last_failure = $servers[0]["last_failure"];
700 $version = $servers[0]["version"];
701 $platform = $servers[0]["platform"];
702 $site_name = $servers[0]["site_name"];
703 $info = $servers[0]["info"];
704 $register_policy = $servers[0]["register_policy"];
706 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
707 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
708 return ($last_contact >= $last_failure);
717 $register_policy = -1;
719 $last_contact = "0000-00-00 00:00:00";
720 $last_failure = "0000-00-00 00:00:00";
722 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
725 $orig_last_failure = $last_failure;
727 // Check if the page is accessible via SSL.
728 $server_url = str_replace("http://", "https://", $server_url);
729 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
731 // Maybe the page is unencrypted only?
732 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
733 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
734 $server_url = str_replace("https://", "http://", $server_url);
735 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
737 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
740 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
741 // Workaround for bad configured servers (known nginx problem)
742 if ($serverret["debug"]["http_code"] != "403") {
743 $last_failure = datetime_convert();
746 } elseif ($network == NETWORK_DIASPORA)
747 $last_contact = datetime_convert();
751 $serverret = z_fetch_url($server_url);
753 if (!$serverret["success"] OR ($serverret["body"] == ""))
756 $lines = explode("\n",$serverret["header"]);
758 foreach($lines as $line) {
760 if(stristr($line,'X-Diaspora-Version:')) {
761 $platform = "Diaspora";
762 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
763 $version = trim(str_replace("x-diaspora-version:", "", $version));
764 $network = NETWORK_DIASPORA;
765 $versionparts = explode("-", $version);
766 $version = $versionparts[0];
769 if(stristr($line,'Server: Mastodon')) {
770 $platform = "Mastodon";
771 $network = NETWORK_OSTATUS;
772 // Mastodon doesn't reveal version numbers
780 // Test for Statusnet
781 // Will also return data for Friendica and GNU Social - but it will be overwritten later
782 // The "not implemented" is a special treatment for really, really old Friendica versions
783 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
784 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
785 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
786 $platform = "StatusNet";
787 $version = trim($serverret["body"], '"');
788 $network = NETWORK_OSTATUS;
791 // Test for GNU Social
792 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
793 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
794 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
795 $platform = "GNU Social";
796 $version = trim($serverret["body"], '"');
797 $network = NETWORK_OSTATUS;
800 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
801 if ($serverret["success"]) {
802 $data = json_decode($serverret["body"]);
804 if (isset($data->site->server)) {
805 $last_contact = datetime_convert();
807 if (isset($data->site->hubzilla)) {
808 $platform = $data->site->hubzilla->PLATFORM_NAME;
809 $version = $data->site->hubzilla->RED_VERSION;
810 $network = NETWORK_DIASPORA;
812 if (isset($data->site->redmatrix)) {
813 if (isset($data->site->redmatrix->PLATFORM_NAME))
814 $platform = $data->site->redmatrix->PLATFORM_NAME;
815 elseif (isset($data->site->redmatrix->RED_PLATFORM))
816 $platform = $data->site->redmatrix->RED_PLATFORM;
818 $version = $data->site->redmatrix->RED_VERSION;
819 $network = NETWORK_DIASPORA;
821 if (isset($data->site->friendica)) {
822 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
823 $version = $data->site->friendica->FRIENDICA_VERSION;
824 $network = NETWORK_DFRN;
827 $site_name = $data->site->name;
829 $data->site->closed = poco_to_boolean($data->site->closed);
830 $data->site->private = poco_to_boolean($data->site->private);
831 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
833 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
834 $register_policy = REGISTER_APPROVE;
835 elseif (!$data->site->closed AND !$data->site->private)
836 $register_policy = REGISTER_OPEN;
838 $register_policy = REGISTER_CLOSED;
843 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
845 $serverret = z_fetch_url($server_url."/statistics.json");
846 if ($serverret["success"]) {
847 $data = json_decode($serverret["body"]);
849 $version = $data->version;
851 $site_name = $data->name;
853 if (isset($data->network) AND ($platform == ""))
854 $platform = $data->network;
856 if ($platform == "Diaspora")
857 $network = NETWORK_DIASPORA;
859 if ($data->registrations_open)
860 $register_policy = REGISTER_OPEN;
862 $register_policy = REGISTER_CLOSED;
864 if (isset($data->version))
865 $last_contact = datetime_convert();
869 // Check for noscrape
870 // Friendica servers could be detected as OStatus servers
871 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
872 $serverret = z_fetch_url($server_url."/friendica/json");
874 if (!$serverret["success"])
875 $serverret = z_fetch_url($server_url."/friendika/json");
877 if ($serverret["success"]) {
878 $data = json_decode($serverret["body"]);
880 if (isset($data->version)) {
881 $last_contact = datetime_convert();
882 $network = NETWORK_DFRN;
884 $noscrape = $data->no_scrape_url;
885 $version = $data->version;
886 $site_name = $data->site_name;
888 $register_policy_str = $data->register_policy;
889 $platform = $data->platform;
891 switch ($register_policy_str) {
892 case "REGISTER_CLOSED":
893 $register_policy = REGISTER_CLOSED;
895 case "REGISTER_APPROVE":
896 $register_policy = REGISTER_APPROVE;
898 case "REGISTER_OPEN":
899 $register_policy = REGISTER_OPEN;
908 $serverret = z_fetch_url($server_url."/poco");
909 if ($serverret["success"]) {
910 $data = json_decode($serverret["body"]);
911 if (isset($data->totalResults)) {
912 $poco = $server_url."/poco";
913 $last_contact = datetime_convert();
918 // Check again if the server exists
919 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
921 $version = strip_tags($version);
922 $site_name = strip_tags($site_name);
923 $info = strip_tags($info);
924 $platform = strip_tags($platform);
927 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
928 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
933 intval($register_policy),
938 dbesc($last_contact),
939 dbesc($last_failure),
940 dbesc(normalise_link($server_url))
943 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
944 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
946 dbesc(normalise_link($server_url)),
950 intval($register_policy),
955 dbesc(datetime_convert()),
956 dbesc($last_contact),
957 dbesc($last_failure),
958 dbesc(datetime_convert())
961 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
966 function count_common_friends($uid,$cid) {
968 $r = q("SELECT count(*) as `total`
969 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
970 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
971 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
972 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
979 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
980 if (dbm::is_result($r))
981 return $r[0]['total'];
987 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
990 $sql_extra = " order by rand() ";
992 $sql_extra = " order by `gcontact`.`name` asc ";
994 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
996 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
997 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
998 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
999 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1000 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1001 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1002 $sql_extra LIMIT %d, %d",
1016 function count_common_friends_zcid($uid,$zcid) {
1018 $r = q("SELECT count(*) as `total`
1019 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1020 where `glink`.`zcid` = %d
1021 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1026 if (dbm::is_result($r))
1027 return $r[0]['total'];
1032 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1035 $sql_extra = " order by rand() ";
1037 $sql_extra = " order by `gcontact`.`name` asc ";
1039 $r = q("SELECT `gcontact`.*
1040 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1041 where `glink`.`zcid` = %d
1042 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1043 $sql_extra limit %d, %d",
1055 function count_all_friends($uid,$cid) {
1057 $r = q("SELECT count(*) as `total`
1058 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1059 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1060 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1065 if (dbm::is_result($r))
1066 return $r[0]['total'];
1072 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1074 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1076 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1077 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1078 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1079 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1080 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1093 function suggestion_query($uid, $start = 0, $limit = 80) {
1099 // Uncommented because the result of the queries are to big to store it in the cache.
1100 // We need to decide if we want to change the db column type or if we want to delete it.
1101 // $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1102 // if (!is_null($list)) {
1106 $network = array(NETWORK_DFRN);
1108 if (get_config('system','diaspora_enabled'))
1109 $network[] = NETWORK_DIASPORA;
1111 if (!get_config('system','ostatus_disabled'))
1112 $network[] = NETWORK_OSTATUS;
1114 $sql_network = implode("', '", $network);
1115 $sql_network = "'".$sql_network."'";
1117 /// @todo This query is really slow
1118 // By now we cache the data for five minutes
1119 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1120 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1121 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1122 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1123 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1124 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1125 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1126 AND `gcontact`.`network` IN (%s)
1127 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1137 if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1138 // Uncommented because the result of the queries are to big to store it in the cache.
1139 // We need to decide if we want to change the db column type or if we want to delete it.
1140 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1145 $r2 = q("SELECT gcontact.* FROM gcontact
1146 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1147 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1148 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1149 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1150 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1151 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1152 AND `gcontact`.`network` IN (%s)
1153 ORDER BY rand() LIMIT %d, %d",
1163 foreach ($r2 AS $suggestion)
1164 $list[$suggestion["nurl"]] = $suggestion;
1166 foreach ($r AS $suggestion)
1167 $list[$suggestion["nurl"]] = $suggestion;
1169 while (sizeof($list) > ($limit))
1172 // Uncommented because the result of the queries are to big to store it in the cache.
1173 // We need to decide if we want to change the db column type or if we want to delete it.
1174 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1178 function update_suggestions() {
1184 /// TODO Check if it is really neccessary to poll the own server
1185 poco_load(0,0,0,App::get_baseurl() . '/poco');
1187 $done[] = App::get_baseurl() . '/poco';
1189 if(strlen(get_config('system','directory'))) {
1190 $x = fetch_url(get_server()."/pubsites");
1192 $j = json_decode($x);
1194 foreach($j->entries as $entry) {
1196 poco_check_server($entry->url);
1198 $url = $entry->url . '/poco';
1199 if (! in_array($url,$done)) {
1200 poco_load(0,0,0,$entry->url . '/poco');
1207 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1208 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1209 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1212 if (dbm::is_result($r)) {
1213 foreach($r as $rr) {
1214 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1215 if(! in_array($base,$done))
1216 poco_load(0,0,0,$base);
1221 function poco_discover_federation() {
1222 $last = get_config('poco','last_federation_discovery');
1225 $next = $last + (24 * 60 * 60);
1230 // Discover Friendica, Hubzilla and Diaspora servers
1231 $serverdata = fetch_url("http://the-federation.info/pods.json");
1234 $servers = json_decode($serverdata);
1236 foreach($servers->pods AS $server)
1237 poco_check_server("https://".$server->host);
1240 // Discover GNU Social Servers
1241 if (!get_config('system','ostatus_disabled')) {
1242 $serverdata = "http://gstools.org/api/get_open_instances/";
1244 $result = z_fetch_url($serverdata);
1245 if ($result["success"]) {
1246 $servers = json_decode($result["body"]);
1248 foreach($servers->data AS $server)
1249 poco_check_server($server->instance_address);
1253 set_config('poco','last_federation_discovery', time());
1256 function poco_discover($complete = false) {
1258 // Update the server list
1259 poco_discover_federation();
1263 $requery_days = intval(get_config("system", "poco_requery_days"));
1265 if ($requery_days == 0)
1268 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1270 $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));
1272 foreach ($r AS $server) {
1274 if (!poco_check_server($server["url"], $server["network"])) {
1275 // The server is not reachable? Okay, then we will try it later
1276 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1280 // Fetch all users from the other server
1281 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1283 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1285 $retdata = z_fetch_url($url);
1286 if ($retdata["success"]) {
1287 $data = json_decode($retdata["body"]);
1289 poco_discover_server($data, 2);
1291 if (get_config('system','poco_discovery') > 1) {
1293 $timeframe = get_config('system','poco_discovery_since');
1294 if ($timeframe == 0)
1297 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1299 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1300 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1304 $retdata = z_fetch_url($url);
1305 if ($retdata["success"]) {
1306 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1307 $success = poco_discover_server(json_decode($retdata["body"]));
1310 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1311 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1312 poco_discover_server_users($data, $server);
1316 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1317 if (!$complete AND (--$no_of_queries == 0))
1320 // If the server hadn't replied correctly, then force a sanity check
1321 poco_check_server($server["url"], $server["network"], true);
1323 // If we couldn't reach the server, we will try it some time later
1324 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1329 function poco_discover_server_users($data, $server) {
1331 if (!isset($data->entry))
1334 foreach ($data->entry AS $entry) {
1336 if (isset($entry->urls)) {
1337 foreach($entry->urls as $url)
1338 if ($url->type == 'profile') {
1339 $profile_url = $url->value;
1340 $urlparts = parse_url($profile_url);
1341 $username = end(explode("/", $urlparts["path"]));
1344 if ($username != "") {
1345 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1347 // Fetch all contacts from a given user from the other server
1348 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1350 $retdata = z_fetch_url($url);
1351 if ($retdata["success"])
1352 poco_discover_server(json_decode($retdata["body"]), 3);
1357 function poco_discover_server($data, $default_generation = 0) {
1359 if (!isset($data->entry) OR !count($data->entry))
1364 foreach ($data->entry AS $entry) {
1366 $profile_photo = '';
1370 $updated = '0000-00-00 00:00:00';
1376 $generation = $default_generation;
1378 $name = $entry->displayName;
1380 if(isset($entry->urls)) {
1381 foreach($entry->urls as $url) {
1382 if ($url->type == 'profile') {
1383 $profile_url = $url->value;
1386 if ($url->type == 'webfinger') {
1387 $connect_url = str_replace('acct:' , '', $url->value);
1393 if(isset($entry->photos)) {
1394 foreach($entry->photos as $photo) {
1395 if($photo->type == 'profile') {
1396 $profile_photo = $photo->value;
1402 if(isset($entry->updated))
1403 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1405 if(isset($entry->network))
1406 $network = $entry->network;
1408 if(isset($entry->currentLocation))
1409 $location = $entry->currentLocation;
1411 if(isset($entry->aboutMe))
1412 $about = html2bbcode($entry->aboutMe);
1414 if(isset($entry->gender))
1415 $gender = $entry->gender;
1417 if(isset($entry->generation) AND ($entry->generation > 0))
1418 $generation = ++$entry->generation;
1420 if(isset($entry->contactType) AND ($entry->contactType >= 0))
1421 $contact_type = $entry->contactType;
1423 if(isset($entry->tags))
1424 foreach($entry->tags as $tag)
1425 $keywords = implode(", ", $tag);
1427 if ($generation > 0) {
1430 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1431 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1433 $gcontact = array("url" => $profile_url, "contact-type" => $contact_type, "generation" => $generation);
1434 update_gcontact($gcontact);
1436 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1443 * @brief Removes unwanted parts from a contact url
1445 * @param string $url Contact url
1446 * @return string Contact url with the wanted parts
1448 function clean_contact_url($url) {
1449 $parts = parse_url($url);
1451 if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1454 $new_url = $parts["scheme"]."://".$parts["host"];
1456 if (isset($parts["port"]))
1457 $new_url .= ":".$parts["port"];
1459 if (isset($parts["path"]))
1460 $new_url .= $parts["path"];
1462 if ($new_url != $url)
1463 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1469 * @brief Replace alternate OStatus user format with the primary one
1471 * @param arr $contact contact array (called by reference)
1473 function fix_alternate_contact_address(&$contact) {
1474 if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1475 $data = probe_url($contact["url"]);
1476 if ($contact["network"] == NETWORK_OSTATUS) {
1477 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1478 $contact["url"] = $data["url"];
1479 $contact["addr"] = $data["addr"];
1480 $contact["alias"] = $data["alias"];
1481 $contact["server_url"] = $data["baseurl"];
1487 * @brief Fetch the gcontact id, add an entry if not existed
1489 * @param arr $contact contact array
1490 * @return bool|int Returns false if not found, integer if contact was found
1492 function get_gcontact_id($contact) {
1497 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1498 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1502 if ($contact["network"] == NETWORK_STATUSNET)
1503 $contact["network"] = NETWORK_OSTATUS;
1505 // All new contacts are hidden by default
1506 if (!isset($contact["hide"]))
1507 $contact["hide"] = true;
1509 // Replace alternate OStatus user format with the primary one
1510 fix_alternate_contact_address($contact);
1512 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1513 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1514 $contact["url"] = clean_contact_url($contact["url"]);
1516 $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1517 dbesc(normalise_link($contact["url"])));
1520 $gcontact_id = $r[0]["id"];
1522 // Update every 90 days
1523 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
1524 $last_failure_str = $r[0]["last_failure"];
1525 $last_failure = strtotime($r[0]["last_failure"]);
1526 $last_contact_str = $r[0]["last_contact"];
1527 $last_contact = strtotime($r[0]["last_contact"]);
1528 $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
1531 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
1532 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
1533 dbesc($contact["name"]),
1534 dbesc($contact["nick"]),
1535 dbesc($contact["addr"]),
1536 dbesc($contact["network"]),
1537 dbesc($contact["url"]),
1538 dbesc(normalise_link($contact["url"])),
1539 dbesc($contact["photo"]),
1540 dbesc(datetime_convert()),
1541 dbesc(datetime_convert()),
1542 dbesc($contact["location"]),
1543 dbesc($contact["about"]),
1544 intval($contact["hide"]),
1545 intval($contact["generation"])
1548 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1549 dbesc(normalise_link($contact["url"])));
1552 $gcontact_id = $r[0]["id"];
1554 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
1559 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
1560 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
1563 if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1564 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1565 dbesc(normalise_link($contact["url"])),
1566 intval($gcontact_id));
1568 return $gcontact_id;
1572 * @brief Updates the gcontact table from a given array
1574 * @param arr $contact contact array
1575 * @return bool|int Returns false if not found, integer if contact was found
1577 function update_gcontact($contact) {
1579 /// @todo update contact table as well
1581 $gcontact_id = get_gcontact_id($contact);
1586 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1587 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1588 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1589 intval($gcontact_id));
1591 // Get all field names
1593 foreach ($r[0] AS $field => $data)
1594 $fields[$field] = $data;
1596 unset($fields["url"]);
1597 unset($fields["updated"]);
1598 unset($fields["hide"]);
1600 // Bugfix: We had an error in the storing of keywords which lead to the "0"
1601 // This value is still transmitted via poco.
1602 if ($contact["keywords"] == "0")
1603 unset($contact["keywords"]);
1605 if ($r[0]["keywords"] == "0")
1606 $r[0]["keywords"] = "";
1608 // assign all unassigned fields from the database entry
1609 foreach ($fields AS $field => $data)
1610 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1611 $contact[$field] = $r[0][$field];
1613 if (!isset($contact["hide"]))
1614 $contact["hide"] = $r[0]["hide"];
1616 $fields["hide"] = $r[0]["hide"];
1618 if ($contact["network"] == NETWORK_STATUSNET)
1619 $contact["network"] = NETWORK_OSTATUS;
1621 // Replace alternate OStatus user format with the primary one
1622 fix_alternate_contact_address($contact);
1624 if (!isset($contact["updated"]))
1625 $contact["updated"] = datetime_convert();
1627 if ($contact["server_url"] == "") {
1628 $server_url = $contact["url"];
1630 $server_url = matching_url($server_url, $contact["alias"]);
1631 if ($server_url != "")
1632 $contact["server_url"] = $server_url;
1634 $server_url = matching_url($server_url, $contact["photo"]);
1635 if ($server_url != "")
1636 $contact["server_url"] = $server_url;
1638 $server_url = matching_url($server_url, $contact["notify"]);
1639 if ($server_url != "")
1640 $contact["server_url"] = $server_url;
1642 $contact["server_url"] = normalise_link($contact["server_url"]);
1644 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1645 $hostname = str_replace("http://", "", $contact["server_url"]);
1646 $contact["addr"] = $contact["nick"]."@".$hostname;
1649 // Check if any field changed
1651 unset($fields["generation"]);
1653 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1654 foreach ($fields AS $field => $data)
1655 if ($contact[$field] != $r[0][$field]) {
1656 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1660 if ($contact["generation"] < $r[0]["generation"]) {
1661 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1667 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
1669 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1670 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1671 `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
1672 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1673 `server_url` = '%s', `connect` = '%s'
1674 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1675 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1676 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1677 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1678 intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
1679 dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
1680 dbesc($contact["about"]), intval($contact["generation"]), dbesc($contact["updated"]),
1681 dbesc($contact["server_url"]), dbesc($contact["connect"]),
1682 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1685 // Now update the contact entry with the user id "0" as well.
1686 // This is used for the shadow copies of public items.
1687 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1688 dbesc(normalise_link($contact["url"])));
1691 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1693 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1695 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1696 `network` = '%s', `bd` = '%s', `gender` = '%s',
1697 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
1698 `url` = '%s', `location` = '%s', `about` = '%s'
1700 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1701 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1702 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
1703 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1704 intval($r[0]["id"]));
1708 return $gcontact_id;
1712 * @brief Updates the gcontact entry from probe
1714 * @param str $url profile link
1716 function update_gcontact_from_probe($url) {
1717 $data = probe_url($url);
1719 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
1720 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1724 update_gcontact($data);
1728 * @brief Update the gcontact entry for a given user id
1730 * @param int $uid User ID
1732 function update_gcontact_for_user($uid) {
1733 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
1734 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
1735 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
1736 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
1737 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
1739 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
1740 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
1741 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
1744 $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
1745 "country-name" => $r[0]["country-name"]));
1747 // The "addr" field was added in 3.4.3 so it can be empty for older users
1748 if ($r[0]["addr"] != "")
1749 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
1751 $addr = $r[0]["addr"];
1753 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
1754 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
1755 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
1756 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
1757 "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
1758 "nick" => $r[0]["nickname"], "addr" => $addr,
1759 "connect" => $addr, "server_url" => App::get_baseurl(),
1760 "generation" => 1, "network" => NETWORK_DFRN);
1762 update_gcontact($gcontact);
1766 * @brief Fetches users of given GNU Social server
1768 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1770 * @param str $server Server address
1772 function gs_fetch_users($server) {
1774 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1776 $url = $server."/main/statistics";
1778 $result = z_fetch_url($url);
1779 if (!$result["success"])
1782 $statistics = json_decode($result["body"]);
1784 if (is_object($statistics->config)) {
1785 if ($statistics->config->instance_with_ssl)
1786 $server = "https://";
1788 $server = "http://";
1790 $server .= $statistics->config->instance_address;
1792 $hostname = $statistics->config->instance_address;
1794 if ($statistics->instance_with_ssl)
1795 $server = "https://";
1797 $server = "http://";
1799 $server .= $statistics->instance_address;
1801 $hostname = $statistics->instance_address;
1804 if (is_object($statistics->users))
1805 foreach ($statistics->users AS $nick => $user) {
1806 $profile_url = $server."/".$user->nickname;
1808 $contact = array("url" => $profile_url,
1809 "name" => $user->fullname,
1810 "addr" => $user->nickname."@".$hostname,
1811 "nick" => $user->nickname,
1812 "about" => $user->bio,
1813 "network" => NETWORK_OSTATUS,
1814 "photo" => App::get_baseurl()."/images/person-175.jpg");
1815 get_gcontact_id($contact);
1820 * @brief Asking GNU Social server on a regular base for their user data
1823 function gs_discover() {
1825 $requery_days = intval(get_config("system", "poco_requery_days"));
1827 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1829 $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",
1830 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1835 foreach ($r AS $server) {
1836 gs_fetch_users($server["url"]);
1837 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));