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/html2bbcode.php");
18 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
19 * and add the entries to the gcontact (Global Contact) table, or update existing entries
20 * if anything (name or photo) has changed.
21 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
23 * Once the global contact is stored add (if necessary) the contact linkage which associates
24 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
25 * pointing to the same global contact id.
32 function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
37 if((! $url) || (! $uid)) {
38 $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
53 $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation') ;
55 logger('poco_load: ' . $url, LOGGER_DEBUG);
59 logger('poco_load: returns ' . $s, LOGGER_DATA);
61 logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
63 if(($a->get_curl_code() > 299) || (! $s))
68 logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
70 if(! isset($j->entry))
74 foreach($j->entry as $entry) {
82 $updated = '0000-00-00 00:00:00';
89 $name = $entry->displayName;
91 if(isset($entry->urls)) {
92 foreach($entry->urls as $url) {
93 if($url->type == 'profile') {
94 $profile_url = $url->value;
97 if($url->type == 'webfinger') {
98 $connect_url = str_replace('acct:' , '', $url->value);
103 if(isset($entry->photos)) {
104 foreach($entry->photos as $photo) {
105 if($photo->type == 'profile') {
106 $profile_photo = $photo->value;
112 if(isset($entry->updated))
113 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
115 if(isset($entry->network))
116 $network = $entry->network;
118 if(isset($entry->currentLocation))
119 $location = $entry->currentLocation;
121 if(isset($entry->aboutMe))
122 $about = html2bbcode($entry->aboutMe);
124 if(isset($entry->gender))
125 $gender = $entry->gender;
127 if(isset($entry->generation) AND ($entry->generation > 0))
128 $generation = ++$entry->generation;
130 if(isset($entry->tags))
131 foreach($entry->tags as $tag)
132 $keywords = implode(", ", $tag);
134 // If you query a Friendica server for its profiles, the network has to be Friendica
135 /// TODO It could also be a Redmatrix server
137 // $network = NETWORK_DFRN;
139 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
141 // Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
142 if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
143 q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
144 WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
149 dbesc(normalise_link($profile_url)),
150 dbesc(NETWORK_DFRN));
152 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
154 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
162 function poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid = 0, $uid = 0, $zcid = 0) {
168 // 1: Profiles on this server
169 // 2: Contacts of profiles on this server
170 // 3: Contacts of contacts of profiles on this server
175 $alternate = poco_alternate_ostatus_url($profile_url);
177 if ($profile_url == "")
180 $urlparts = parse_url($profile_url);
181 if (!isset($urlparts["scheme"]))
184 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
185 "identi.ca", "alpha.app.net")))
188 $orig_updated = $updated;
190 // Don't store the statusnet connector as network
191 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
192 if ($network == NETWORK_STATUSNET)
195 // The global contacts should contain the original picture, not the cached one
196 if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link($a->get_baseurl()."/photo/")))
199 $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
200 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
203 $network = $r[0]["network"];
205 if (($network == "") OR ($network == NETWORK_OSTATUS)) {
206 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
207 dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
210 $network = $r[0]["network"];
211 //$profile_url = $r[0]["url"];
215 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
216 dbesc(normalise_link($profile_url))
220 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
221 $network = $x[0]["network"];
223 if ($updated == "0000-00-00 00:00:00")
224 $updated = $x[0]["updated"];
226 $created = $x[0]["created"];
227 $server_url = $x[0]["server_url"];
228 $nick = $x[0]["nick"];
229 $addr = $x[0]["addr"];
230 $alias = $x[0]["alias"];
231 $notify = $x[0]["notify"];
233 $created = "0000-00-00 00:00:00";
236 $urlparts = parse_url($profile_url);
237 $nick = end(explode("/", $urlparts["path"]));
243 if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
244 AND poco_reachable($profile_url, $server_url, $network, false)) {
245 $data = probe_url($profile_url);
247 $orig_profile = $profile_url;
249 $network = $data["network"];
250 $name = $data["name"];
251 $nick = $data["nick"];
252 $addr = $data["addr"];
253 $alias = $data["alias"];
254 $notify = $data["notify"];
255 $profile_url = $data["url"];
256 $profile_photo = $data["photo"];
257 $server_url = $data["baseurl"];
259 if ($alternate AND ($network == NETWORK_OSTATUS)) {
260 // Delete the old entry - if it exists
261 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
263 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
264 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
267 // possibly create a new entry
268 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
272 if ($alternate AND ($network == NETWORK_OSTATUS))
275 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
276 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
278 dbesc(normalise_link($profile_url))
282 if (($name == "") OR ($profile_photo == ""))
285 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
288 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
290 poco_check_server($server_url, $network);
295 if (($location == "") AND ($x[0]['location'] != ""))
296 $location = $x[0]['location'];
298 if (($about == "") AND ($x[0]['about'] != ""))
299 $about = $x[0]['about'];
301 if (($gender == "") AND ($x[0]['gender'] != ""))
302 $gender = $x[0]['gender'];
304 if (($keywords == "") AND ($x[0]['keywords'] != ""))
305 $keywords = $x[0]['keywords'];
307 if (($addr == "") AND ($x[0]['addr'] != ""))
308 $addr = $x[0]['addr'];
310 if (($alias == "") AND ($x[0]['alias'] != ""))
311 $alias = $x[0]['alias'];
313 if (($notify == "") AND ($x[0]['notify'] != ""))
314 $notify = $x[0]['notify'];
316 if (($generation == 0) AND ($x[0]['generation'] > 0))
317 $generation = $x[0]['generation'];
319 if($x[0]['name'] != $name || $x[0]['photo'] != $profile_photo || $x[0]['updated'] < $updated) {
320 q("UPDATE `gcontact` SET `name` = '%s', `addr` = '%s', `network` = '%s', `photo` = '%s', `connect` = '%s', `url` = '%s', `server_url` = '%s',
321 `updated` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s', `generation` = %d,
322 `alias` = '$s', `notify` = '%s'
323 WHERE (`generation` >= %d OR `generation` = 0) AND `nurl` = '%s'",
327 dbesc($profile_photo),
340 dbesc(normalise_link($profile_url))
344 // Maybe another process had inserted the entry after the first check, so it again
345 $x = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
346 dbesc(normalise_link($profile_url))
349 q("INSERT INTO `gcontact` (`name`, `nick`, `addr`, `network`, `url`, `nurl`, `photo`, `connect`, `server_url`, `created`, `updated`, `location`, `about`, `keywords`, `gender`, `alias`, `notify`, `generation`)
350 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
356 dbesc(normalise_link($profile_url)),
357 dbesc($profile_photo),
360 dbesc(datetime_convert()),
370 $x = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
371 dbesc(normalise_link($profile_url))
381 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
388 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
393 dbesc(datetime_convert())
396 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
397 dbesc(datetime_convert()),
405 // For unknown reasons there are sometimes duplicates
406 //q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d AND
407 // NOT EXISTS (SELECT `gcid` FROM `glink` WHERE `gcid` = `gcontact`.`id`)",
408 // dbesc(normalise_link($profile_url)),
415 function poco_reachable($profile, $server = "", $network = "", $force = false) {
418 $server = poco_detect_server($profile);
423 return poco_check_server($server, $network, $force);
426 function poco_detect_server($profile) {
428 // Try to detect the server path based upon some known standard paths
431 if ($server_url == "") {
432 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
433 if ($friendica != $profile) {
434 $server_url = $friendica;
435 $network = NETWORK_DFRN;
439 if ($server_url == "") {
440 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
441 if ($diaspora != $profile) {
442 $server_url = $diaspora;
443 $network = NETWORK_DIASPORA;
447 if ($server_url == "") {
448 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
449 if ($red != $profile) {
451 $network = NETWORK_DIASPORA;
458 function poco_alternate_ostatus_url($url) {
459 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
462 function poco_last_updated($profile, $force = false) {
464 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
465 dbesc(normalise_link($profile)));
467 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
468 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
469 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
471 if ($gcontacts[0]["server_url"] != "")
472 $server_url = $gcontacts[0]["server_url"];
474 $server_url = poco_detect_server($profile);
476 if ($server_url != "") {
477 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
480 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
481 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
486 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
487 dbesc($server_url), dbesc(normalise_link($profile)));
490 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
491 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
492 dbesc(normalise_link($server_url)));
495 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
496 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
501 // noscrape is really fast so we don't cache the call.
502 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
504 // Use noscrape if possible
505 $server = q("SELECT `noscrape` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
508 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
510 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
512 $noscrape = json_decode($noscraperet["body"], true);
514 if (($noscrape["fn"] != "") AND ($noscrape["fn"] != $gcontacts[0]["name"]))
515 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
516 dbesc($noscrape["fn"]), dbesc(normalise_link($profile)));
518 if (($noscrape["photo"] != "") AND ($noscrape["photo"] != $gcontacts[0]["photo"]))
519 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
520 dbesc($noscrape["photo"]), dbesc(normalise_link($profile)));
522 if (($noscrape["updated"] != "") AND ($noscrape["updated"] != $gcontacts[0]["updated"]))
523 q("UPDATE `gcontact` SET `updated` = '%s' WHERE `nurl` = '%s'",
524 dbesc($noscrape["updated"]), dbesc(normalise_link($profile)));
526 if (($noscrape["gender"] != "") AND ($noscrape["gender"] != $gcontacts[0]["gender"]))
527 q("UPDATE `gcontact` SET `gender` = '%s' WHERE `nurl` = '%s'",
528 dbesc($noscrape["gender"]), dbesc(normalise_link($profile)));
530 if (($noscrape["pdesc"] != "") AND ($noscrape["pdesc"] != $gcontacts[0]["about"]))
531 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
532 dbesc($noscrape["pdesc"]), dbesc(normalise_link($profile)));
534 if (($noscrape["about"] != "") AND ($noscrape["about"] != $gcontacts[0]["about"]))
535 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
536 dbesc($noscrape["about"]), dbesc(normalise_link($profile)));
538 if (isset($noscrape["comm"]) AND ($noscrape["comm"] != $gcontacts[0]["community"]))
539 q("UPDATE `gcontact` SET `community` = %d WHERE `nurl` = '%s'",
540 intval($noscrape["comm"]), dbesc(normalise_link($profile)));
542 if (isset($noscrape["tags"]))
543 $keywords = implode(" ", $noscrape["tags"]);
547 if (($keywords != "") AND ($keywords != $gcontacts[0]["keywords"]))
548 q("UPDATE `gcontact` SET `keywords` = '%s' WHERE `nurl` = '%s'",
549 dbesc($keywords), dbesc(normalise_link($profile)));
551 $location = $noscrape["locality"];
553 if ($noscrape["region"] != "") {
557 $location .= $noscrape["region"];
560 if ($noscrape["country-name"] != "") {
564 $location .= $noscrape["country-name"];
567 if (($location != "") AND ($location != $gcontacts[0]["location"]))
568 q("UPDATE `gcontact` SET `location` = '%s' WHERE `nurl` = '%s'",
569 dbesc($location), dbesc(normalise_link($profile)));
571 // If we got data from noscrape then mark the contact as reachable
572 if (is_array($noscrape) AND count($noscrape))
573 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
574 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
576 return $noscrape["updated"];
581 // If we only can poll the feed, then we only do this once a while
582 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"]))
583 return $gcontacts[0]["updated"];
585 $data = probe_url($profile);
587 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
588 // Then check the other link and delete this one
589 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
590 (normalise_link($profile) == normalise_link($data["alias"])) AND
591 (normalise_link($profile) != normalise_link($data["url"]))) {
593 // Delete the old entry
594 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
595 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
597 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
598 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
600 poco_last_updated($data["url"], $force);
605 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
606 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
607 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
611 if (($data["name"] != "") AND ($data["name"] != $gcontacts[0]["name"]))
612 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
613 dbesc($data["name"]), dbesc(normalise_link($profile)));
615 if (($data["nick"] != "") AND ($data["nick"] != $gcontacts[0]["nick"]))
616 q("UPDATE `gcontact` SET `nick` = '%s' WHERE `nurl` = '%s'",
617 dbesc($data["nick"]), dbesc(normalise_link($profile)));
619 if (($data["addr"] != "") AND ($data["addr"] != $gcontacts[0]["connect"]))
620 q("UPDATE `gcontact` SET `connect` = '%s' WHERE `nurl` = '%s'",
621 dbesc($data["addr"]), dbesc(normalise_link($profile)));
623 if (($data["photo"] != "") AND ($data["photo"] != $gcontacts[0]["photo"]))
624 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
625 dbesc($data["photo"]), dbesc(normalise_link($profile)));
627 if (($data["baseurl"] != "") AND ($data["baseurl"] != $gcontacts[0]["server_url"]))
628 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
629 dbesc($data["baseurl"]), dbesc(normalise_link($profile)));
631 $feedret = z_fetch_url($data["poll"]);
633 if (!$feedret["success"]) {
634 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
635 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
639 $doc = new DOMDocument();
640 @$doc->loadXML($feedret["body"]);
642 $xpath = new DomXPath($doc);
643 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
645 $entries = $xpath->query('/atom:feed/atom:entry');
649 foreach ($entries AS $entry) {
650 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
651 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
653 if ($last_updated < $published)
654 $last_updated = $published;
656 if ($last_updated < $updated)
657 $last_updated = $updated;
660 // Maybe there aren't any entries. Then check if it is a valid feed
661 if ($last_updated == "")
662 if ($xpath->query('/atom:feed')->length > 0)
663 $last_updated = "0000-00-00 00:00:00";
665 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
666 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
668 if (($gcontacts[0]["generation"] == 0))
669 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
670 dbesc(normalise_link($profile)));
672 return($last_updated);
675 function poco_do_update($created, $updated, $last_failure, $last_contact) {
676 $now = strtotime(datetime_convert());
678 if ($updated > $last_contact)
679 $contact_time = strtotime($updated);
681 $contact_time = strtotime($last_contact);
683 $failure_time = strtotime($last_failure);
684 $created_time = strtotime($created);
686 // If there is no "created" time then use the current time
687 if ($created_time <= 0)
688 $created_time = $now;
690 // If the last contact was less than 24 hours then don't update
691 if (($now - $contact_time) < (60 * 60 * 24))
694 // If the last failure was less than 24 hours then don't update
695 if (($now - $failure_time) < (60 * 60 * 24))
698 // If the last contact was less than a week ago and the last failure is older than a week then don't update
699 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
702 // 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
703 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
706 // 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
707 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
713 function poco_to_boolean($val) {
714 if (($val == "true") OR ($val == 1))
716 if (($val == "false") OR ($val == 0))
722 function poco_check_server($server_url, $network = "", $force = false) {
724 // Unify the server address
725 $server_url = trim($server_url, "/");
726 $server_url = str_replace("/index.php", "", $server_url);
728 if ($server_url == "")
731 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
734 if ($servers[0]["created"] == "0000-00-00 00:00:00")
735 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
736 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
738 $poco = $servers[0]["poco"];
739 $noscrape = $servers[0]["noscrape"];
742 $network = $servers[0]["network"];
744 $last_contact = $servers[0]["last_contact"];
745 $last_failure = $servers[0]["last_failure"];
746 $version = $servers[0]["version"];
747 $platform = $servers[0]["platform"];
748 $site_name = $servers[0]["site_name"];
749 $info = $servers[0]["info"];
750 $register_policy = $servers[0]["register_policy"];
752 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
753 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
754 return ($last_contact >= $last_failure);
763 $register_policy = -1;
765 $last_contact = "0000-00-00 00:00:00";
766 $last_failure = "0000-00-00 00:00:00";
768 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
771 $orig_last_failure = $last_failure;
773 // Check if the page is accessible via SSL.
774 $server_url = str_replace("http://", "https://", $server_url);
775 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
777 // Maybe the page is unencrypted only?
778 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
779 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
780 $server_url = str_replace("https://", "http://", $server_url);
781 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
783 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
786 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
787 // Workaround for bad configured servers (known nginx problem)
788 if ($serverret["debug"]["http_code"] != "403") {
789 $last_failure = datetime_convert();
792 } elseif ($network == NETWORK_DIASPORA)
793 $last_contact = datetime_convert();
797 $serverret = z_fetch_url($server_url);
799 $lines = explode("\n",$serverret["header"]);
801 foreach($lines as $line) {
803 if(stristr($line,'X-Diaspora-Version:')) {
804 $platform = "Diaspora";
805 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
806 $version = trim(str_replace("x-diaspora-version:", "", $version));
807 $network = NETWORK_DIASPORA;
808 $versionparts = explode("-", $version);
809 $version = $versionparts[0];
815 // Test for Statusnet
816 // Will also return data for Friendica and GNU Social - but it will be overwritten later
817 // The "not implemented" is a special treatment for really, really old Friendica versions
818 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
819 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
820 $platform = "StatusNet";
821 $version = trim($serverret["body"], '"');
822 $network = NETWORK_OSTATUS;
825 // Test for GNU Social
826 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
827 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
828 $platform = "GNU Social";
829 $version = trim($serverret["body"], '"');
830 $network = NETWORK_OSTATUS;
833 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
834 if ($serverret["success"]) {
835 $data = json_decode($serverret["body"]);
837 if (isset($data->site->server)) {
838 $last_contact = datetime_convert();
840 if (isset($data->site->hubzilla)) {
841 $platform = $data->site->hubzilla->PLATFORM_NAME;
842 $version = $data->site->hubzilla->RED_VERSION;
843 $network = NETWORK_DIASPORA;
845 if (isset($data->site->redmatrix)) {
846 if (isset($data->site->redmatrix->PLATFORM_NAME))
847 $platform = $data->site->redmatrix->PLATFORM_NAME;
848 elseif (isset($data->site->redmatrix->RED_PLATFORM))
849 $platform = $data->site->redmatrix->RED_PLATFORM;
851 $version = $data->site->redmatrix->RED_VERSION;
852 $network = NETWORK_DIASPORA;
854 if (isset($data->site->friendica)) {
855 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
856 $version = $data->site->friendica->FRIENDICA_VERSION;
857 $network = NETWORK_DFRN;
860 $site_name = $data->site->name;
862 $data->site->closed = poco_to_boolean($data->site->closed);
863 $data->site->private = poco_to_boolean($data->site->private);
864 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
866 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
867 $register_policy = REGISTER_APPROVE;
868 elseif (!$data->site->closed AND !$data->site->private)
869 $register_policy = REGISTER_OPEN;
871 $register_policy = REGISTER_CLOSED;
876 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
878 $serverret = z_fetch_url($server_url."/statistics.json");
879 if ($serverret["success"]) {
880 $data = json_decode($serverret["body"]);
882 $version = $data->version;
884 $site_name = $data->name;
886 if (isset($data->network) AND ($platform == ""))
887 $platform = $data->network;
889 if ($platform == "Diaspora")
890 $network = NETWORK_DIASPORA;
892 if ($data->registrations_open)
893 $register_policy = REGISTER_OPEN;
895 $register_policy = REGISTER_CLOSED;
897 if (isset($data->version))
898 $last_contact = datetime_convert();
902 // Check for noscrape
903 // Friendica servers could be detected as OStatus servers
904 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
905 $serverret = z_fetch_url($server_url."/friendica/json");
907 if (!$serverret["success"])
908 $serverret = z_fetch_url($server_url."/friendika/json");
910 if ($serverret["success"]) {
911 $data = json_decode($serverret["body"]);
913 if (isset($data->version)) {
914 $last_contact = datetime_convert();
915 $network = NETWORK_DFRN;
917 $noscrape = $data->no_scrape_url;
918 $version = $data->version;
919 $site_name = $data->site_name;
921 $register_policy_str = $data->register_policy;
922 $platform = $data->platform;
924 switch ($register_policy_str) {
925 case "REGISTER_CLOSED":
926 $register_policy = REGISTER_CLOSED;
928 case "REGISTER_APPROVE":
929 $register_policy = REGISTER_APPROVE;
931 case "REGISTER_OPEN":
932 $register_policy = REGISTER_OPEN;
941 $serverret = z_fetch_url($server_url."/poco");
942 if ($serverret["success"]) {
943 $data = json_decode($serverret["body"]);
944 if (isset($data->totalResults)) {
945 $poco = $server_url."/poco";
946 $last_contact = datetime_convert();
951 // Check again if the server exists
952 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
955 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
956 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
961 intval($register_policy),
966 dbesc($last_contact),
967 dbesc($last_failure),
968 dbesc(normalise_link($server_url))
971 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
972 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
974 dbesc(normalise_link($server_url)),
978 intval($register_policy),
983 dbesc(datetime_convert()),
984 dbesc($last_contact),
985 dbesc($last_failure),
986 dbesc(datetime_convert())
989 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
994 function poco_contact_from_body($body, $created, $cid, $uid) {
995 preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
996 function ($match) use ($created, $cid, $uid){
997 return(sub_poco_from_share($match, $created, $cid, $uid));
1001 function sub_poco_from_share($share, $created, $cid, $uid) {
1003 preg_match("/profile='(.*?)'/ism", $share[1], $matches);
1004 if ($matches[1] != "")
1005 $profile = $matches[1];
1007 preg_match('/profile="(.*?)"/ism', $share[1], $matches);
1008 if ($matches[1] != "")
1009 $profile = $matches[1];
1014 logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
1015 poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
1018 function poco_store($item) {
1021 if ($item['private'])
1024 // Or is it from a network where we don't store the global contacts?
1025 if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
1028 // Is it a global copy?
1029 $store_gcontact = ($item["uid"] == 0);
1031 // Is it a comment on a global copy?
1032 if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
1033 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
1034 $store_gcontact = count($q);
1037 if (!$store_gcontact)
1040 // "3" means: We don't know this contact directly (Maybe a reshared item)
1043 $profile_url = $item["author-link"];
1045 // Is it a user from our server?
1046 $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
1047 dbesc(normalise_link($item["author-link"])));
1049 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
1051 $network = NETWORK_DFRN;
1052 } else { // Is it a contact from a user on our server?
1053 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
1054 AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
1055 dbesc(normalise_link($item["author-link"])),
1056 dbesc(normalise_link($item["author-link"])),
1057 dbesc($item["author-link"]),
1058 dbesc(NETWORK_STATUSNET));
1061 $network = $q[0]["network"];
1062 $profile_url = $q[0]["url"];
1063 logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
1067 if ($generation == 3)
1068 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
1070 poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
1072 // Maybe its a body with a shared item? Then extract a global contact from it.
1073 poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
1076 function count_common_friends($uid,$cid) {
1078 $r = q("SELECT count(*) as `total`
1079 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1080 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1081 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1082 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1089 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1091 return $r[0]['total'];
1097 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1100 $sql_extra = " order by rand() ";
1102 $sql_extra = " order by `gcontact`.`name` asc ";
1104 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1106 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1107 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1108 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1109 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1110 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1111 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1112 $sql_extra LIMIT %d, %d",
1126 function count_common_friends_zcid($uid,$zcid) {
1128 $r = q("SELECT count(*) as `total`
1129 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1130 where `glink`.`zcid` = %d
1131 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1137 return $r[0]['total'];
1142 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1145 $sql_extra = " order by rand() ";
1147 $sql_extra = " order by `gcontact`.`name` asc ";
1149 $r = q("SELECT `gcontact`.*
1150 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1151 where `glink`.`zcid` = %d
1152 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1153 $sql_extra limit %d, %d",
1165 function count_all_friends($uid,$cid) {
1167 $r = q("SELECT count(*) as `total`
1168 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1169 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1170 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1176 return $r[0]['total'];
1182 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1184 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1186 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1187 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1188 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1189 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1190 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1203 function suggestion_query($uid, $start = 0, $limit = 80) {
1208 $network = array(NETWORK_DFRN);
1210 if (get_config('system','diaspora_enabled'))
1211 $network[] = NETWORK_DIASPORA;
1213 if (!get_config('system','ostatus_disabled'))
1214 $network[] = NETWORK_OSTATUS;
1216 $sql_network = implode("', '", $network);
1217 //$sql_network = "'".$sql_network."', ''";
1218 $sql_network = "'".$sql_network."'";
1220 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1221 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1222 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1223 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1224 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1225 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1226 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1227 AND `gcontact`.`network` IN (%s)
1228 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1238 if(count($r) && count($r) >= ($limit -1))
1241 $r2 = q("SELECT gcontact.* FROM gcontact
1242 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1243 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1244 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1245 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1246 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1247 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1248 AND `gcontact`.`network` IN (%s)
1249 ORDER BY rand() LIMIT %d, %d",
1259 foreach ($r2 AS $suggestion)
1260 $list[$suggestion["nurl"]] = $suggestion;
1262 foreach ($r AS $suggestion)
1263 $list[$suggestion["nurl"]] = $suggestion;
1265 while (sizeof($list) > ($limit))
1271 function update_suggestions() {
1277 /// TODO Check if it is really neccessary to poll the own server
1278 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1280 $done[] = $a->get_baseurl() . '/poco';
1282 if(strlen(get_config('system','directory'))) {
1283 $x = fetch_url(get_server()."/pubsites");
1285 $j = json_decode($x);
1287 foreach($j->entries as $entry) {
1289 poco_check_server($entry->url);
1291 $url = $entry->url . '/poco';
1292 if(! in_array($url,$done))
1293 poco_load(0,0,0,$entry->url . '/poco');
1299 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1300 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1301 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1305 foreach($r as $rr) {
1306 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1307 if(! in_array($base,$done))
1308 poco_load(0,0,0,$base);
1313 function poco_discover_federation() {
1314 $last = get_config('poco','last_federation_discovery');
1317 $next = $last + (24 * 60 * 60);
1322 // Discover Friendica, Hubzilla and Diaspora servers
1323 $serverdata = fetch_url("http://the-federation.info/pods.json");
1326 $servers = json_decode($serverdata);
1328 foreach($servers->pods AS $server)
1329 poco_check_server("https://".$server->host);
1332 // Discover GNU Social Servers
1333 if (!get_config('system','ostatus_disabled')) {
1334 $serverdata = "http://gstools.org/api/get_open_instances/";
1336 $result = z_fetch_url($serverdata);
1337 if ($result["success"]) {
1338 $servers = json_decode($result["body"]);
1340 foreach($servers->data AS $server)
1341 poco_check_server($server->instance_address);
1345 set_config('poco','last_federation_discovery', time());
1348 function poco_discover($complete = false) {
1350 // Update the server list
1351 poco_discover_federation();
1355 $requery_days = intval(get_config("system", "poco_requery_days"));
1357 if ($requery_days == 0)
1360 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1362 $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));
1364 foreach ($r AS $server) {
1366 if (!poco_check_server($server["url"], $server["network"])) {
1367 // The server is not reachable? Okay, then we will try it later
1368 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1372 // Fetch all users from the other server
1373 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1375 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1377 $retdata = z_fetch_url($url);
1378 if ($retdata["success"]) {
1379 $data = json_decode($retdata["body"]);
1381 poco_discover_server($data, 2);
1383 if (get_config('system','poco_discovery') > 1) {
1385 $timeframe = get_config('system','poco_discovery_since');
1386 if ($timeframe == 0)
1389 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1391 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1392 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1396 $retdata = z_fetch_url($url);
1397 if ($retdata["success"]) {
1398 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1399 $success = poco_discover_server(json_decode($retdata["body"]));
1402 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1403 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1404 poco_discover_server_users($data, $server);
1408 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1409 if (!$complete AND (--$no_of_queries == 0))
1412 // If the server hadn't replied correctly, then force a sanity check
1413 poco_check_server($server["url"], $server["network"], true);
1415 // If we couldn't reach the server, we will try it some time later
1416 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1421 function poco_discover_server_users($data, $server) {
1423 if (!isset($data->entry))
1426 foreach ($data->entry AS $entry) {
1428 if (isset($entry->urls)) {
1429 foreach($entry->urls as $url)
1430 if($url->type == 'profile') {
1431 $profile_url = $url->value;
1432 $urlparts = parse_url($profile_url);
1433 $username = end(explode("/", $urlparts["path"]));
1436 if ($username != "") {
1437 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1439 // Fetch all contacts from a given user from the other server
1440 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1442 $retdata = z_fetch_url($url);
1443 if ($retdata["success"])
1444 poco_discover_server(json_decode($retdata["body"]), 3);
1449 function poco_discover_server($data, $default_generation = 0) {
1451 if (!isset($data->entry) OR !count($data->entry))
1456 foreach ($data->entry AS $entry) {
1458 $profile_photo = '';
1462 $updated = '0000-00-00 00:00:00';
1467 $generation = $default_generation;
1469 $name = $entry->displayName;
1471 if(isset($entry->urls)) {
1472 foreach($entry->urls as $url) {
1473 if($url->type == 'profile') {
1474 $profile_url = $url->value;
1477 if($url->type == 'webfinger') {
1478 $connect_url = str_replace('acct:' , '', $url->value);
1484 if(isset($entry->photos)) {
1485 foreach($entry->photos as $photo) {
1486 if($photo->type == 'profile') {
1487 $profile_photo = $photo->value;
1493 if(isset($entry->updated))
1494 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1496 if(isset($entry->network))
1497 $network = $entry->network;
1499 if(isset($entry->currentLocation))
1500 $location = $entry->currentLocation;
1502 if(isset($entry->aboutMe))
1503 $about = html2bbcode($entry->aboutMe);
1505 if(isset($entry->gender))
1506 $gender = $entry->gender;
1508 if(isset($entry->generation) AND ($entry->generation > 0))
1509 $generation = ++$entry->generation;
1511 if(isset($entry->tags))
1512 foreach($entry->tags as $tag)
1513 $keywords = implode(", ", $tag);
1515 if ($generation > 0) {
1518 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1519 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1520 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1527 * @brief Fetch the gcontact id, add an entry if not existed
1529 * @param arr $contact contact array
1530 * @return bool|int Returns false if not found, integer if contact was found
1532 function get_gcontact_id($contact) {
1536 if ($contact["network"] == NETWORK_STATUSNET)
1537 $contact["network"] = NETWORK_OSTATUS;
1539 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1540 dbesc(normalise_link($contact["url"])));
1543 $gcontact_id = $r[0]["id"];
1545 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `generation`)
1546 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
1547 dbesc($contact["name"]),
1548 dbesc($contact["nick"]),
1549 dbesc($contact["addr"]),
1550 dbesc($contact["network"]),
1551 dbesc($contact["url"]),
1552 dbesc(normalise_link($contact["url"])),
1553 dbesc($contact["photo"]),
1554 dbesc(datetime_convert()),
1555 dbesc(datetime_convert()),
1556 dbesc($contact["location"]),
1557 dbesc($contact["about"]),
1558 intval($contact["generation"])
1561 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1562 dbesc(normalise_link($contact["url"])));
1565 $gcontact_id = $r[0]["id"];
1568 return $gcontact_id;
1572 * @brief Updates the gcontact table from a given array
1574 * @param arr $contact contact array
1575 * @return bool|int Returns false if not found, integer if contact was found
1577 function update_gcontact($contact) {
1579 /// @todo update contact table as well
1581 $gcontact_id = get_gcontact_id($contact);
1586 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`, `hide`, `nsfw`, `network`, `alias`, `notify`, `url`
1587 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1588 intval($gcontact_id));
1590 if ($contact["generation"] == 0)
1591 $contact["generation"] = $r[0]["generation"];
1593 if ($contact["photo"] == "")
1594 $contact["photo"] = $r[0]["photo"];
1596 if ($contact["name"] == "")
1597 $contact["name"] = $r[0]["name"];
1599 if ($contact["nick"] == "")
1600 $contact["nick"] = $r[0]["nick"];
1602 if ($contact["addr"] == "")
1603 $contact["addr"] = $r[0]["addr"];
1605 if ($contact["location"] =="")
1606 $contact["location"] = $r[0]["location"];
1608 if ($contact["about"] =="")
1609 $contact["about"] = $r[0]["about"];
1611 if ($contact["birthday"] =="")
1612 $contact["birthday"] = $r[0]["birthday"];
1614 if ($contact["gender"] =="")
1615 $contact["gender"] = $r[0]["gender"];
1617 if ($contact["keywords"] =="")
1618 $contact["keywords"] = $r[0]["keywords"];
1620 if (!isset($contact["hide"]))
1621 $contact["hide"] = $r[0]["hide"];
1623 if (!isset($contact["nsfw"]))
1624 $contact["nsfw"] = $r[0]["nsfw"];
1626 if ($contact["network"] =="")
1627 $contact["network"] = $r[0]["network"];
1629 if ($contact["alias"] =="")
1630 $contact["alias"] = $r[0]["alias"];
1632 if ($contact["url"] =="")
1633 $contact["url"] = $r[0]["url"];
1635 if ($contact["notify"] =="")
1636 $contact["notify"] = $r[0]["notify"];
1638 if ($contact["network"] == NETWORK_STATUSNET)
1639 $contact["network"] = NETWORK_OSTATUS;
1641 if (($contact["photo"] != $r[0]["photo"]) OR ($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["addr"] != $r[0]["addr"]) OR
1642 ($contact["birthday"] != $r[0]["birthday"]) OR ($contact["gender"] != $r[0]["gender"]) OR ($contact["keywords"] != $r[0]["keywords"]) OR
1643 ($contact["hide"] != $r[0]["hide"]) OR ($contact["nsfw"] != $r[0]["nsfw"]) OR ($contact["network"] != $r[0]["network"]) OR
1644 ($contact["alias"] != $r[0]["alias"]) OR ($contact["notify"] != $r[0]["notify"]) OR ($contact["url"] != $r[0]["url"]) OR
1645 ($contact["location"] != $r[0]["location"]) OR ($contact["about"] != $r[0]["about"]) OR ($contact["generation"] < $r[0]["generation"])) {
1647 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1648 `birthday` = '%s', `gender` = '%s', `keywords` = %d, `hide` = %d, `nsfw` = %d,
1649 `alias` = '%s', `notify` = '%s', `url` = '%s',
1650 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s'
1651 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1652 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1653 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1654 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1655 intval($contact["nsfw"]), dbesc($contact["alias"]), dbesc($contact["notify"]),
1656 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1657 intval($contact["generation"]), dbesc(datetime_convert()),
1658 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1661 return $gcontact_id;
1665 * @brief Updates the gcontact entry from probe
1667 * @param str $url profile link
1669 function update_gcontact_from_probe($url) {
1670 $data = probe_url($url);
1672 if ($data["network"] != NETWORK_PHANTOM)
1673 update_gcontact($data);
1677 * @brief Fetches users of given GNU Social server
1679 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1681 * @param str $server Server address
1683 function gs_fetch_users($server) {
1685 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1689 $url = $server."/main/statistics";
1691 $result = z_fetch_url($url);
1692 if (!$result["success"])
1695 $statistics = json_decode($result["body"]);
1697 if (is_object($statistics->config)) {
1698 if ($statistics->config->instance_with_ssl)
1699 $server = "https://";
1701 $server = "http://";
1703 $server .= $statistics->config->instance_address;
1705 $hostname = $statistics->config->instance_address;
1707 if ($statistics->instance_with_ssl)
1708 $server = "https://";
1710 $server = "http://";
1712 $server .= $statistics->instance_address;
1714 $hostname = $statistics->instance_address;
1717 foreach ($statistics->users AS $nick => $user) {
1718 $profile_url = $server."/".$user->nickname;
1720 $contact = array("url" => $profile_url,
1721 "name" => $user->fullname,
1722 "addr" => $user->nickname."@".$hostname,
1723 "nick" => $user->nickname,
1724 "about" => $user->bio,
1725 "network" => NETWORK_OSTATUS,
1726 "photo" => $a->get_baseurl()."/images/person-175.jpg");
1727 get_gcontact_id($contact);
1732 * @brief Asking GNU Social server on a regular base for their user data
1735 function gs_discover() {
1737 $requery_days = intval(get_config("system", "poco_requery_days"));
1739 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1741 $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",
1742 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1747 foreach ($r AS $server) {
1748 gs_fetch_users($server["url"]);
1749 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));