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 // Only fetch last update manually if it wasn't provided and enabled in the system
242 if (get_config('system','poco_completion') AND ($orig_updated == "0000-00-00 00:00:00") AND poco_do_update($updated, $last_contact, $last_failure)) {
243 $last_updated = poco_last_updated($profile_url);
245 $updated = $last_updated;
246 $last_contact = datetime_convert();
247 logger("Last updated for profile ".$profile_url.": ".$updated, LOGGER_DEBUG);
250 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'", dbesc($last_contact), dbesc(normalise_link($profile_url)));
252 $last_failure = datetime_convert();
255 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'", dbesc($last_failure), dbesc(normalise_link($profile_url)));
259 poco_check_server($server_url, $network);
261 // Test - remove before flight
262 //if ($last_contact > $last_failure)
263 // q("UPDATE `gserver` SET `last_contact` = '%s' WHERE `nurl` = '%s'", dbesc($last_contact), dbesc(normalise_link($server_url)));
265 // q("UPDATE `gserver` SET `last_failure` = '%s' WHERE `nurl` = '%s'", dbesc($last_failure), dbesc(normalise_link($server_url)));
270 if (($location == "") AND ($x[0]['location'] != ""))
271 $location = $x[0]['location'];
273 if (($about == "") AND ($x[0]['about'] != ""))
274 $about = $x[0]['about'];
276 if (($gender == "") AND ($x[0]['gender'] != ""))
277 $gender = $x[0]['gender'];
279 if (($keywords == "") AND ($x[0]['keywords'] != ""))
280 $keywords = $x[0]['keywords'];
282 if (($generation == 0) AND ($x[0]['generation'] > 0))
283 $generation = $x[0]['generation'];
285 if($x[0]['name'] != $name || $x[0]['photo'] != $profile_photo || $x[0]['updated'] < $updated) {
286 q("UPDATE `gcontact` SET `name` = '%s', `network` = '%s', `photo` = '%s', `connect` = '%s', `url` = '%s', `server_url` = '%s',
287 `updated` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s', `generation` = %d
288 WHERE (`generation` >= %d OR `generation` = 0) AND `nurl` = '%s'",
291 dbesc($profile_photo),
302 dbesc(normalise_link($profile_url))
306 q("INSERT INTO `gcontact` (`name`,`network`, `url`,`nurl`,`photo`,`connect`, `server_url`, `updated`, `last_contact`, `last_failure`, `location`, `about`, `keywords`, `gender`, `generation`)
307 VALUES ('%s', '%s', '%s', '%s', '%s','%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
311 dbesc(normalise_link($profile_url)),
312 dbesc($profile_photo),
316 dbesc($last_contact),
317 dbesc($last_failure),
324 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
325 dbesc(normalise_link($profile_url))
334 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
341 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
346 dbesc(datetime_convert())
349 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
350 dbesc(datetime_convert()),
358 // For unknown reasons there are sometimes duplicates
359 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d AND
360 NOT EXISTS (SELECT `gcid` FROM `glink` WHERE `gcid` = `gcontact`.`id`)",
361 dbesc(normalise_link($profile_url)),
368 function poco_last_updated($profile) {
369 $data = probe_url($profile);
371 if (($data["poll"] == "") OR ($data["network"] == NETWORK_FEED))
374 // To-Do: Use noscrape
376 $feedret = z_fetch_url($data["poll"]);
378 if (!$feedret["success"])
381 $doc = new DOMDocument();
382 @$doc->loadXML($feedret["body"]);
384 $xpath = new DomXPath($doc);
385 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
387 $entries = $xpath->query('/atom:feed/atom:entry');
391 foreach ($entries AS $entry) {
392 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
393 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
395 if ($last_updated < $published)
396 $last_updated = $published;
398 if ($last_updated < $updated)
399 $last_updated = $updated;
402 // Maybe there aren't any entries. Then check if it is a valid feed
403 if ($last_updated == "")
404 if ($xpath->query('/atom:feed')->length > 0)
405 $last_updated = "0000-00-00 00:00:00";
407 return($last_updated);
410 function poco_do_update($updated, $last_contact, $last_failure) {
411 $now = strtotime(datetime_convert());
413 if ($updated > $last_contact)
414 $contact_time = strtotime($updated);
416 $contact_time = strtotime($last_contact);
418 $failure_time = strtotime($last_failure);
420 // If the last contact was less than 24 hours then don't update
421 if (($now - $contact_time) < (60 * 60 * 24))
424 // If the last failure was less than 24 hours then don't update
425 if (($now - $failure_time) < (60 * 60 * 24))
428 // If the last contact was less than a week ago and the last failure is older than a week then don't update
429 if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
432 // If the last contact time was more than a week ago, then only try once a week
433 if (($now - $contact_time) > (60 * 60 * 24 * 7) AND ($now - $failure_time) < (60 * 60 * 24 * 7))
436 // If the last contact time was more than a month ago, then only try once a month
437 if (($now - $contact_time) > (60 * 60 * 24 * 30) AND ($now - $failure_time) < (60 * 60 * 24 * 30))
443 function poco_to_boolean($val) {
444 if (($val == "true") OR ($val == 1))
446 if (($val == "false") OR ($val == 0))
452 function poco_check_server($server_url, $network = "") {
454 if ($server_url == "")
457 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
459 $poco = $servers[0]["poco"];
460 $noscrape = $servers[0]["noscrape"];
463 $network = $servers[0]["network"];
465 $last_contact = $servers[0]["last_contact"];
466 $last_failure = $servers[0]["last_failure"];
467 $version = $servers[0]["version"];
468 $platform = $servers[0]["platform"];
469 $site_name = $servers[0]["site_name"];
470 $info = $servers[0]["info"];
471 $register_policy = $servers[0]["register_policy"];
473 // Only check the server once a week
474 if (strtotime(datetime_convert()) < (strtotime($last_contact) + (60 * 60 * 24 * 7)))
477 if (strtotime(datetime_convert()) < (strtotime($last_failure) + (60 * 60 * 24 * 7)))
486 $register_policy = -1;
488 $last_contact = "0000-00-00 00:00:00";
489 $last_failure = "0000-00-00 00:00:00";
493 $orig_last_failure = $last_failure;
495 // Check if the page is accessible via SSL.
496 $server_url = str_replace("http://", "https://", $server_url);
497 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
499 // Maybe the page is unencrypted only?
500 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
501 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
502 $server_url = str_replace("https://", "http://", $server_url);
503 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
505 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
508 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
509 $last_failure = datetime_convert();
511 } elseif ($network == NETWORK_DIASPORA)
512 $last_contact = datetime_convert();
515 // Test for Statusnet
516 // Will also return data for Friendica and GNU Social - but it will be overwritten later
517 // The "not implemented" is a special treatment for really, really old Friendica versions
518 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
519 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
520 $platform = "StatusNet";
521 $version = trim($serverret["body"], '"');
522 $network = NETWORK_OSTATUS;
525 // Test for GNU Social
526 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
527 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
528 $platform = "GNU Social";
529 $version = trim($serverret["body"], '"');
530 $network = NETWORK_OSTATUS;
533 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
534 if ($serverret["success"]) {
535 $data = json_decode($serverret["body"]);
537 if (isset($data->site->server)) {
538 $last_contact = datetime_convert();
540 if (isset($data->site->redmatrix)) {
541 if (isset($data->site->redmatrix->PLATFORM_NAME))
542 $platform = $data->site->redmatrix->PLATFORM_NAME;
543 elseif (isset($data->site->redmatrix->RED_PLATFORM))
544 $platform = $data->site->redmatrix->RED_PLATFORM;
546 $version = $data->site->redmatrix->RED_VERSION;
547 $network = NETWORK_DIASPORA;
549 if (isset($data->site->friendica)) {
550 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
551 $version = $data->site->friendica->FRIENDICA_VERSION;
552 $network = NETWORK_DFRN;
555 $site_name = $data->site->name;
557 $data->site->closed = poco_to_boolean($data->site->closed);
558 $data->site->private = poco_to_boolean($data->site->private);
559 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
561 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
562 $register_policy = REGISTER_APPROVE;
563 elseif (!$data->site->closed AND !$data->site->private)
564 $register_policy = REGISTER_OPEN;
566 $register_policy = REGISTER_CLOSED;
571 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
573 $serverret = z_fetch_url($server_url."/statistics.json");
574 if ($serverret["success"]) {
575 $data = json_decode($serverret["body"]);
577 $version = $data->version;
579 $site_name = $data->name;
581 if (isset($data->network) AND ($platform == ""))
582 $platform = $data->network;
584 if ($data->registrations_open)
585 $register_policy = REGISTER_OPEN;
587 $register_policy = REGISTER_CLOSED;
589 if (isset($data->version))
590 $last_contact = datetime_convert();
594 // Check for noscrape
595 // Friendica servers could be detected as OStatus servers
596 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
597 $serverret = z_fetch_url($server_url."/friendica/json");
599 if ($serverret["success"]) {
600 $data = json_decode($serverret["body"]);
602 if (isset($data->version)) {
603 $last_contact = datetime_convert();
604 $network = NETWORK_DFRN;
606 $noscrape = $data->no_scrape_url;
607 $version = $data->version;
608 $site_name = $data->site_name;
610 $register_policy_str = $data->register_policy;
611 $platform = $data->platform;
613 switch ($register_policy_str) {
614 case "REGISTER_CLOSED":
615 $register_policy = REGISTER_CLOSED;
617 case "REGISTER_APPROVE":
618 $register_policy = REGISTER_APPROVE;
620 case "REGISTER_OPEN":
621 $register_policy = REGISTER_OPEN;
630 $serverret = z_fetch_url($server_url."/poco");
631 if ($serverret["success"]) {
632 $data = json_decode($serverret["body"]);
633 if (isset($data->totalResults)) {
634 $poco = $server_url."/poco";
635 $last_contact = datetime_convert();
641 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
642 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
647 intval($register_policy),
652 dbesc($last_contact),
653 dbesc($last_failure),
654 dbesc(normalise_link($server_url))
657 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `last_contact`)
658 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s')",
660 dbesc(normalise_link($server_url)),
664 intval($register_policy),
669 dbesc(datetime_convert())
673 function poco_contact_from_body($body, $created, $cid, $uid) {
674 preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
675 function ($match) use ($created, $cid, $uid){
676 return(sub_poco_from_share($match, $created, $cid, $uid));
680 function sub_poco_from_share($share, $created, $cid, $uid) {
682 preg_match("/profile='(.*?)'/ism", $share[1], $matches);
683 if ($matches[1] != "")
684 $profile = $matches[1];
686 preg_match('/profile="(.*?)"/ism', $share[1], $matches);
687 if ($matches[1] != "")
688 $profile = $matches[1];
693 logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
694 poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
697 function poco_store($item) {
700 if ($item['private'])
703 // Or is it from a network where we don't store the global contacts?
704 if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
707 // Is it a global copy?
708 $store_gcontact = ($item["uid"] == 0);
710 // Is it a comment on a global copy?
711 if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
712 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
713 $store_gcontact = count($q);
716 if (!$store_gcontact)
719 // "3" means: We don't know this contact directly (Maybe a reshared item)
722 $profile_url = $item["author-link"];
724 // Is it a user from our server?
725 $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
726 dbesc(normalise_link($item["author-link"])));
728 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
730 $network = NETWORK_DFRN;
731 } else { // Is it a contact from a user on our server?
732 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
733 AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
734 dbesc(normalise_link($item["author-link"])),
735 dbesc(normalise_link($item["author-link"])),
736 dbesc($item["author-link"]),
737 dbesc(NETWORK_STATUSNET));
740 $network = $q[0]["network"];
741 $profile_url = $q[0]["url"];
742 logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
746 if ($generation == 3)
747 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
749 poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
751 // Maybe its a body with a shared item? Then extract a global contact from it.
752 poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
755 function count_common_friends($uid,$cid) {
757 $r = q("SELECT count(*) as `total`
758 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
759 where `glink`.`cid` = %d and `glink`.`uid` = %d
760 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
767 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
769 return $r[0]['total'];
775 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
778 $sql_extra = " order by rand() ";
780 $sql_extra = " order by `gcontact`.`name` asc ";
782 $r = q("SELECT `gcontact`.*
783 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
784 where `glink`.`cid` = %d and `glink`.`uid` = %d
785 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d )
786 $sql_extra limit %d, %d",
800 function count_common_friends_zcid($uid,$zcid) {
802 $r = q("SELECT count(*) as `total`
803 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
804 where `glink`.`zcid` = %d
805 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
811 return $r[0]['total'];
816 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
819 $sql_extra = " order by rand() ";
821 $sql_extra = " order by `gcontact`.`name` asc ";
823 $r = q("SELECT `gcontact`.*
824 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
825 where `glink`.`zcid` = %d
826 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
827 $sql_extra limit %d, %d",
839 function count_all_friends($uid,$cid) {
841 $r = q("SELECT count(*) as `total`
842 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
843 where `glink`.`cid` = %d and `glink`.`uid` = %d ",
849 return $r[0]['total'];
855 function all_friends($uid,$cid,$start = 0, $limit = 80) {
857 $r = q("SELECT `gcontact`.*
858 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
859 where `glink`.`cid` = %d and `glink`.`uid` = %d
860 order by `gcontact`.`name` asc LIMIT %d, %d ",
872 function suggestion_query($uid, $start = 0, $limit = 80) {
877 $network = array(NETWORK_DFRN);
879 if (get_config('system','diaspora_enabled'))
880 $network[] = NETWORK_DIASPORA;
882 if (!get_config('system','ostatus_disabled'))
883 $network[] = NETWORK_OSTATUS;
885 $sql_network = implode("', '", $network);
886 //$sql_network = "'".$sql_network."', ''";
887 $sql_network = "'".$sql_network."'";
889 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
890 INNER JOIN glink on glink.gcid = gcontact.id
891 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
892 and not gcontact.name in ( select name from contact where uid = %d )
893 and not gcontact.id in ( select gcid from gcign where uid = %d )
894 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
895 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
896 AND `gcontact`.`network` IN (%s)
897 group by glink.gcid order by gcontact.updated desc,total desc limit %d, %d ",
907 if(count($r) && count($r) >= ($limit -1))
910 $r2 = q("SELECT gcontact.* from gcontact
911 INNER JOIN glink on glink.gcid = gcontact.id
912 where glink.uid = 0 and glink.cid = 0 and glink.zcid = 0 and not gcontact.nurl in ( select nurl from contact where uid = %d )
913 and not gcontact.name in ( select name from contact where uid = %d )
914 and not gcontact.id in ( select gcid from gcign where uid = %d )
915 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
916 AND `gcontact`.`network` IN (%s)
917 order by rand() limit %d, %d ",
927 foreach ($r2 AS $suggestion)
928 $list[$suggestion["nurl"]] = $suggestion;
930 foreach ($r AS $suggestion)
931 $list[$suggestion["nurl"]] = $suggestion;
936 function update_suggestions() {
942 // To-Do: Check if it is really neccessary to poll the own server
943 poco_load(0,0,0,$a->get_baseurl() . '/poco');
945 $done[] = $a->get_baseurl() . '/poco';
947 if(strlen(get_config('system','directory_submit_url'))) {
948 $x = fetch_url('http://dir.friendica.com/pubsites');
950 $j = json_decode($x);
952 foreach($j->entries as $entry) {
954 poco_check_server($entry->url);
956 $url = $entry->url . '/poco';
957 if(! in_array($url,$done))
958 poco_load(0,0,0,$entry->url . '/poco');
964 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
965 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
966 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
971 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
972 if(! in_array($base,$done))
973 poco_load(0,0,0,$base);
978 function poco_discover($complete = false) {
980 $last_update = date("c", time() - (60 * 60 * 24));
982 $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));
984 foreach ($r AS $server) {
985 // Fetch all users from the other server
986 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
988 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
990 $retdata = z_fetch_url($url);
991 if ($retdata["success"]) {
992 $data = json_decode($retdata["body"]);
993 poco_discover_server($data, 2);
995 if (get_config('system','poco_discovery') > 1) {
997 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
998 $url = $server["poco"]."/@global?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1000 $retdata = z_fetch_url($url);
1001 if ($retdata["success"]) {
1002 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1003 poco_discover_server(json_decode($retdata["body"]));
1004 } elseif (get_config('system','poco_discovery') > 2) {
1005 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1006 poco_discover_server_users($data);
1010 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1017 function poco_discover_server_users($data) {
1018 foreach ($data->entry AS $entry) {
1020 if (isset($entry->urls)) {
1021 foreach($entry->urls as $url)
1022 if($url->type == 'profile') {
1023 $profile_url = $url->value;
1024 $urlparts = parse_url($profile_url);
1025 $username = end(explode("/", $urlparts["path"]));
1028 if ($username != "") {
1029 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1031 // Fetch all contacts from a given user from the other server
1032 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1034 $retdata = z_fetch_url($url);
1035 if ($retdata["success"])
1036 poco_discover_server(json_decode($retdata["body"]), 3);
1041 function poco_discover_server($data, $default_generation = 0) {
1043 if (!isset($data->entry) OR !count($data->entry))
1046 foreach ($data->entry AS $entry) {
1048 $profile_photo = '';
1052 $updated = '0000-00-00 00:00:00';
1057 $generation = $default_generation;
1059 $name = $entry->displayName;
1061 if(isset($entry->urls)) {
1062 foreach($entry->urls as $url) {
1063 if($url->type == 'profile') {
1064 $profile_url = $url->value;
1067 if($url->type == 'webfinger') {
1068 $connect_url = str_replace('acct:' , '', $url->value);
1073 if(isset($entry->photos)) {
1074 foreach($entry->photos as $photo) {
1075 if($photo->type == 'profile') {
1076 $profile_photo = $photo->value;
1082 if(isset($entry->updated))
1083 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1085 if(isset($entry->network))
1086 $network = $entry->network;
1088 if(isset($entry->currentLocation))
1089 $location = $entry->currentLocation;
1091 if(isset($entry->aboutMe))
1092 $about = html2bbcode($entry->aboutMe);
1094 if(isset($entry->gender))
1095 $gender = $entry->gender;
1097 if(isset($entry->generation) AND ($entry->generation > 0))
1098 $generation = ++$entry->generation;
1100 if(isset($entry->tags))
1101 foreach($entry->tags as $tag)
1102 $keywords = implode(", ", $tag);
1104 if ($generation > 0) {
1105 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1106 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation);
1107 logger("Done for profile ".$profile_url, LOGGER_DEBUG);