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",
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($a->get_baseurl()."/photo/")))
213 $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
214 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
217 $network = $r[0]["network"];
219 if (($network == "") OR ($network == NETWORK_OSTATUS)) {
220 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
221 dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
224 $network = $r[0]["network"];
225 //$profile_url = $r[0]["url"];
229 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
230 dbesc(normalise_link($profile_url))
234 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
235 $network = $x[0]["network"];
237 if ($updated == "0000-00-00 00:00:00")
238 $updated = $x[0]["updated"];
240 $created = $x[0]["created"];
241 $server_url = $x[0]["server_url"];
242 $nick = $x[0]["nick"];
243 $addr = $x[0]["addr"];
244 $alias = $x[0]["alias"];
245 $notify = $x[0]["notify"];
247 $created = "0000-00-00 00:00:00";
250 $urlparts = parse_url($profile_url);
251 $nick = end(explode("/", $urlparts["path"]));
257 if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
258 AND poco_reachable($profile_url, $server_url, $network, false)) {
259 $data = probe_url($profile_url);
261 $orig_profile = $profile_url;
263 $network = $data["network"];
264 $name = $data["name"];
265 $nick = $data["nick"];
266 $addr = $data["addr"];
267 $alias = $data["alias"];
268 $notify = $data["notify"];
269 $profile_url = $data["url"];
270 $profile_photo = $data["photo"];
271 $server_url = $data["baseurl"];
273 if ($alternate AND ($network == NETWORK_OSTATUS)) {
274 // Delete the old entry - if it exists
275 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
277 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
278 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
281 // possibly create a new entry
282 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
286 if ($alternate AND ($network == NETWORK_OSTATUS))
289 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
290 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
292 dbesc(normalise_link($profile_url))
296 if (($name == "") OR ($profile_photo == ""))
299 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
302 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
304 poco_check_server($server_url, $network);
306 $gcontact = array("url" => $profile_url,
310 "network" => $network,
311 "photo" => $profile_photo,
313 "location" => $location,
315 "keywords" => $keywords,
316 "server_url" => $server_url,
317 "connect" => $connect_url,
319 "updated" => $updated,
320 "generation" => $generation);
322 $gcid = update_gcontact($gcontact);
327 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
334 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
339 dbesc(datetime_convert())
342 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
343 dbesc(datetime_convert()),
354 function poco_reachable($profile, $server = "", $network = "", $force = false) {
357 $server = poco_detect_server($profile);
362 return poco_check_server($server, $network, $force);
365 function poco_detect_server($profile) {
367 // Try to detect the server path based upon some known standard paths
370 if ($server_url == "") {
371 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
372 if ($friendica != $profile) {
373 $server_url = $friendica;
374 $network = NETWORK_DFRN;
378 if ($server_url == "") {
379 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
380 if ($diaspora != $profile) {
381 $server_url = $diaspora;
382 $network = NETWORK_DIASPORA;
386 if ($server_url == "") {
387 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
388 if ($red != $profile) {
390 $network = NETWORK_DIASPORA;
395 if ($server_url == "") {
396 $red = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
397 if ($red != $profile) {
399 $network = NETWORK_OSTATUS;
406 function poco_alternate_ostatus_url($url) {
407 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
410 function poco_last_updated($profile, $force = false) {
412 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
413 dbesc(normalise_link($profile)));
415 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
416 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
417 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
419 if ($gcontacts[0]["server_url"] != "")
420 $server_url = $gcontacts[0]["server_url"];
422 $server_url = poco_detect_server($profile);
424 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
425 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
429 if ($server_url != "") {
430 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
433 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
434 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
436 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
440 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
441 dbesc($server_url), dbesc(normalise_link($profile)));
444 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
445 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
446 dbesc(normalise_link($server_url)));
449 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
450 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
455 // noscrape is really fast so we don't cache the call.
456 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
458 // Use noscrape if possible
459 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
462 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
464 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
466 $noscrape = json_decode($noscraperet["body"], true);
468 if (is_array($noscrape)) {
469 $contact = array("url" => $profile,
470 "network" => $server[0]["network"],
471 "generation" => $gcontacts[0]["generation"]);
473 if (isset($noscrape["fn"]))
474 $contact["name"] = $noscrape["fn"];
476 if (isset($noscrape["comm"]))
477 $contact["community"] = $noscrape["comm"];
479 if (isset($noscrape["tags"])) {
480 $keywords = implode(" ", $noscrape["tags"]);
482 $contact["keywords"] = $keywords;
485 $location = formatted_location($noscrape);
487 $contact["location"] = $location;
489 if (isset($noscrape["dfrn-notify"]))
490 $contact["notify"] = $noscrape["dfrn-notify"];
492 // Remove all fields that are not present in the gcontact table
493 unset($noscrape["fn"]);
494 unset($noscrape["key"]);
495 unset($noscrape["homepage"]);
496 unset($noscrape["comm"]);
497 unset($noscrape["tags"]);
498 unset($noscrape["locality"]);
499 unset($noscrape["region"]);
500 unset($noscrape["country-name"]);
501 unset($noscrape["contacts"]);
502 unset($noscrape["dfrn-request"]);
503 unset($noscrape["dfrn-confirm"]);
504 unset($noscrape["dfrn-notify"]);
505 unset($noscrape["dfrn-poll"]);
507 // Set the date of the last contact
508 /// @todo By now the function "update_gcontact" doesn't work with this field
509 //$contact["last_contact"] = datetime_convert();
511 $contact = array_merge($contact, $noscrape);
513 update_gcontact($contact);
515 if (trim($noscrape["updated"]) != "") {
516 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
517 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
519 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
521 return $noscrape["updated"];
528 // If we only can poll the feed, then we only do this once a while
529 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
530 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
531 return $gcontacts[0]["updated"];
534 $data = probe_url($profile);
536 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
537 // Then check the other link and delete this one
538 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
539 (normalise_link($profile) == normalise_link($data["alias"])) AND
540 (normalise_link($profile) != normalise_link($data["url"]))) {
542 // Delete the old entry
543 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
544 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
546 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
547 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
549 poco_last_updated($data["url"], $force);
551 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
555 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
556 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
557 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
559 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
563 $contact = array("generation" => $gcontacts[0]["generation"]);
565 $contact = array_merge($contact, $data);
567 $contact["server_url"] = $data["baseurl"];
569 unset($contact["batch"]);
570 unset($contact["poll"]);
571 unset($contact["request"]);
572 unset($contact["confirm"]);
573 unset($contact["poco"]);
574 unset($contact["priority"]);
575 unset($contact["pubkey"]);
576 unset($contact["baseurl"]);
578 update_gcontact($contact);
580 $feedret = z_fetch_url($data["poll"]);
582 if (!$feedret["success"]) {
583 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
584 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
586 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
590 $doc = new DOMDocument();
591 @$doc->loadXML($feedret["body"]);
593 $xpath = new DomXPath($doc);
594 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
596 $entries = $xpath->query('/atom:feed/atom:entry');
600 foreach ($entries AS $entry) {
601 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
602 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
604 if ($last_updated < $published)
605 $last_updated = $published;
607 if ($last_updated < $updated)
608 $last_updated = $updated;
611 // Maybe there aren't any entries. Then check if it is a valid feed
612 if ($last_updated == "")
613 if ($xpath->query('/atom:feed')->length > 0)
614 $last_updated = "0000-00-00 00:00:00";
616 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
617 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
619 if (($gcontacts[0]["generation"] == 0))
620 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
621 dbesc(normalise_link($profile)));
623 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
625 return($last_updated);
628 function poco_do_update($created, $updated, $last_failure, $last_contact) {
629 $now = strtotime(datetime_convert());
631 if ($updated > $last_contact)
632 $contact_time = strtotime($updated);
634 $contact_time = strtotime($last_contact);
636 $failure_time = strtotime($last_failure);
637 $created_time = strtotime($created);
639 // If there is no "created" time then use the current time
640 if ($created_time <= 0)
641 $created_time = $now;
643 // If the last contact was less than 24 hours then don't update
644 if (($now - $contact_time) < (60 * 60 * 24))
647 // If the last failure was less than 24 hours then don't update
648 if (($now - $failure_time) < (60 * 60 * 24))
651 // If the last contact was less than a week ago and the last failure is older than a week then don't update
652 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
655 // 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
656 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
659 // 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
660 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
666 function poco_to_boolean($val) {
667 if (($val == "true") OR ($val == 1))
669 if (($val == "false") OR ($val == 0))
675 function poco_check_server($server_url, $network = "", $force = false) {
677 // Unify the server address
678 $server_url = trim($server_url, "/");
679 $server_url = str_replace("/index.php", "", $server_url);
681 if ($server_url == "")
684 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
687 if ($servers[0]["created"] == "0000-00-00 00:00:00")
688 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
689 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
691 $poco = $servers[0]["poco"];
692 $noscrape = $servers[0]["noscrape"];
695 $network = $servers[0]["network"];
697 $last_contact = $servers[0]["last_contact"];
698 $last_failure = $servers[0]["last_failure"];
699 $version = $servers[0]["version"];
700 $platform = $servers[0]["platform"];
701 $site_name = $servers[0]["site_name"];
702 $info = $servers[0]["info"];
703 $register_policy = $servers[0]["register_policy"];
705 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
706 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
707 return ($last_contact >= $last_failure);
716 $register_policy = -1;
718 $last_contact = "0000-00-00 00:00:00";
719 $last_failure = "0000-00-00 00:00:00";
721 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
724 $orig_last_failure = $last_failure;
726 // Check if the page is accessible via SSL.
727 $server_url = str_replace("http://", "https://", $server_url);
728 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
730 // Maybe the page is unencrypted only?
731 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
732 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
733 $server_url = str_replace("https://", "http://", $server_url);
734 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
735 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
738 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
739 // Workaround for bad configured servers (known nginx problem)
740 if ($serverret["debug"]["http_code"] != "403") {
741 $last_failure = datetime_convert();
744 } elseif ($network == NETWORK_DIASPORA)
745 $last_contact = datetime_convert();
749 $serverret = z_fetch_url($server_url);
751 if (!$serverret["success"] OR ($serverret["body"] == ""))
754 $lines = explode("\n",$serverret["header"]);
756 foreach($lines as $line) {
758 if(stristr($line,'X-Diaspora-Version:')) {
759 $platform = "Diaspora";
760 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
761 $version = trim(str_replace("x-diaspora-version:", "", $version));
762 $network = NETWORK_DIASPORA;
763 $versionparts = explode("-", $version);
764 $version = $versionparts[0];
767 if(stristr($line,'Server: Mastodon')) {
768 $platform = "Mastodon";
769 $network = NETWORK_OSTATUS;
770 // Mastodon doesn't reveal version numbers
778 // Test for Statusnet
779 // Will also return data for Friendica and GNU Social - but it will be overwritten later
780 // The "not implemented" is a special treatment for really, really old Friendica versions
781 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
782 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
783 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
784 $platform = "StatusNet";
785 $version = trim($serverret["body"], '"');
786 $network = NETWORK_OSTATUS;
789 // Test for GNU Social
790 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
791 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
792 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
793 $platform = "GNU Social";
794 $version = trim($serverret["body"], '"');
795 $network = NETWORK_OSTATUS;
798 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
799 if ($serverret["success"]) {
800 $data = json_decode($serverret["body"]);
802 if (isset($data->site->server)) {
803 $last_contact = datetime_convert();
805 if (isset($data->site->hubzilla)) {
806 $platform = $data->site->hubzilla->PLATFORM_NAME;
807 $version = $data->site->hubzilla->RED_VERSION;
808 $network = NETWORK_DIASPORA;
810 if (isset($data->site->redmatrix)) {
811 if (isset($data->site->redmatrix->PLATFORM_NAME))
812 $platform = $data->site->redmatrix->PLATFORM_NAME;
813 elseif (isset($data->site->redmatrix->RED_PLATFORM))
814 $platform = $data->site->redmatrix->RED_PLATFORM;
816 $version = $data->site->redmatrix->RED_VERSION;
817 $network = NETWORK_DIASPORA;
819 if (isset($data->site->friendica)) {
820 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
821 $version = $data->site->friendica->FRIENDICA_VERSION;
822 $network = NETWORK_DFRN;
825 $site_name = $data->site->name;
827 $data->site->closed = poco_to_boolean($data->site->closed);
828 $data->site->private = poco_to_boolean($data->site->private);
829 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
831 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
832 $register_policy = REGISTER_APPROVE;
833 elseif (!$data->site->closed AND !$data->site->private)
834 $register_policy = REGISTER_OPEN;
836 $register_policy = REGISTER_CLOSED;
841 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
843 $serverret = z_fetch_url($server_url."/statistics.json");
844 if ($serverret["success"]) {
845 $data = json_decode($serverret["body"]);
847 $version = $data->version;
849 $site_name = $data->name;
851 if (isset($data->network) AND ($platform == ""))
852 $platform = $data->network;
854 if ($platform == "Diaspora")
855 $network = NETWORK_DIASPORA;
857 if ($data->registrations_open)
858 $register_policy = REGISTER_OPEN;
860 $register_policy = REGISTER_CLOSED;
862 if (isset($data->version))
863 $last_contact = datetime_convert();
867 // Check for noscrape
868 // Friendica servers could be detected as OStatus servers
869 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
870 $serverret = z_fetch_url($server_url."/friendica/json");
872 if (!$serverret["success"])
873 $serverret = z_fetch_url($server_url."/friendika/json");
875 if ($serverret["success"]) {
876 $data = json_decode($serverret["body"]);
878 if (isset($data->version)) {
879 $last_contact = datetime_convert();
880 $network = NETWORK_DFRN;
882 $noscrape = $data->no_scrape_url;
883 $version = $data->version;
884 $site_name = $data->site_name;
886 $register_policy_str = $data->register_policy;
887 $platform = $data->platform;
889 switch ($register_policy_str) {
890 case "REGISTER_CLOSED":
891 $register_policy = REGISTER_CLOSED;
893 case "REGISTER_APPROVE":
894 $register_policy = REGISTER_APPROVE;
896 case "REGISTER_OPEN":
897 $register_policy = REGISTER_OPEN;
906 $serverret = z_fetch_url($server_url."/poco");
907 if ($serverret["success"]) {
908 $data = json_decode($serverret["body"]);
909 if (isset($data->totalResults)) {
910 $poco = $server_url."/poco";
911 $last_contact = datetime_convert();
916 // Check again if the server exists
917 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
919 $version = strip_tags($version);
920 $site_name = strip_tags($site_name);
921 $info = strip_tags($info);
922 $platform = strip_tags($platform);
925 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
926 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
931 intval($register_policy),
936 dbesc($last_contact),
937 dbesc($last_failure),
938 dbesc(normalise_link($server_url))
941 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
942 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
944 dbesc(normalise_link($server_url)),
948 intval($register_policy),
953 dbesc(datetime_convert()),
954 dbesc($last_contact),
955 dbesc($last_failure),
956 dbesc(datetime_convert())
959 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
964 function count_common_friends($uid,$cid) {
966 $r = q("SELECT count(*) as `total`
967 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
968 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
969 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
970 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
977 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
979 return $r[0]['total'];
985 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
988 $sql_extra = " order by rand() ";
990 $sql_extra = " order by `gcontact`.`name` asc ";
992 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
994 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
995 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
996 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
997 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
998 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
999 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1000 $sql_extra LIMIT %d, %d",
1014 function count_common_friends_zcid($uid,$zcid) {
1016 $r = q("SELECT count(*) as `total`
1017 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1018 where `glink`.`zcid` = %d
1019 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1025 return $r[0]['total'];
1030 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1033 $sql_extra = " order by rand() ";
1035 $sql_extra = " order by `gcontact`.`name` asc ";
1037 $r = q("SELECT `gcontact`.*
1038 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1039 where `glink`.`zcid` = %d
1040 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1041 $sql_extra limit %d, %d",
1053 function count_all_friends($uid,$cid) {
1055 $r = q("SELECT count(*) as `total`
1056 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1057 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1058 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1064 return $r[0]['total'];
1070 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1072 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1074 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1075 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1076 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1077 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1078 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1091 function suggestion_query($uid, $start = 0, $limit = 80) {
1097 // Uncommented because the result of the queries are to big to store it in the cache.
1098 // We need to decide if we want to change the db column type or if we want to delete it.
1099 // $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1100 // if (!is_null($list)) {
1104 $network = array(NETWORK_DFRN);
1106 if (get_config('system','diaspora_enabled'))
1107 $network[] = NETWORK_DIASPORA;
1109 if (!get_config('system','ostatus_disabled'))
1110 $network[] = NETWORK_OSTATUS;
1112 $sql_network = implode("', '", $network);
1113 $sql_network = "'".$sql_network."'";
1115 /// @todo This query is really slow
1116 // By now we cache the data for five minutes
1117 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1118 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1119 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1120 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1121 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1122 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1123 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1124 AND `gcontact`.`network` IN (%s)
1125 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1135 if (count($r) && count($r) >= ($limit -1)) {
1136 // Uncommented because the result of the queries are to big to store it in the cache.
1137 // We need to decide if we want to change the db column type or if we want to delete it.
1138 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1143 $r2 = q("SELECT gcontact.* FROM gcontact
1144 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1145 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1146 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1147 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1148 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1149 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1150 AND `gcontact`.`network` IN (%s)
1151 ORDER BY rand() LIMIT %d, %d",
1161 foreach ($r2 AS $suggestion)
1162 $list[$suggestion["nurl"]] = $suggestion;
1164 foreach ($r AS $suggestion)
1165 $list[$suggestion["nurl"]] = $suggestion;
1167 while (sizeof($list) > ($limit))
1170 // Uncommented because the result of the queries are to big to store it in the cache.
1171 // We need to decide if we want to change the db column type or if we want to delete it.
1172 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1176 function update_suggestions() {
1182 /// TODO Check if it is really neccessary to poll the own server
1183 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1185 $done[] = $a->get_baseurl() . '/poco';
1187 if(strlen(get_config('system','directory'))) {
1188 $x = fetch_url(get_server()."/pubsites");
1190 $j = json_decode($x);
1192 foreach($j->entries as $entry) {
1194 poco_check_server($entry->url);
1196 $url = $entry->url . '/poco';
1197 if(! in_array($url,$done))
1198 poco_load(0,0,0,$entry->url . '/poco');
1204 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1205 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1206 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1210 foreach($r as $rr) {
1211 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1212 if(! in_array($base,$done))
1213 poco_load(0,0,0,$base);
1218 function poco_discover_federation() {
1219 $last = get_config('poco','last_federation_discovery');
1222 $next = $last + (24 * 60 * 60);
1227 // Discover Friendica, Hubzilla and Diaspora servers
1228 $serverdata = fetch_url("http://the-federation.info/pods.json");
1231 $servers = json_decode($serverdata);
1233 foreach($servers->pods AS $server)
1234 poco_check_server("https://".$server->host);
1237 // Discover GNU Social Servers
1238 if (!get_config('system','ostatus_disabled')) {
1239 $serverdata = "http://gstools.org/api/get_open_instances/";
1241 $result = z_fetch_url($serverdata);
1242 if ($result["success"]) {
1243 $servers = json_decode($result["body"]);
1245 foreach($servers->data AS $server)
1246 poco_check_server($server->instance_address);
1250 set_config('poco','last_federation_discovery', time());
1253 function poco_discover($complete = false) {
1255 // Update the server list
1256 poco_discover_federation();
1260 $requery_days = intval(get_config("system", "poco_requery_days"));
1262 if ($requery_days == 0)
1265 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1267 $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));
1269 foreach ($r AS $server) {
1271 if (!poco_check_server($server["url"], $server["network"])) {
1272 // The server is not reachable? Okay, then we will try it later
1273 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1277 // Fetch all users from the other server
1278 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1280 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1282 $retdata = z_fetch_url($url);
1283 if ($retdata["success"]) {
1284 $data = json_decode($retdata["body"]);
1286 poco_discover_server($data, 2);
1288 if (get_config('system','poco_discovery') > 1) {
1290 $timeframe = get_config('system','poco_discovery_since');
1291 if ($timeframe == 0)
1294 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1296 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1297 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1301 $retdata = z_fetch_url($url);
1302 if ($retdata["success"]) {
1303 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1304 $success = poco_discover_server(json_decode($retdata["body"]));
1307 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1308 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1309 poco_discover_server_users($data, $server);
1313 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1314 if (!$complete AND (--$no_of_queries == 0))
1317 // If the server hadn't replied correctly, then force a sanity check
1318 poco_check_server($server["url"], $server["network"], true);
1320 // If we couldn't reach the server, we will try it some time later
1321 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1326 function poco_discover_server_users($data, $server) {
1328 if (!isset($data->entry))
1331 foreach ($data->entry AS $entry) {
1333 if (isset($entry->urls)) {
1334 foreach($entry->urls as $url)
1335 if($url->type == 'profile') {
1336 $profile_url = $url->value;
1337 $urlparts = parse_url($profile_url);
1338 $username = end(explode("/", $urlparts["path"]));
1341 if ($username != "") {
1342 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1344 // Fetch all contacts from a given user from the other server
1345 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1347 $retdata = z_fetch_url($url);
1348 if ($retdata["success"])
1349 poco_discover_server(json_decode($retdata["body"]), 3);
1354 function poco_discover_server($data, $default_generation = 0) {
1356 if (!isset($data->entry) OR !count($data->entry))
1361 foreach ($data->entry AS $entry) {
1363 $profile_photo = '';
1367 $updated = '0000-00-00 00:00:00';
1373 $generation = $default_generation;
1375 $name = $entry->displayName;
1377 if(isset($entry->urls)) {
1378 foreach($entry->urls as $url) {
1379 if($url->type == 'profile') {
1380 $profile_url = $url->value;
1383 if($url->type == 'webfinger') {
1384 $connect_url = str_replace('acct:' , '', $url->value);
1390 if(isset($entry->photos)) {
1391 foreach($entry->photos as $photo) {
1392 if($photo->type == 'profile') {
1393 $profile_photo = $photo->value;
1399 if(isset($entry->updated))
1400 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1402 if(isset($entry->network))
1403 $network = $entry->network;
1405 if(isset($entry->currentLocation))
1406 $location = $entry->currentLocation;
1408 if(isset($entry->aboutMe))
1409 $about = html2bbcode($entry->aboutMe);
1411 if(isset($entry->gender))
1412 $gender = $entry->gender;
1414 if(isset($entry->generation) AND ($entry->generation > 0))
1415 $generation = ++$entry->generation;
1417 if(isset($entry->contactType) AND ($entry->contactType >= 0))
1418 $contact_type = $entry->contactType;
1420 if(isset($entry->tags))
1421 foreach($entry->tags as $tag)
1422 $keywords = implode(", ", $tag);
1424 if ($generation > 0) {
1427 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1428 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1430 $gcontact = array("url" => $profile_url, "contact-type" => $contact_type, "generation" => $generation);
1431 update_gcontact($gcontact);
1433 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1440 * @brief Removes unwanted parts from a contact url
1442 * @param string $url Contact url
1443 * @return string Contact url with the wanted parts
1445 function clean_contact_url($url) {
1446 $parts = parse_url($url);
1448 if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1451 $new_url = $parts["scheme"]."://".$parts["host"];
1453 if (isset($parts["port"]))
1454 $new_url .= ":".$parts["port"];
1456 if (isset($parts["path"]))
1457 $new_url .= $parts["path"];
1459 if ($new_url != $url)
1460 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1466 * @brief Replace alternate OStatus user format with the primary one
1468 * @param arr $contact contact array (called by reference)
1470 function fix_alternate_contact_address(&$contact) {
1471 if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1472 $data = probe_url($contact["url"]);
1473 if ($contact["network"] == NETWORK_OSTATUS) {
1474 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1475 $contact["url"] = $data["url"];
1476 $contact["addr"] = $data["addr"];
1477 $contact["alias"] = $data["alias"];
1478 $contact["server_url"] = $data["baseurl"];
1484 * @brief Fetch the gcontact id, add an entry if not existed
1486 * @param arr $contact contact array
1487 * @return bool|int Returns false if not found, integer if contact was found
1489 function get_gcontact_id($contact) {
1494 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1495 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1499 if ($contact["network"] == NETWORK_STATUSNET)
1500 $contact["network"] = NETWORK_OSTATUS;
1502 // All new contacts are hidden by default
1503 if (!isset($contact["hide"]))
1504 $contact["hide"] = true;
1506 // Replace alternate OStatus user format with the primary one
1507 fix_alternate_contact_address($contact);
1509 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1510 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1511 $contact["url"] = clean_contact_url($contact["url"]);
1513 $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1514 dbesc(normalise_link($contact["url"])));
1517 $gcontact_id = $r[0]["id"];
1519 // Update every 90 days
1520 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
1521 $last_failure_str = $r[0]["last_failure"];
1522 $last_failure = strtotime($r[0]["last_failure"]);
1523 $last_contact_str = $r[0]["last_contact"];
1524 $last_contact = strtotime($r[0]["last_contact"]);
1525 $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
1528 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
1529 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
1530 dbesc($contact["name"]),
1531 dbesc($contact["nick"]),
1532 dbesc($contact["addr"]),
1533 dbesc($contact["network"]),
1534 dbesc($contact["url"]),
1535 dbesc(normalise_link($contact["url"])),
1536 dbesc($contact["photo"]),
1537 dbesc(datetime_convert()),
1538 dbesc(datetime_convert()),
1539 dbesc($contact["location"]),
1540 dbesc($contact["about"]),
1541 intval($contact["hide"]),
1542 intval($contact["generation"])
1545 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1546 dbesc(normalise_link($contact["url"])));
1549 $gcontact_id = $r[0]["id"];
1551 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
1556 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
1557 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
1560 if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1561 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1562 dbesc(normalise_link($contact["url"])),
1563 intval($gcontact_id));
1565 return $gcontact_id;
1569 * @brief Updates the gcontact table from a given array
1571 * @param arr $contact contact array
1572 * @return bool|int Returns false if not found, integer if contact was found
1574 function update_gcontact($contact) {
1576 /// @todo update contact table as well
1578 $gcontact_id = get_gcontact_id($contact);
1583 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1584 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1585 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1586 intval($gcontact_id));
1588 // Get all field names
1590 foreach ($r[0] AS $field => $data)
1591 $fields[$field] = $data;
1593 unset($fields["url"]);
1594 unset($fields["updated"]);
1595 unset($fields["hide"]);
1597 // Bugfix: We had an error in the storing of keywords which lead to the "0"
1598 // This value is still transmitted via poco.
1599 if ($contact["keywords"] == "0")
1600 unset($contact["keywords"]);
1602 if ($r[0]["keywords"] == "0")
1603 $r[0]["keywords"] = "";
1605 // assign all unassigned fields from the database entry
1606 foreach ($fields AS $field => $data)
1607 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1608 $contact[$field] = $r[0][$field];
1610 if (!isset($contact["hide"]))
1611 $contact["hide"] = $r[0]["hide"];
1613 $fields["hide"] = $r[0]["hide"];
1615 if ($contact["network"] == NETWORK_STATUSNET)
1616 $contact["network"] = NETWORK_OSTATUS;
1618 // Replace alternate OStatus user format with the primary one
1619 fix_alternate_contact_address($contact);
1621 if (!isset($contact["updated"]))
1622 $contact["updated"] = datetime_convert();
1624 if ($contact["server_url"] == "") {
1625 $server_url = $contact["url"];
1627 $server_url = matching_url($server_url, $contact["alias"]);
1628 if ($server_url != "")
1629 $contact["server_url"] = $server_url;
1631 $server_url = matching_url($server_url, $contact["photo"]);
1632 if ($server_url != "")
1633 $contact["server_url"] = $server_url;
1635 $server_url = matching_url($server_url, $contact["notify"]);
1636 if ($server_url != "")
1637 $contact["server_url"] = $server_url;
1639 $contact["server_url"] = normalise_link($contact["server_url"]);
1641 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1642 $hostname = str_replace("http://", "", $contact["server_url"]);
1643 $contact["addr"] = $contact["nick"]."@".$hostname;
1646 // Check if any field changed
1648 unset($fields["generation"]);
1650 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1651 foreach ($fields AS $field => $data)
1652 if ($contact[$field] != $r[0][$field]) {
1653 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1657 if ($contact["generation"] < $r[0]["generation"]) {
1658 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1664 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
1666 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1667 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1668 `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
1669 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1670 `server_url` = '%s', `connect` = '%s'
1671 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1672 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1673 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1674 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1675 intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
1676 dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
1677 dbesc($contact["about"]), intval($contact["generation"]), dbesc($contact["updated"]),
1678 dbesc($contact["server_url"]), dbesc($contact["connect"]),
1679 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1682 // Now update the contact entry with the user id "0" as well.
1683 // This is used for the shadow copies of public items.
1684 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1685 dbesc(normalise_link($contact["url"])));
1688 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1690 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1692 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1693 `network` = '%s', `bd` = '%s', `gender` = '%s',
1694 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
1695 `url` = '%s', `location` = '%s', `about` = '%s'
1697 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1698 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1699 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
1700 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1701 intval($r[0]["id"]));
1705 return $gcontact_id;
1709 * @brief Updates the gcontact entry from probe
1711 * @param str $url profile link
1713 function update_gcontact_from_probe($url) {
1714 $data = probe_url($url);
1716 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
1717 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1721 update_gcontact($data);
1725 * @brief Update the gcontact entry for a given user id
1727 * @param int $uid User ID
1729 function update_gcontact_for_user($uid) {
1730 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
1731 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
1732 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
1733 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
1734 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
1736 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
1737 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
1738 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
1741 $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
1742 "country-name" => $r[0]["country-name"]));
1744 // The "addr" field was added in 3.4.3 so it can be empty for older users
1745 if ($r[0]["addr"] != "")
1746 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
1748 $addr = $r[0]["addr"];
1750 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
1751 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
1752 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
1753 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
1754 "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
1755 "nick" => $r[0]["nickname"], "addr" => $addr,
1756 "connect" => $addr, "server_url" => App::get_baseurl(),
1757 "generation" => 1, "network" => NETWORK_DFRN);
1759 update_gcontact($gcontact);
1763 * @brief Fetches users of given GNU Social server
1765 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1767 * @param str $server Server address
1769 function gs_fetch_users($server) {
1771 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1775 $url = $server."/main/statistics";
1777 $result = z_fetch_url($url);
1778 if (!$result["success"])
1781 $statistics = json_decode($result["body"]);
1783 if (is_object($statistics->config)) {
1784 if ($statistics->config->instance_with_ssl)
1785 $server = "https://";
1787 $server = "http://";
1789 $server .= $statistics->config->instance_address;
1791 $hostname = $statistics->config->instance_address;
1793 if ($statistics->instance_with_ssl)
1794 $server = "https://";
1796 $server = "http://";
1798 $server .= $statistics->instance_address;
1800 $hostname = $statistics->instance_address;
1803 if (is_object($statistics->users))
1804 foreach ($statistics->users AS $nick => $user) {
1805 $profile_url = $server."/".$user->nickname;
1807 $contact = array("url" => $profile_url,
1808 "name" => $user->fullname,
1809 "addr" => $user->nickname."@".$hostname,
1810 "nick" => $user->nickname,
1811 "about" => $user->bio,
1812 "network" => NETWORK_OSTATUS,
1813 "photo" => $a->get_baseurl()."/images/person-175.jpg");
1814 get_gcontact_id($contact);
1819 * @brief Asking GNU Social server on a regular base for their user data
1822 function gs_discover() {
1824 $requery_days = intval(get_config("system", "poco_requery_days"));
1826 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1828 $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",
1829 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1834 foreach ($r AS $server) {
1835 gs_fetch_users($server["url"]);
1836 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));