3 require_once('include/datetime.php');
4 require_once("include/Scrape.php");
5 require_once("include/html2bbcode.php");
10 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
11 * and add the entries to the gcontact (Global Contact) table, or update existing entries
12 * if anything (name or photo) has changed.
13 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
15 * Once the global contact is stored add (if necessary) the contact linkage which associates
16 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
17 * pointing to the same global contact id.
24 function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
29 if((! $url) || (! $uid)) {
30 $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
45 $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') ;
47 logger('poco_load: ' . $url, LOGGER_DEBUG);
51 logger('poco_load: returns ' . $s, LOGGER_DATA);
53 logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
55 if(($a->get_curl_code() > 299) || (! $s))
60 logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
62 if(! isset($j->entry))
66 foreach($j->entry as $entry) {
74 $updated = '0000-00-00 00:00:00';
81 $name = $entry->displayName;
83 if(isset($entry->urls)) {
84 foreach($entry->urls as $url) {
85 if($url->type == 'profile') {
86 $profile_url = $url->value;
89 if($url->type == 'webfinger') {
90 $connect_url = str_replace('acct:' , '', $url->value);
95 if(isset($entry->photos)) {
96 foreach($entry->photos as $photo) {
97 if($photo->type == 'profile') {
98 $profile_photo = $photo->value;
104 if(isset($entry->updated))
105 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
107 if(isset($entry->network))
108 $network = $entry->network;
110 if(isset($entry->currentLocation))
111 $location = $entry->currentLocation;
113 if(isset($entry->aboutMe))
114 $about = html2bbcode($entry->aboutMe);
116 if(isset($entry->gender))
117 $gender = $entry->gender;
119 if(isset($entry->generation) AND ($entry->generation > 0))
120 $generation = ++$entry->generation;
122 if(isset($entry->tags))
123 foreach($entry->tags as $tag)
124 $keywords = implode(", ", $tag);
126 // If you query a Friendica server for its profiles, the network has to be Friendica
127 // To-Do: It could also be a Redmatrix server
129 // $network = NETWORK_DFRN;
131 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
133 // Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
134 if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
135 q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
136 WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
141 dbesc(normalise_link($profile_url)),
142 dbesc(NETWORK_DFRN));
144 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
146 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
154 function poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid = 0, $uid = 0, $zcid = 0) {
160 // 1: Profiles on this server
161 // 2: Contacts of profiles on this server
162 // 3: Contacts of contacts of profiles on this server
167 if ($profile_url == "")
170 $orig_updated = $updated;
172 // Don't store the statusnet connector as network
173 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
174 if ($network == NETWORK_STATUSNET)
177 // The global contacts should contain the original picture, not the cached one
178 if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link($a->get_baseurl()."/photo/")))
181 $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
182 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
185 $network = $r[0]["network"];
187 if (($network == "") OR ($network == NETWORK_OSTATUS)) {
188 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
189 dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
192 $network = $r[0]["network"];
193 $profile_url = $r[0]["url"];
197 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
198 dbesc(normalise_link($profile_url))
202 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
203 $network = $x[0]["network"];
205 if ($updated == "0000-00-00 00:00:00")
206 $updated = $x[0]["updated"];
208 $last_contact = $x[0]["last_contact"];
209 $last_failure = $x[0]["last_failure"];
210 $server_url = $x[0]["server_url"];
212 $last_contact = "0000-00-00 00:00:00";
213 $last_failure = "0000-00-00 00:00:00";
217 if (($network == "") OR ($name == "") OR ($profile_photo == "") OR ($server_url == "")) {
218 $data = probe_url($profile_url);
219 $network = $data["network"];
220 $name = $data["name"];
221 $profile_url = $data["url"];
222 $profile_photo = $data["photo"];
223 $server_url = $data["baseurl"];
226 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
227 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
229 dbesc(normalise_link($profile_url))
233 if (($name == "") OR ($profile_photo == ""))
236 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
239 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
241 poco_check_server($server_url, $network);
243 // Only fetch last update manually if it wasn't provided and enabled in the system
244 if (get_config('system','poco_completion') AND ($orig_updated == "0000-00-00 00:00:00") AND poco_do_update($updated, $last_contact, $last_failure)) {
245 $last_updated = poco_last_updated($profile_url);
247 $updated = $last_updated;
248 $last_contact = datetime_convert();
249 logger("Last updated for profile ".$profile_url.": ".$updated, LOGGER_DEBUG);
251 $last_failure = datetime_convert();
257 if (($location == "") AND ($x[0]['location'] != ""))
258 $location = $x[0]['location'];
260 if (($about == "") AND ($x[0]['about'] != ""))
261 $about = $x[0]['about'];
263 if (($gender == "") AND ($x[0]['gender'] != ""))
264 $gender = $x[0]['gender'];
266 if (($keywords == "") AND ($x[0]['keywords'] != ""))
267 $keywords = $x[0]['keywords'];
269 if (($generation == 0) AND ($x[0]['generation'] > 0))
270 $generation = $x[0]['generation'];
272 if($x[0]['name'] != $name || $x[0]['photo'] != $profile_photo || $x[0]['updated'] < $updated) {
273 q("UPDATE `gcontact` SET `name` = '%s', `network` = '%s', `photo` = '%s', `connect` = '%s', `url` = '%s', `server_url` = '%s',
274 `updated` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s', `generation` = %d
275 WHERE (`generation` >= %d OR `generation` = 0) AND `nurl` = '%s'",
278 dbesc($profile_photo),
289 dbesc(normalise_link($profile_url))
293 q("INSERT INTO `gcontact` (`name`,`network`, `url`,`nurl`,`photo`,`connect`, `server_url`, `updated`, `last_contact`, `last_failure`, `location`, `about`, `keywords`, `gender`, `generation`)
294 VALUES ('%s', '%s', '%s', '%s', '%s','%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
298 dbesc(normalise_link($profile_url)),
299 dbesc($profile_photo),
303 dbesc($last_contact),
304 dbesc($last_failure),
311 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
312 dbesc(normalise_link($profile_url))
321 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
328 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
333 dbesc(datetime_convert())
336 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
337 dbesc(datetime_convert()),
345 // For unknown reasons there are sometimes duplicates
346 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d AND
347 NOT EXISTS (SELECT `gcid` FROM `glink` WHERE `gcid` = `gcontact`.`id`)",
348 dbesc(normalise_link($profile_url)),
355 function poco_last_updated($profile) {
357 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
358 dbesc(normalise_link($profile)));
360 if ($gcontacts[0]["server_url"] != "") {
361 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` < `last_failure`", dbesc(normalise_link($gcontacts[0]["server_url"])));
367 $data = probe_url($profile);
369 if (($data["poll"] == "") OR ($data["network"] == NETWORK_FEED)) {
370 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
371 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
375 if (($data["name"] != "") AND ($data["name"] != $gcontacts[0]["name"]))
376 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
377 dbesc($data["name"]), dbesc(normalise_link($profile)));
379 if (($data["addr"] != "") AND ($data["addr"] != $gcontacts[0]["connect"]))
380 q("UPDATE `gcontact` SET `connect` = '%s' WHERE `nurl` = '%s'",
381 dbesc($data["addr"]), dbesc(normalise_link($profile)));
383 if (($data["photo"] != "") AND ($data["photo"] != $gcontacts[0]["photo"]))
384 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
385 dbesc($data["photo"]), dbesc(normalise_link($profile)));
387 if (($data["baseurl"] != "") AND ($data["baseurl"] != $gcontacts[0]["server_url"]))
388 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
389 dbesc($data["baseurl"]), dbesc(normalise_link($profile)));
391 if ($data["baseurl"] != "")
392 poco_check_server($data["baseurl"], $data["network"]);
394 // To-Do: Use noscrape
396 $feedret = z_fetch_url($data["poll"]);
398 if (!$feedret["success"]) {
399 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
400 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
404 $doc = new DOMDocument();
405 @$doc->loadXML($feedret["body"]);
407 $xpath = new DomXPath($doc);
408 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
410 $entries = $xpath->query('/atom:feed/atom:entry');
414 foreach ($entries AS $entry) {
415 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
416 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
418 if ($last_updated < $published)
419 $last_updated = $published;
421 if ($last_updated < $updated)
422 $last_updated = $updated;
425 // Maybe there aren't any entries. Then check if it is a valid feed
426 if ($last_updated == "")
427 if ($xpath->query('/atom:feed')->length > 0)
428 $last_updated = "0000-00-00 00:00:00";
430 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
431 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
433 return($last_updated);
436 function poco_do_update($updated, $last_contact, $last_failure) {
437 $now = strtotime(datetime_convert());
439 if ($updated > $last_contact)
440 $contact_time = strtotime($updated);
442 $contact_time = strtotime($last_contact);
444 $failure_time = strtotime($last_failure);
446 // If the last contact was less than 24 hours then don't update
447 if (($now - $contact_time) < (60 * 60 * 24))
450 // If the last failure was less than 24 hours then don't update
451 if (($now - $failure_time) < (60 * 60 * 24))
454 // If the last contact was less than a week ago and the last failure is older than a week then don't update
455 if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
458 // If the last contact time was more than a week ago, then only try once a week
459 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
462 // If the last contact time was more than a month ago, then only try once a month - but only if there ever was a contact time
463 if (($contact_time > 0) AND (($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
469 function poco_to_boolean($val) {
470 if (($val == "true") OR ($val == 1))
472 if (($val == "false") OR ($val == 0))
478 function poco_check_server($server_url, $network = "") {
480 if ($server_url == "")
483 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
485 $poco = $servers[0]["poco"];
486 $noscrape = $servers[0]["noscrape"];
489 $network = $servers[0]["network"];
491 $last_contact = $servers[0]["last_contact"];
492 $last_failure = $servers[0]["last_failure"];
493 $version = $servers[0]["version"];
494 $platform = $servers[0]["platform"];
495 $site_name = $servers[0]["site_name"];
496 $info = $servers[0]["info"];
497 $register_policy = $servers[0]["register_policy"];
499 if (!poco_do_update("", $last_contact, $last_failure))
500 return ($last_contact >= $last_failure);
508 $register_policy = -1;
510 $last_contact = "0000-00-00 00:00:00";
511 $last_failure = "0000-00-00 00:00:00";
515 $orig_last_failure = $last_failure;
517 // Check if the page is accessible via SSL.
518 $server_url = str_replace("http://", "https://", $server_url);
519 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
521 // Maybe the page is unencrypted only?
522 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
523 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
524 $server_url = str_replace("https://", "http://", $server_url);
525 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
527 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
530 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
531 $last_failure = datetime_convert();
533 } elseif ($network == NETWORK_DIASPORA)
534 $last_contact = datetime_convert();
537 // Test for Statusnet
538 // Will also return data for Friendica and GNU Social - but it will be overwritten later
539 // The "not implemented" is a special treatment for really, really old Friendica versions
540 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
541 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
542 $platform = "StatusNet";
543 $version = trim($serverret["body"], '"');
544 $network = NETWORK_OSTATUS;
547 // Test for GNU Social
548 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
549 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
550 $platform = "GNU Social";
551 $version = trim($serverret["body"], '"');
552 $network = NETWORK_OSTATUS;
555 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
556 if ($serverret["success"]) {
557 $data = json_decode($serverret["body"]);
559 if (isset($data->site->server)) {
560 $last_contact = datetime_convert();
562 if (isset($data->site->redmatrix)) {
563 if (isset($data->site->redmatrix->PLATFORM_NAME))
564 $platform = $data->site->redmatrix->PLATFORM_NAME;
565 elseif (isset($data->site->redmatrix->RED_PLATFORM))
566 $platform = $data->site->redmatrix->RED_PLATFORM;
568 $version = $data->site->redmatrix->RED_VERSION;
569 $network = NETWORK_DIASPORA;
571 if (isset($data->site->friendica)) {
572 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
573 $version = $data->site->friendica->FRIENDICA_VERSION;
574 $network = NETWORK_DFRN;
577 $site_name = $data->site->name;
579 $data->site->closed = poco_to_boolean($data->site->closed);
580 $data->site->private = poco_to_boolean($data->site->private);
581 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
583 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
584 $register_policy = REGISTER_APPROVE;
585 elseif (!$data->site->closed AND !$data->site->private)
586 $register_policy = REGISTER_OPEN;
588 $register_policy = REGISTER_CLOSED;
593 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
595 $serverret = z_fetch_url($server_url."/statistics.json");
596 if ($serverret["success"]) {
597 $data = json_decode($serverret["body"]);
599 $version = $data->version;
601 $site_name = $data->name;
603 if (isset($data->network) AND ($platform == ""))
604 $platform = $data->network;
606 if ($data->registrations_open)
607 $register_policy = REGISTER_OPEN;
609 $register_policy = REGISTER_CLOSED;
611 if (isset($data->version))
612 $last_contact = datetime_convert();
616 // Check for noscrape
617 // Friendica servers could be detected as OStatus servers
618 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
619 $serverret = z_fetch_url($server_url."/friendica/json");
621 if ($serverret["success"]) {
622 $data = json_decode($serverret["body"]);
624 if (isset($data->version)) {
625 $last_contact = datetime_convert();
626 $network = NETWORK_DFRN;
628 $noscrape = $data->no_scrape_url;
629 $version = $data->version;
630 $site_name = $data->site_name;
632 $register_policy_str = $data->register_policy;
633 $platform = $data->platform;
635 switch ($register_policy_str) {
636 case "REGISTER_CLOSED":
637 $register_policy = REGISTER_CLOSED;
639 case "REGISTER_APPROVE":
640 $register_policy = REGISTER_APPROVE;
642 case "REGISTER_OPEN":
643 $register_policy = REGISTER_OPEN;
652 $serverret = z_fetch_url($server_url."/poco");
653 if ($serverret["success"]) {
654 $data = json_decode($serverret["body"]);
655 if (isset($data->totalResults)) {
656 $poco = $server_url."/poco";
657 $last_contact = datetime_convert();
663 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
664 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
669 intval($register_policy),
674 dbesc($last_contact),
675 dbesc($last_failure),
676 dbesc(normalise_link($server_url))
679 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `last_contact`)
680 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s')",
682 dbesc(normalise_link($server_url)),
686 intval($register_policy),
691 dbesc(datetime_convert())
696 function poco_contact_from_body($body, $created, $cid, $uid) {
697 preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
698 function ($match) use ($created, $cid, $uid){
699 return(sub_poco_from_share($match, $created, $cid, $uid));
703 function sub_poco_from_share($share, $created, $cid, $uid) {
705 preg_match("/profile='(.*?)'/ism", $share[1], $matches);
706 if ($matches[1] != "")
707 $profile = $matches[1];
709 preg_match('/profile="(.*?)"/ism', $share[1], $matches);
710 if ($matches[1] != "")
711 $profile = $matches[1];
716 logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
717 poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
720 function poco_store($item) {
723 if ($item['private'])
726 // Or is it from a network where we don't store the global contacts?
727 if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
730 // Is it a global copy?
731 $store_gcontact = ($item["uid"] == 0);
733 // Is it a comment on a global copy?
734 if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
735 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
736 $store_gcontact = count($q);
739 if (!$store_gcontact)
742 // "3" means: We don't know this contact directly (Maybe a reshared item)
745 $profile_url = $item["author-link"];
747 // Is it a user from our server?
748 $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
749 dbesc(normalise_link($item["author-link"])));
751 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
753 $network = NETWORK_DFRN;
754 } else { // Is it a contact from a user on our server?
755 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
756 AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
757 dbesc(normalise_link($item["author-link"])),
758 dbesc(normalise_link($item["author-link"])),
759 dbesc($item["author-link"]),
760 dbesc(NETWORK_STATUSNET));
763 $network = $q[0]["network"];
764 $profile_url = $q[0]["url"];
765 logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
769 if ($generation == 3)
770 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
772 poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
774 // Maybe its a body with a shared item? Then extract a global contact from it.
775 poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
778 function count_common_friends($uid,$cid) {
780 $r = q("SELECT count(*) as `total`
781 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
782 where `glink`.`cid` = %d and `glink`.`uid` = %d
783 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
790 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
792 return $r[0]['total'];
798 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
801 $sql_extra = " order by rand() ";
803 $sql_extra = " order by `gcontact`.`name` asc ";
805 $r = q("SELECT `gcontact`.*
806 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
807 where `glink`.`cid` = %d and `glink`.`uid` = %d
808 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d )
809 $sql_extra limit %d, %d",
823 function count_common_friends_zcid($uid,$zcid) {
825 $r = q("SELECT count(*) as `total`
826 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
827 where `glink`.`zcid` = %d
828 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
834 return $r[0]['total'];
839 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
842 $sql_extra = " order by rand() ";
844 $sql_extra = " order by `gcontact`.`name` asc ";
846 $r = q("SELECT `gcontact`.*
847 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
848 where `glink`.`zcid` = %d
849 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
850 $sql_extra limit %d, %d",
862 function count_all_friends($uid,$cid) {
864 $r = q("SELECT count(*) as `total`
865 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
866 where `glink`.`cid` = %d and `glink`.`uid` = %d ",
872 return $r[0]['total'];
878 function all_friends($uid,$cid,$start = 0, $limit = 80) {
880 $r = q("SELECT `gcontact`.*
881 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
882 where `glink`.`cid` = %d and `glink`.`uid` = %d
883 order by `gcontact`.`name` asc LIMIT %d, %d ",
895 function suggestion_query($uid, $start = 0, $limit = 80) {
900 $network = array(NETWORK_DFRN);
902 if (get_config('system','diaspora_enabled'))
903 $network[] = NETWORK_DIASPORA;
905 if (!get_config('system','ostatus_disabled'))
906 $network[] = NETWORK_OSTATUS;
908 $sql_network = implode("', '", $network);
909 //$sql_network = "'".$sql_network."', ''";
910 $sql_network = "'".$sql_network."'";
912 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
913 INNER JOIN glink on glink.gcid = gcontact.id
914 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
915 and not gcontact.name in ( select name from contact where uid = %d )
916 and not gcontact.id in ( select gcid from gcign where uid = %d )
917 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
918 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
919 AND `gcontact`.`network` IN (%s)
920 group by glink.gcid order by gcontact.updated desc,total desc limit %d, %d ",
930 if(count($r) && count($r) >= ($limit -1))
933 $r2 = q("SELECT gcontact.* from gcontact
934 INNER JOIN glink on glink.gcid = gcontact.id
935 where glink.uid = 0 and glink.cid = 0 and glink.zcid = 0 and not gcontact.nurl in ( select nurl from contact where uid = %d )
936 and not gcontact.name in ( select name from contact where uid = %d )
937 and not gcontact.id in ( select gcid from gcign where uid = %d )
938 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
939 AND `gcontact`.`network` IN (%s)
940 order by rand() limit %d, %d ",
950 foreach ($r2 AS $suggestion)
951 $list[$suggestion["nurl"]] = $suggestion;
953 foreach ($r AS $suggestion)
954 $list[$suggestion["nurl"]] = $suggestion;
959 function update_suggestions() {
965 // To-Do: Check if it is really neccessary to poll the own server
966 poco_load(0,0,0,$a->get_baseurl() . '/poco');
968 $done[] = $a->get_baseurl() . '/poco';
970 if(strlen(get_config('system','directory_submit_url'))) {
971 $x = fetch_url('http://dir.friendica.com/pubsites');
973 $j = json_decode($x);
975 foreach($j->entries as $entry) {
977 poco_check_server($entry->url);
979 $url = $entry->url . '/poco';
980 if(! in_array($url,$done))
981 poco_load(0,0,0,$entry->url . '/poco');
987 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
988 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
989 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
994 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
995 if(! in_array($base,$done))
996 poco_load(0,0,0,$base);
1001 function poco_discover($complete = false) {
1003 $last_update = date("c", time() - (60 * 60 * 24));
1005 $r = q("SELECT `poco`, `nurl` FROM `gserver` WHERE `last_contact` > `last_failure` AND `poco` != '' AND `last_poco_query` < '%s' ORDER BY RAND()", dbesc($last_update));
1007 foreach ($r AS $server) {
1008 // Fetch all users from the other server
1009 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1011 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1013 $retdata = z_fetch_url($url);
1014 if ($retdata["success"]) {
1015 $data = json_decode($retdata["body"]);
1016 poco_discover_server($data, 2);
1018 if (get_config('system','poco_discovery') > 1) {
1020 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1021 $url = $server["poco"]."/@global?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1023 $retdata = z_fetch_url($url);
1024 if ($retdata["success"]) {
1025 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1026 poco_discover_server(json_decode($retdata["body"]));
1027 } elseif (get_config('system','poco_discovery') > 2) {
1028 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1029 poco_discover_server_users($data);
1033 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1040 function poco_discover_server_users($data) {
1041 foreach ($data->entry AS $entry) {
1043 if (isset($entry->urls)) {
1044 foreach($entry->urls as $url)
1045 if($url->type == 'profile') {
1046 $profile_url = $url->value;
1047 $urlparts = parse_url($profile_url);
1048 $username = end(explode("/", $urlparts["path"]));
1051 if ($username != "") {
1052 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1054 // Fetch all contacts from a given user from the other server
1055 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1057 $retdata = z_fetch_url($url);
1058 if ($retdata["success"])
1059 poco_discover_server(json_decode($retdata["body"]), 3);
1064 function poco_discover_server($data, $default_generation = 0) {
1066 if (!isset($data->entry) OR !count($data->entry))
1069 foreach ($data->entry AS $entry) {
1071 $profile_photo = '';
1075 $updated = '0000-00-00 00:00:00';
1080 $generation = $default_generation;
1082 $name = $entry->displayName;
1084 if(isset($entry->urls)) {
1085 foreach($entry->urls as $url) {
1086 if($url->type == 'profile') {
1087 $profile_url = $url->value;
1090 if($url->type == 'webfinger') {
1091 $connect_url = str_replace('acct:' , '', $url->value);
1096 if(isset($entry->photos)) {
1097 foreach($entry->photos as $photo) {
1098 if($photo->type == 'profile') {
1099 $profile_photo = $photo->value;
1105 if(isset($entry->updated))
1106 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1108 if(isset($entry->network))
1109 $network = $entry->network;
1111 if(isset($entry->currentLocation))
1112 $location = $entry->currentLocation;
1114 if(isset($entry->aboutMe))
1115 $about = html2bbcode($entry->aboutMe);
1117 if(isset($entry->gender))
1118 $gender = $entry->gender;
1120 if(isset($entry->generation) AND ($entry->generation > 0))
1121 $generation = ++$entry->generation;
1123 if(isset($entry->tags))
1124 foreach($entry->tags as $tag)
1125 $keywords = implode(", ", $tag);
1127 if ($generation > 0) {
1128 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1129 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation);
1130 logger("Done for profile ".$profile_url, LOGGER_DEBUG);