3 * @file include/socgraph.php
5 * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6 * @todo Fetch profile data from profile page for Redmatrix users
7 * @todo Detect if it is a forum
10 require_once('include/datetime.php');
11 require_once("include/Scrape.php");
12 require_once("include/network.php");
13 require_once("include/html2bbcode.php");
14 require_once("include/Contact.php");
15 require_once("include/Photo.php");
20 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
21 * and add the entries to the gcontact (Global Contact) table, or update existing entries
22 * if anything (name or photo) has changed.
23 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
25 * Once the global contact is stored add (if necessary) the contact linkage which associates
26 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
27 * pointing to the same global contact id.
34 function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
39 if((! $url) || (! $uid)) {
40 $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
43 if (dbm::is_result($r)) {
55 $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation') ;
57 logger('poco_load: ' . $url, LOGGER_DEBUG);
61 logger('poco_load: returns ' . $s, LOGGER_DATA);
63 logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
65 if(($a->get_curl_code() > 299) || (! $s))
70 logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
72 if(! isset($j->entry))
76 foreach($j->entry as $entry) {
84 $updated = '0000-00-00 00:00:00';
92 $name = $entry->displayName;
94 if (isset($entry->urls)) {
95 foreach ($entry->urls as $url) {
96 if ($url->type == 'profile') {
97 $profile_url = $url->value;
100 if ($url->type == 'webfinger') {
101 $connect_url = str_replace('acct:' , '', $url->value);
106 if (isset($entry->photos)) {
107 foreach ($entry->photos as $photo) {
108 if ($photo->type == 'profile') {
109 $profile_photo = $photo->value;
115 if (isset($entry->updated)) {
116 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
119 if (isset($entry->network)) {
120 $network = $entry->network;
123 if (isset($entry->currentLocation)) {
124 $location = $entry->currentLocation;
127 if (isset($entry->aboutMe)) {
128 $about = html2bbcode($entry->aboutMe);
131 if (isset($entry->gender)) {
132 $gender = $entry->gender;
135 if (isset($entry->generation) AND ($entry->generation > 0)) {
136 $generation = ++$entry->generation;
139 if (isset($entry->tags)) {
140 foreach($entry->tags as $tag) {
141 $keywords = implode(", ", $tag);
145 if (isset($entry->contactType) AND ($entry->contactType >= 0))
146 $contact_type = $entry->contactType;
148 // If you query a Friendica server for its profiles, the network has to be Friendica
149 /// TODO It could also be a Redmatrix server
151 // $network = NETWORK_DFRN;
153 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
155 $gcontact = array("url" => $profile_url, "contact-type" => $contact_type, "generation" => $generation);
156 update_gcontact($gcontact);
158 // Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
159 // Deactivated because we now update Friendica contacts in dfrn.php
160 //if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
161 // q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
162 // WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
167 // dbesc(normalise_link($profile_url)),
168 // dbesc(NETWORK_DFRN));
170 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
172 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
180 function poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid = 0, $uid = 0, $zcid = 0) {
184 // 1: Profiles on this server
185 // 2: Contacts of profiles on this server
186 // 3: Contacts of contacts of profiles on this server
191 if ($profile_url == "")
194 $urlparts = parse_url($profile_url);
195 if (!isset($urlparts["scheme"]))
198 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
199 "identi.ca", "alpha.app.net")))
202 // Don't store the statusnet connector as network
203 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
204 if ($network == NETWORK_STATUSNET)
207 // Assure that there are no parameter fragments in the profile url
208 if (in_array($network, array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
209 $profile_url = clean_contact_url($profile_url);
211 $alternate = poco_alternate_ostatus_url($profile_url);
213 $orig_updated = $updated;
215 // The global contacts should contain the original picture, not the cached one
216 if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link(App::get_baseurl()."/photo/"))) {
220 $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
221 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
223 if (dbm::is_result($r)) {
224 $network = $r[0]["network"];
227 if (($network == "") OR ($network == NETWORK_OSTATUS)) {
228 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
229 dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
231 if (dbm::is_result($r)) {
232 $network = $r[0]["network"];
233 //$profile_url = $r[0]["url"];
237 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
238 dbesc(normalise_link($profile_url))
242 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
243 $network = $x[0]["network"];
245 if ($updated == "0000-00-00 00:00:00")
246 $updated = $x[0]["updated"];
248 $created = $x[0]["created"];
249 $server_url = $x[0]["server_url"];
250 $nick = $x[0]["nick"];
251 $addr = $x[0]["addr"];
252 $alias = $x[0]["alias"];
253 $notify = $x[0]["notify"];
255 $created = "0000-00-00 00:00:00";
258 $urlparts = parse_url($profile_url);
259 $nick = end(explode("/", $urlparts["path"]));
265 if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
266 AND poco_reachable($profile_url, $server_url, $network, false)) {
267 $data = probe_url($profile_url);
269 $orig_profile = $profile_url;
271 $network = $data["network"];
272 $name = $data["name"];
273 $nick = $data["nick"];
274 $addr = $data["addr"];
275 $alias = $data["alias"];
276 $notify = $data["notify"];
277 $profile_url = $data["url"];
278 $profile_photo = $data["photo"];
279 $server_url = $data["baseurl"];
281 if ($alternate AND ($network == NETWORK_OSTATUS)) {
282 // Delete the old entry - if it exists
283 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
285 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
286 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
289 // possibly create a new entry
290 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
294 if ($alternate AND ($network == NETWORK_OSTATUS))
297 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
298 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
300 dbesc(normalise_link($profile_url))
304 if (($name == "") OR ($profile_photo == ""))
307 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
310 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
312 poco_check_server($server_url, $network);
314 $gcontact = array("url" => $profile_url,
318 "network" => $network,
319 "photo" => $profile_photo,
321 "location" => $location,
323 "keywords" => $keywords,
324 "server_url" => $server_url,
325 "connect" => $connect_url,
327 "updated" => $updated,
328 "generation" => $generation);
330 $gcid = update_gcontact($gcontact);
335 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
341 if (! dbm::is_result($r)) {
342 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
347 dbesc(datetime_convert())
350 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
351 dbesc(datetime_convert()),
362 function poco_reachable($profile, $server = "", $network = "", $force = false) {
365 $server = poco_detect_server($profile);
370 return poco_check_server($server, $network, $force);
373 function poco_detect_server($profile) {
375 // Try to detect the server path based upon some known standard paths
378 if ($server_url == "") {
379 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
380 if ($friendica != $profile) {
381 $server_url = $friendica;
382 $network = NETWORK_DFRN;
386 if ($server_url == "") {
387 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
388 if ($diaspora != $profile) {
389 $server_url = $diaspora;
390 $network = NETWORK_DIASPORA;
394 if ($server_url == "") {
395 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
396 if ($red != $profile) {
398 $network = NETWORK_DIASPORA;
403 if ($server_url == "") {
404 $red = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
405 if ($red != $profile) {
407 $network = NETWORK_OSTATUS;
414 function poco_alternate_ostatus_url($url) {
415 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
418 function poco_last_updated($profile, $force = false) {
420 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
421 dbesc(normalise_link($profile)));
423 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
424 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
425 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
427 if ($gcontacts[0]["server_url"] != "")
428 $server_url = $gcontacts[0]["server_url"];
430 $server_url = poco_detect_server($profile);
432 if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
433 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
437 if ($server_url != "") {
438 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
441 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
442 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
444 logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
448 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
449 dbesc($server_url), dbesc(normalise_link($profile)));
452 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
453 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
454 dbesc(normalise_link($server_url)));
457 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
458 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
463 // noscrape is really fast so we don't cache the call.
464 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
466 // Use noscrape if possible
467 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
470 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
472 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
474 $noscrape = json_decode($noscraperet["body"], true);
476 if (is_array($noscrape)) {
477 $contact = array("url" => $profile,
478 "network" => $server[0]["network"],
479 "generation" => $gcontacts[0]["generation"]);
481 if (isset($noscrape["fn"]))
482 $contact["name"] = $noscrape["fn"];
484 if (isset($noscrape["comm"]))
485 $contact["community"] = $noscrape["comm"];
487 if (isset($noscrape["tags"])) {
488 $keywords = implode(" ", $noscrape["tags"]);
490 $contact["keywords"] = $keywords;
493 $location = formatted_location($noscrape);
495 $contact["location"] = $location;
497 if (isset($noscrape["dfrn-notify"]))
498 $contact["notify"] = $noscrape["dfrn-notify"];
500 // Remove all fields that are not present in the gcontact table
501 unset($noscrape["fn"]);
502 unset($noscrape["key"]);
503 unset($noscrape["homepage"]);
504 unset($noscrape["comm"]);
505 unset($noscrape["tags"]);
506 unset($noscrape["locality"]);
507 unset($noscrape["region"]);
508 unset($noscrape["country-name"]);
509 unset($noscrape["contacts"]);
510 unset($noscrape["dfrn-request"]);
511 unset($noscrape["dfrn-confirm"]);
512 unset($noscrape["dfrn-notify"]);
513 unset($noscrape["dfrn-poll"]);
515 // Set the date of the last contact
516 /// @todo By now the function "update_gcontact" doesn't work with this field
517 //$contact["last_contact"] = datetime_convert();
519 $contact = array_merge($contact, $noscrape);
521 update_gcontact($contact);
523 if (trim($noscrape["updated"]) != "") {
524 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
525 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
527 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
529 return $noscrape["updated"];
536 // If we only can poll the feed, then we only do this once a while
537 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
538 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
539 return $gcontacts[0]["updated"];
542 $data = probe_url($profile);
544 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
545 // Then check the other link and delete this one
546 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
547 (normalise_link($profile) == normalise_link($data["alias"])) AND
548 (normalise_link($profile) != normalise_link($data["url"]))) {
550 // Delete the old entry
551 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
552 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
554 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
555 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
557 poco_last_updated($data["url"], $force);
559 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
563 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
564 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
565 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
567 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
571 $contact = array("generation" => $gcontacts[0]["generation"]);
573 $contact = array_merge($contact, $data);
575 $contact["server_url"] = $data["baseurl"];
577 unset($contact["batch"]);
578 unset($contact["poll"]);
579 unset($contact["request"]);
580 unset($contact["confirm"]);
581 unset($contact["poco"]);
582 unset($contact["priority"]);
583 unset($contact["pubkey"]);
584 unset($contact["baseurl"]);
586 update_gcontact($contact);
588 $feedret = z_fetch_url($data["poll"]);
590 if (!$feedret["success"]) {
591 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
592 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
594 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
598 $doc = new DOMDocument();
599 @$doc->loadXML($feedret["body"]);
601 $xpath = new DomXPath($doc);
602 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
604 $entries = $xpath->query('/atom:feed/atom:entry');
608 foreach ($entries AS $entry) {
609 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
610 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
612 if ($last_updated < $published)
613 $last_updated = $published;
615 if ($last_updated < $updated)
616 $last_updated = $updated;
619 // Maybe there aren't any entries. Then check if it is a valid feed
620 if ($last_updated == "")
621 if ($xpath->query('/atom:feed')->length > 0)
622 $last_updated = "0000-00-00 00:00:00";
624 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
625 dbesc(dbm::date($last_updated)), dbesc(dbm::date()), dbesc(normalise_link($profile)));
627 if (($gcontacts[0]["generation"] == 0))
628 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
629 dbesc(normalise_link($profile)));
631 logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
633 return($last_updated);
636 function poco_do_update($created, $updated, $last_failure, $last_contact) {
637 $now = strtotime(datetime_convert());
639 if ($updated > $last_contact)
640 $contact_time = strtotime($updated);
642 $contact_time = strtotime($last_contact);
644 $failure_time = strtotime($last_failure);
645 $created_time = strtotime($created);
647 // If there is no "created" time then use the current time
648 if ($created_time <= 0)
649 $created_time = $now;
651 // If the last contact was less than 24 hours then don't update
652 if (($now - $contact_time) < (60 * 60 * 24))
655 // If the last failure was less than 24 hours then don't update
656 if (($now - $failure_time) < (60 * 60 * 24))
659 // If the last contact was less than a week ago and the last failure is older than a week then don't update
660 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
663 // 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
664 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
667 // 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
668 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
674 function poco_to_boolean($val) {
675 if (($val == "true") OR ($val == 1))
677 if (($val == "false") OR ($val == 0))
683 function poco_check_server($server_url, $network = "", $force = false) {
685 // Unify the server address
686 $server_url = trim($server_url, "/");
687 $server_url = str_replace("/index.php", "", $server_url);
689 if ($server_url == "")
692 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
693 if (dbm::is_result($servers)) {
695 if ($servers[0]["created"] == "0000-00-00 00:00:00")
696 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
697 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
699 $poco = $servers[0]["poco"];
700 $noscrape = $servers[0]["noscrape"];
703 $network = $servers[0]["network"];
705 $last_contact = $servers[0]["last_contact"];
706 $last_failure = $servers[0]["last_failure"];
707 $version = $servers[0]["version"];
708 $platform = $servers[0]["platform"];
709 $site_name = $servers[0]["site_name"];
710 $info = $servers[0]["info"];
711 $register_policy = $servers[0]["register_policy"];
713 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
714 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
715 return ($last_contact >= $last_failure);
724 $register_policy = -1;
726 $last_contact = "0000-00-00 00:00:00";
727 $last_failure = "0000-00-00 00:00:00";
729 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
732 $orig_last_failure = $last_failure;
734 // Check if the page is accessible via SSL.
735 $orig_server_url = $server_url;
736 $server_url = str_replace("http://", "https://", $server_url);
738 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
739 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
741 // Quit if there is a timeout.
742 // But we want to make sure to only quit if we are mostly sure that this server url fits.
743 if (dbm::is_result($servers) AND ($orig_server_url == $server_url) AND
744 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
745 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
749 // Maybe the page is unencrypted only?
750 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
751 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
752 $server_url = str_replace("https://", "http://", $server_url);
754 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
755 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
757 // Quit if there is a timeout
758 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
759 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
763 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
766 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
767 // Workaround for bad configured servers (known nginx problem)
768 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
769 $last_failure = datetime_convert();
772 } elseif ($network == NETWORK_DIASPORA)
773 $last_contact = datetime_convert();
777 $serverret = z_fetch_url($server_url);
779 if (!$serverret["success"] OR ($serverret["body"] == ""))
782 $lines = explode("\n",$serverret["header"]);
784 foreach($lines as $line) {
786 if(stristr($line,'X-Diaspora-Version:')) {
787 $platform = "Diaspora";
788 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
789 $version = trim(str_replace("x-diaspora-version:", "", $version));
790 $network = NETWORK_DIASPORA;
791 $versionparts = explode("-", $version);
792 $version = $versionparts[0];
795 if(stristr($line,'Server: Mastodon')) {
796 $platform = "Mastodon";
797 $network = NETWORK_OSTATUS;
798 // Mastodon doesn't reveal version numbers
806 // Test for Statusnet
807 // Will also return data for Friendica and GNU Social - but it will be overwritten later
808 // The "not implemented" is a special treatment for really, really old Friendica versions
809 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
810 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
811 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
812 $platform = "StatusNet";
813 $version = trim($serverret["body"], '"');
814 $network = NETWORK_OSTATUS;
817 // Test for GNU Social
818 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
819 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
820 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
821 $platform = "GNU Social";
822 $version = trim($serverret["body"], '"');
823 $network = NETWORK_OSTATUS;
826 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
827 if ($serverret["success"]) {
828 $data = json_decode($serverret["body"]);
830 if (isset($data->site->server)) {
831 $last_contact = datetime_convert();
833 if (isset($data->site->hubzilla)) {
834 $platform = $data->site->hubzilla->PLATFORM_NAME;
835 $version = $data->site->hubzilla->RED_VERSION;
836 $network = NETWORK_DIASPORA;
838 if (isset($data->site->redmatrix)) {
839 if (isset($data->site->redmatrix->PLATFORM_NAME))
840 $platform = $data->site->redmatrix->PLATFORM_NAME;
841 elseif (isset($data->site->redmatrix->RED_PLATFORM))
842 $platform = $data->site->redmatrix->RED_PLATFORM;
844 $version = $data->site->redmatrix->RED_VERSION;
845 $network = NETWORK_DIASPORA;
847 if (isset($data->site->friendica)) {
848 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
849 $version = $data->site->friendica->FRIENDICA_VERSION;
850 $network = NETWORK_DFRN;
853 $site_name = $data->site->name;
855 $data->site->closed = poco_to_boolean($data->site->closed);
856 $data->site->private = poco_to_boolean($data->site->private);
857 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
859 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
860 $register_policy = REGISTER_APPROVE;
861 elseif (!$data->site->closed AND !$data->site->private)
862 $register_policy = REGISTER_OPEN;
864 $register_policy = REGISTER_CLOSED;
869 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
871 $serverret = z_fetch_url($server_url."/statistics.json");
872 if ($serverret["success"]) {
873 $data = json_decode($serverret["body"]);
875 $version = $data->version;
877 $site_name = $data->name;
879 if (isset($data->network) AND ($platform == ""))
880 $platform = $data->network;
882 if ($platform == "Diaspora")
883 $network = NETWORK_DIASPORA;
885 if ($data->registrations_open)
886 $register_policy = REGISTER_OPEN;
888 $register_policy = REGISTER_CLOSED;
890 if (isset($data->version))
891 $last_contact = datetime_convert();
895 // Check for noscrape
896 // Friendica servers could be detected as OStatus servers
897 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
898 $serverret = z_fetch_url($server_url."/friendica/json");
900 if (!$serverret["success"])
901 $serverret = z_fetch_url($server_url."/friendika/json");
903 if ($serverret["success"]) {
904 $data = json_decode($serverret["body"]);
906 if (isset($data->version)) {
907 $last_contact = datetime_convert();
908 $network = NETWORK_DFRN;
910 $noscrape = $data->no_scrape_url;
911 $version = $data->version;
912 $site_name = $data->site_name;
914 $register_policy_str = $data->register_policy;
915 $platform = $data->platform;
917 switch ($register_policy_str) {
918 case "REGISTER_CLOSED":
919 $register_policy = REGISTER_CLOSED;
921 case "REGISTER_APPROVE":
922 $register_policy = REGISTER_APPROVE;
924 case "REGISTER_OPEN":
925 $register_policy = REGISTER_OPEN;
934 $serverret = z_fetch_url($server_url."/poco");
935 if ($serverret["success"]) {
936 $data = json_decode($serverret["body"]);
937 if (isset($data->totalResults)) {
938 $poco = $server_url."/poco";
939 $last_contact = datetime_convert();
944 // Check again if the server exists
945 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
947 $version = strip_tags($version);
948 $site_name = strip_tags($site_name);
949 $info = strip_tags($info);
950 $platform = strip_tags($platform);
953 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
954 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
959 intval($register_policy),
964 dbesc($last_contact),
965 dbesc($last_failure),
966 dbesc(normalise_link($server_url))
969 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
970 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
972 dbesc(normalise_link($server_url)),
976 intval($register_policy),
981 dbesc(datetime_convert()),
982 dbesc($last_contact),
983 dbesc($last_failure),
984 dbesc(datetime_convert())
987 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
992 function count_common_friends($uid,$cid) {
994 $r = q("SELECT count(*) as `total`
995 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
996 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
997 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
998 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1005 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1006 if (dbm::is_result($r))
1007 return $r[0]['total'];
1013 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1016 $sql_extra = " order by rand() ";
1018 $sql_extra = " order by `gcontact`.`name` asc ";
1020 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1022 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1023 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1024 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1025 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1026 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1027 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1028 $sql_extra LIMIT %d, %d",
1042 function count_common_friends_zcid($uid,$zcid) {
1044 $r = q("SELECT count(*) as `total`
1045 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1046 where `glink`.`zcid` = %d
1047 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1052 if (dbm::is_result($r))
1053 return $r[0]['total'];
1058 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1061 $sql_extra = " order by rand() ";
1063 $sql_extra = " order by `gcontact`.`name` asc ";
1065 $r = q("SELECT `gcontact`.*
1066 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1067 where `glink`.`zcid` = %d
1068 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1069 $sql_extra limit %d, %d",
1081 function count_all_friends($uid,$cid) {
1083 $r = q("SELECT count(*) as `total`
1084 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1085 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1086 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1091 if (dbm::is_result($r))
1092 return $r[0]['total'];
1098 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1100 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1102 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1103 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1104 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1105 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1106 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1119 function suggestion_query($uid, $start = 0, $limit = 80) {
1125 // Uncommented because the result of the queries are to big to store it in the cache.
1126 // We need to decide if we want to change the db column type or if we want to delete it.
1127 // $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1128 // if (!is_null($list)) {
1132 $network = array(NETWORK_DFRN);
1134 if (get_config('system','diaspora_enabled'))
1135 $network[] = NETWORK_DIASPORA;
1137 if (!get_config('system','ostatus_disabled'))
1138 $network[] = NETWORK_OSTATUS;
1140 $sql_network = implode("', '", $network);
1141 $sql_network = "'".$sql_network."'";
1143 /// @todo This query is really slow
1144 // By now we cache the data for five minutes
1145 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1146 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1147 where uid = %d 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 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1163 if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1164 // Uncommented because the result of the queries are to big to store it in the cache.
1165 // We need to decide if we want to change the db column type or if we want to delete it.
1166 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1171 $r2 = q("SELECT gcontact.* FROM gcontact
1172 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1173 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1174 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1175 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1176 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1177 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1178 AND `gcontact`.`network` IN (%s)
1179 ORDER BY rand() LIMIT %d, %d",
1189 foreach ($r2 AS $suggestion)
1190 $list[$suggestion["nurl"]] = $suggestion;
1192 foreach ($r AS $suggestion)
1193 $list[$suggestion["nurl"]] = $suggestion;
1195 while (sizeof($list) > ($limit))
1198 // Uncommented because the result of the queries are to big to store it in the cache.
1199 // We need to decide if we want to change the db column type or if we want to delete it.
1200 // Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1204 function update_suggestions() {
1210 /// @TODO Check if it is really neccessary to poll the own server
1211 poco_load(0,0,0,App::get_baseurl() . '/poco');
1213 $done[] = App::get_baseurl() . '/poco';
1215 if (strlen(get_config('system','directory'))) {
1216 $x = fetch_url(get_server()."/pubsites");
1218 $j = json_decode($x);
1220 foreach ($j->entries as $entry) {
1222 poco_check_server($entry->url);
1224 $url = $entry->url . '/poco';
1225 if (! in_array($url,$done)) {
1226 poco_load(0,0,0,$entry->url . '/poco');
1233 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1234 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1235 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1238 if (dbm::is_result($r)) {
1239 foreach ($r as $rr) {
1240 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1241 if(! in_array($base,$done))
1242 poco_load(0,0,0,$base);
1247 function poco_discover_federation() {
1248 $last = get_config('poco','last_federation_discovery');
1251 $next = $last + (24 * 60 * 60);
1256 // Discover Friendica, Hubzilla and Diaspora servers
1257 $serverdata = fetch_url("http://the-federation.info/pods.json");
1260 $servers = json_decode($serverdata);
1262 foreach($servers->pods AS $server)
1263 poco_check_server("https://".$server->host);
1266 // Currently disabled, since the service isn't available anymore.
1267 // It is not removed since I hope that there will be a successor.
1268 // Discover GNU Social Servers.
1269 //if (!get_config('system','ostatus_disabled')) {
1270 // $serverdata = "http://gstools.org/api/get_open_instances/";
1272 // $result = z_fetch_url($serverdata);
1273 // if ($result["success"]) {
1274 // $servers = json_decode($result["body"]);
1276 // foreach($servers->data AS $server)
1277 // poco_check_server($server->instance_address);
1281 set_config('poco','last_federation_discovery', time());
1284 function poco_discover($complete = false) {
1286 // Update the server list
1287 poco_discover_federation();
1291 $requery_days = intval(get_config("system", "poco_requery_days"));
1293 if ($requery_days == 0)
1296 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1298 $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));
1300 foreach ($r AS $server) {
1302 if (!poco_check_server($server["url"], $server["network"])) {
1303 // The server is not reachable? Okay, then we will try it later
1304 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1308 // Fetch all users from the other server
1309 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1311 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1313 $retdata = z_fetch_url($url);
1314 if ($retdata["success"]) {
1315 $data = json_decode($retdata["body"]);
1317 poco_discover_server($data, 2);
1319 if (get_config('system','poco_discovery') > 1) {
1321 $timeframe = get_config('system','poco_discovery_since');
1322 if ($timeframe == 0)
1325 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1327 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1328 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1332 $retdata = z_fetch_url($url);
1333 if ($retdata["success"]) {
1334 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1335 $success = poco_discover_server(json_decode($retdata["body"]));
1338 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1339 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1340 poco_discover_server_users($data, $server);
1344 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1345 if (!$complete AND (--$no_of_queries == 0))
1348 // If the server hadn't replied correctly, then force a sanity check
1349 poco_check_server($server["url"], $server["network"], true);
1351 // If we couldn't reach the server, we will try it some time later
1352 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1357 function poco_discover_server_users($data, $server) {
1359 if (!isset($data->entry))
1362 foreach ($data->entry AS $entry) {
1364 if (isset($entry->urls)) {
1365 foreach($entry->urls as $url)
1366 if ($url->type == 'profile') {
1367 $profile_url = $url->value;
1368 $urlparts = parse_url($profile_url);
1369 $username = end(explode("/", $urlparts["path"]));
1372 if ($username != "") {
1373 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1375 // Fetch all contacts from a given user from the other server
1376 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1378 $retdata = z_fetch_url($url);
1379 if ($retdata["success"])
1380 poco_discover_server(json_decode($retdata["body"]), 3);
1385 function poco_discover_server($data, $default_generation = 0) {
1387 if (!isset($data->entry) OR !count($data->entry))
1392 foreach ($data->entry AS $entry) {
1394 $profile_photo = '';
1398 $updated = '0000-00-00 00:00:00';
1404 $generation = $default_generation;
1406 $name = $entry->displayName;
1408 if (isset($entry->urls)) {
1409 foreach($entry->urls as $url) {
1410 if ($url->type == 'profile') {
1411 $profile_url = $url->value;
1414 if ($url->type == 'webfinger') {
1415 $connect_url = str_replace('acct:' , '', $url->value);
1421 if (isset($entry->photos)) {
1422 foreach ($entry->photos as $photo) {
1423 if ($photo->type == 'profile') {
1424 $profile_photo = $photo->value;
1430 if (isset($entry->updated)) {
1431 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1434 if(isset($entry->network)) {
1435 $network = $entry->network;
1438 if(isset($entry->currentLocation)) {
1439 $location = $entry->currentLocation;
1442 if(isset($entry->aboutMe)) {
1443 $about = html2bbcode($entry->aboutMe);
1446 if(isset($entry->gender)) {
1447 $gender = $entry->gender;
1450 if(isset($entry->generation) AND ($entry->generation > 0)) {
1451 $generation = ++$entry->generation;
1454 if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
1455 $contact_type = $entry->contactType;
1458 if(isset($entry->tags)) {
1459 foreach ($entry->tags as $tag) {
1460 $keywords = implode(", ", $tag);
1464 if ($generation > 0) {
1467 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1468 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1470 $gcontact = array("url" => $profile_url, "contact-type" => $contact_type, "generation" => $generation);
1471 update_gcontact($gcontact);
1473 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1480 * @brief Removes unwanted parts from a contact url
1482 * @param string $url Contact url
1483 * @return string Contact url with the wanted parts
1485 function clean_contact_url($url) {
1486 $parts = parse_url($url);
1488 if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1491 $new_url = $parts["scheme"]."://".$parts["host"];
1493 if (isset($parts["port"]))
1494 $new_url .= ":".$parts["port"];
1496 if (isset($parts["path"]))
1497 $new_url .= $parts["path"];
1499 if ($new_url != $url)
1500 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1506 * @brief Replace alternate OStatus user format with the primary one
1508 * @param arr $contact contact array (called by reference)
1510 function fix_alternate_contact_address(&$contact) {
1511 if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1512 $data = probe_url($contact["url"]);
1513 if ($contact["network"] == NETWORK_OSTATUS) {
1514 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1515 $contact["url"] = $data["url"];
1516 $contact["addr"] = $data["addr"];
1517 $contact["alias"] = $data["alias"];
1518 $contact["server_url"] = $data["baseurl"];
1524 * @brief Fetch the gcontact id, add an entry if not existed
1526 * @param arr $contact contact array
1527 * @return bool|int Returns false if not found, integer if contact was found
1529 function get_gcontact_id($contact) {
1534 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1535 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1539 if ($contact["network"] == NETWORK_STATUSNET)
1540 $contact["network"] = NETWORK_OSTATUS;
1542 // All new contacts are hidden by default
1543 if (!isset($contact["hide"]))
1544 $contact["hide"] = true;
1546 // Replace alternate OStatus user format with the primary one
1547 fix_alternate_contact_address($contact);
1549 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1550 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1551 $contact["url"] = clean_contact_url($contact["url"]);
1553 $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
1554 dbesc(normalise_link($contact["url"])));
1557 $gcontact_id = $r[0]["id"];
1559 // Update every 90 days
1560 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
1561 $last_failure_str = $r[0]["last_failure"];
1562 $last_failure = strtotime($r[0]["last_failure"]);
1563 $last_contact_str = $r[0]["last_contact"];
1564 $last_contact = strtotime($r[0]["last_contact"]);
1565 $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
1568 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
1569 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
1570 dbesc($contact["name"]),
1571 dbesc($contact["nick"]),
1572 dbesc($contact["addr"]),
1573 dbesc($contact["network"]),
1574 dbesc($contact["url"]),
1575 dbesc(normalise_link($contact["url"])),
1576 dbesc($contact["photo"]),
1577 dbesc(datetime_convert()),
1578 dbesc(datetime_convert()),
1579 dbesc($contact["location"]),
1580 dbesc($contact["about"]),
1581 intval($contact["hide"]),
1582 intval($contact["generation"])
1585 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1586 dbesc(normalise_link($contact["url"])));
1589 $gcontact_id = $r[0]["id"];
1591 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
1596 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
1597 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
1600 if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1601 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1602 dbesc(normalise_link($contact["url"])),
1603 intval($gcontact_id));
1605 return $gcontact_id;
1609 * @brief Updates the gcontact table from a given array
1611 * @param arr $contact contact array
1612 * @return bool|int Returns false if not found, integer if contact was found
1614 function update_gcontact($contact) {
1616 // Check for invalid "contact-type" value
1617 if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
1618 $contact['contact-type'] = 0;
1621 /// @todo update contact table as well
1623 $gcontact_id = get_gcontact_id($contact);
1628 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1629 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1630 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1631 intval($gcontact_id));
1633 // Get all field names
1635 foreach ($r[0] AS $field => $data)
1636 $fields[$field] = $data;
1638 unset($fields["url"]);
1639 unset($fields["updated"]);
1640 unset($fields["hide"]);
1642 // Bugfix: We had an error in the storing of keywords which lead to the "0"
1643 // This value is still transmitted via poco.
1644 if ($contact["keywords"] == "0")
1645 unset($contact["keywords"]);
1647 if ($r[0]["keywords"] == "0")
1648 $r[0]["keywords"] = "";
1650 // assign all unassigned fields from the database entry
1651 foreach ($fields AS $field => $data)
1652 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1653 $contact[$field] = $r[0][$field];
1655 if (!isset($contact["hide"]))
1656 $contact["hide"] = $r[0]["hide"];
1658 $fields["hide"] = $r[0]["hide"];
1660 if ($contact["network"] == NETWORK_STATUSNET)
1661 $contact["network"] = NETWORK_OSTATUS;
1663 // Replace alternate OStatus user format with the primary one
1664 fix_alternate_contact_address($contact);
1666 if (!isset($contact["updated"]))
1667 $contact["updated"] = datetime_convert();
1669 if ($contact["server_url"] == "") {
1670 $server_url = $contact["url"];
1672 $server_url = matching_url($server_url, $contact["alias"]);
1673 if ($server_url != "")
1674 $contact["server_url"] = $server_url;
1676 $server_url = matching_url($server_url, $contact["photo"]);
1677 if ($server_url != "")
1678 $contact["server_url"] = $server_url;
1680 $server_url = matching_url($server_url, $contact["notify"]);
1681 if ($server_url != "")
1682 $contact["server_url"] = $server_url;
1684 $contact["server_url"] = normalise_link($contact["server_url"]);
1686 if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1687 $hostname = str_replace("http://", "", $contact["server_url"]);
1688 $contact["addr"] = $contact["nick"]."@".$hostname;
1691 // Check if any field changed
1693 unset($fields["generation"]);
1695 if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1696 foreach ($fields AS $field => $data)
1697 if ($contact[$field] != $r[0][$field]) {
1698 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1702 if ($contact["generation"] < $r[0]["generation"]) {
1703 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1709 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
1711 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1712 `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1713 `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
1714 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1715 `server_url` = '%s', `connect` = '%s'
1716 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1717 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1718 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1719 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1720 intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
1721 dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
1722 dbesc($contact["about"]), intval($contact["generation"]), dbesc($contact["updated"]),
1723 dbesc($contact["server_url"]), dbesc($contact["connect"]),
1724 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1727 // Now update the contact entry with the user id "0" as well.
1728 // This is used for the shadow copies of public items.
1729 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1730 dbesc(normalise_link($contact["url"])));
1733 logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1735 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1737 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1738 `network` = '%s', `bd` = '%s', `gender` = '%s',
1739 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
1740 `url` = '%s', `location` = '%s', `about` = '%s'
1742 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1743 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1744 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
1745 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1746 intval($r[0]["id"]));
1750 return $gcontact_id;
1754 * @brief Updates the gcontact entry from probe
1756 * @param str $url profile link
1758 function update_gcontact_from_probe($url) {
1759 $data = probe_url($url);
1761 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
1762 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1766 update_gcontact($data);
1770 * @brief Update the gcontact entry for a given user id
1772 * @param int $uid User ID
1774 function update_gcontact_for_user($uid) {
1775 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
1776 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
1777 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
1778 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
1779 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
1781 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
1782 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
1783 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
1786 $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
1787 "country-name" => $r[0]["country-name"]));
1789 // The "addr" field was added in 3.4.3 so it can be empty for older users
1790 if ($r[0]["addr"] != "")
1791 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
1793 $addr = $r[0]["addr"];
1795 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
1796 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
1797 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
1798 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
1799 "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
1800 "nick" => $r[0]["nickname"], "addr" => $addr,
1801 "connect" => $addr, "server_url" => App::get_baseurl(),
1802 "generation" => 1, "network" => NETWORK_DFRN);
1804 update_gcontact($gcontact);
1808 * @brief Fetches users of given GNU Social server
1810 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1812 * @param str $server Server address
1814 function gs_fetch_users($server) {
1816 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1818 $url = $server."/main/statistics";
1820 $result = z_fetch_url($url);
1821 if (!$result["success"])
1824 $statistics = json_decode($result["body"]);
1826 if (is_object($statistics->config)) {
1827 if ($statistics->config->instance_with_ssl)
1828 $server = "https://";
1830 $server = "http://";
1832 $server .= $statistics->config->instance_address;
1834 $hostname = $statistics->config->instance_address;
1836 if ($statistics->instance_with_ssl)
1837 $server = "https://";
1839 $server = "http://";
1841 $server .= $statistics->instance_address;
1843 $hostname = $statistics->instance_address;
1846 if (is_object($statistics->users))
1847 foreach ($statistics->users AS $nick => $user) {
1848 $profile_url = $server."/".$user->nickname;
1850 $contact = array("url" => $profile_url,
1851 "name" => $user->fullname,
1852 "addr" => $user->nickname."@".$hostname,
1853 "nick" => $user->nickname,
1854 "about" => $user->bio,
1855 "network" => NETWORK_OSTATUS,
1856 "photo" => App::get_baseurl()."/images/person-175.jpg");
1857 get_gcontact_id($contact);
1862 * @brief Asking GNU Social server on a regular base for their user data
1865 function gs_discover() {
1867 $requery_days = intval(get_config("system", "poco_requery_days"));
1869 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1871 $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",
1872 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1877 foreach ($r AS $server) {
1878 gs_fetch_users($server["url"]);
1879 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));