3 require_once('include/datetime.php');
8 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
9 * and add the entries to the gcontact (Global Contact) table, or update existing entries
10 * if anything (name or photo) has changed.
11 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
13 * Once the global contact is stored add (if necessary) the contact linkage which associates
14 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
15 * pointing to the same global contact id.
22 function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
24 require_once("include/html2bbcode.php");
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 // Don't store the statusnet connector as network
171 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
172 if ($network == NETWORK_STATUSNET)
175 // The global contacts should contain the original picture, not the cached one
176 if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link($a->get_baseurl()."/photo/")))
179 $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
180 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
183 $network = $r[0]["network"];
185 if (($network == "") OR ($network == NETWORK_OSTATUS)) {
186 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
187 dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
190 $network = $r[0]["network"];
191 $profile_url = $r[0]["url"];
195 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
196 dbesc(normalise_link($profile_url))
200 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
201 $network = $x[0]["network"];
203 if ($updated = "0000-00-00 00:00:00")
204 $updated = $x[0]["updated"];
206 $last_contact = $x[0]["last_contact"];
207 $last_failure = $x[0]["last_failure"];
209 $last_contact = "0000-00-00 00:00:00";
210 $last_failure = "0000-00-00 00:00:00";
213 if (($network == "") OR ($name == "") OR ($profile_photo == "")) {
214 require_once("include/Scrape.php");
216 $data = probe_url($profile_url);
217 $network = $data["network"];
218 $name = $data["name"];
219 $profile_url = $data["url"];
220 $profile_photo = $data["photo"];
223 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
224 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
226 dbesc(normalise_link($profile_url))
230 if (($name == "") OR ($profile_photo == ""))
233 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
236 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
238 if (poco_do_update($updated, $last_contact, $last_failure)) {
239 $last_updated = poco_last_updated($profile_url);
241 $updated = $last_updated;
242 $last_contact = datetime_convert();
243 logger("Last updated for profile ".$profile_url.": ".$updated, LOGGER_DEBUG);
246 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'", dbesc($last_contact), dbesc(normalise_link($profile_url)));
248 $last_failure = datetime_convert();
251 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'", dbesc($last_failure), dbesc(normalise_link($profile_url)));
258 if (($location == "") AND ($x[0]['location'] != ""))
259 $location = $x[0]['location'];
261 if (($about == "") AND ($x[0]['about'] != ""))
262 $about = $x[0]['about'];
264 if (($gender == "") AND ($x[0]['gender'] != ""))
265 $gender = $x[0]['gender'];
267 if (($keywords == "") AND ($x[0]['keywords'] != ""))
268 $keywords = $x[0]['keywords'];
270 if (($generation == 0) AND ($x[0]['generation'] > 0))
271 $generation = $x[0]['generation'];
273 if ($last_contact < $x[0]['last_contact'])
274 $last_contact = $x[0]['last_contact'];
276 if($x[0]['name'] != $name || $x[0]['photo'] != $profile_photo || $x[0]['updated'] < $updated) {
277 q("UPDATE `gcontact` SET `name` = '%s', `network` = '%s', `photo` = '%s', `connect` = '%s', `url` = '%s',
278 `updated` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s', `generation` = %d
279 WHERE (`generation` >= %d OR `generation` = 0) AND `nurl` = '%s'",
282 dbesc($profile_photo),
292 dbesc(normalise_link($profile_url))
296 q("INSERT INTO `gcontact` (`name`,`network`, `url`,`nurl`,`photo`,`connect`, `updated`, `last_contact`, `last_failure`, `location`, `about`, `keywords`, `gender`, `generation`)
297 VALUES ('%s', '%s', '%s', '%s', '%s','%s', '%s', '%s', '%s', '%s', '%s', %d)",
301 dbesc(normalise_link($profile_url)),
302 dbesc($profile_photo),
305 dbesc($last_contact),
306 dbesc($last_failure),
313 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
314 dbesc(normalise_link($profile_url))
323 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
330 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
335 dbesc(datetime_convert())
338 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
339 dbesc(datetime_convert()),
347 // For unknown reasons there are sometimes duplicates
348 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d AND
349 NOT EXISTS (SELECT `gcid` FROM `glink` WHERE `gcid` = `gcontact`.`id`)",
350 dbesc(normalise_link($profile_url)),
357 function poco_last_updated($profile) {
358 $data = probe_url($profile);
360 if (($data["poll"] == "") OR ($data["network"] == NETWORK_FEED))
363 $feedret = z_fetch_url($data["poll"]);
365 if (!$feedret["success"])
368 $doc = new DOMDocument();
369 @$doc->loadXML($feedret["body"]);
371 $xpath = new DomXPath($doc);
372 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
374 $entries = $xpath->query('/atom:feed/atom:entry');
378 foreach ($entries AS $entry) {
379 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
380 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
382 if ($last_updated < $published)
383 $last_updated = $published;
385 if ($last_updated < $updated)
386 $last_updated = $updated;
389 // Maybe there aren't any entries. Then check if it is a valid feed
390 if ($last_updated == "")
391 if ($xpath->query('/atom:feed')->length > 0)
392 $last_updated = "0000-00-00 00:00:00";
394 return($last_updated);
397 function poco_do_update($updated, $last_contact, $last_failure) {
398 $now = strtotime(datetime_convert());
400 if ($updated > $last_contact)
401 $contact_time = strtotime($updated);
403 $contact_time = strtotime($last_contact);
405 $failure_time = strtotime($last_failure);
407 // If the last contact was less than 24 hours then don't update
408 if (($now - $contact_time) < (60 * 60 * 24))
411 // If the last failure was less than 24 hours then don't update
412 if (($now - $failure_time) < (60 * 60 * 24))
415 // If the last contact was less than a week ago and the last failure is older than a week then don't update
416 if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
419 // If the last contact time was more than a week ago, then only try once a week
420 if (($now - $contact_time) > (60 * 60 * 24 * 7) AND ($now - $failure_time) < (60 * 60 * 24 * 7))
423 // If the last contact time was more than a month ago, then only try once a month
424 if (($now - $contact_time) > (60 * 60 * 24 * 30) AND ($now - $failure_time) < (60 * 60 * 24 * 30))
430 function poco_contact_from_body($body, $created, $cid, $uid) {
431 preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
432 function ($match) use ($created, $cid, $uid){
433 return(sub_poco_from_share($match, $created, $cid, $uid));
437 function sub_poco_from_share($share, $created, $cid, $uid) {
439 preg_match("/profile='(.*?)'/ism", $share[1], $matches);
440 if ($matches[1] != "")
441 $profile = $matches[1];
443 preg_match('/profile="(.*?)"/ism', $share[1], $matches);
444 if ($matches[1] != "")
445 $profile = $matches[1];
450 logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
451 poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
454 function poco_store($item) {
457 if ($item['private'])
460 // Or is it from a network where we don't store the global contacts?
461 if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
464 // Is it a global copy?
465 $store_gcontact = ($item["uid"] == 0);
467 // Is it a comment on a global copy?
468 if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
469 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
470 $store_gcontact = count($q);
473 if (!$store_gcontact)
476 // "3" means: We don't know this contact directly (Maybe a reshared item)
479 $profile_url = $item["author-link"];
481 // Is it a user from our server?
482 $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
483 dbesc(normalise_link($item["author-link"])));
485 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
487 $network = NETWORK_DFRN;
488 } else { // Is it a contact from a user on our server?
489 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
490 AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
491 dbesc(normalise_link($item["author-link"])),
492 dbesc(normalise_link($item["author-link"])),
493 dbesc($item["author-link"]),
494 dbesc(NETWORK_STATUSNET));
497 $network = $q[0]["network"];
498 $profile_url = $q[0]["url"];
499 logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
503 if ($generation == 3)
504 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
506 poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
508 // Maybe its a body with a shared item? Then extract a global contact from it.
509 poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
512 function count_common_friends($uid,$cid) {
514 $r = q("SELECT count(*) as `total`
515 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
516 where `glink`.`cid` = %d and `glink`.`uid` = %d
517 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
524 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
526 return $r[0]['total'];
532 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
535 $sql_extra = " order by rand() ";
537 $sql_extra = " order by `gcontact`.`name` asc ";
539 $r = q("SELECT `gcontact`.*
540 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
541 where `glink`.`cid` = %d and `glink`.`uid` = %d
542 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d )
543 $sql_extra limit %d, %d",
557 function count_common_friends_zcid($uid,$zcid) {
559 $r = q("SELECT count(*) as `total`
560 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
561 where `glink`.`zcid` = %d
562 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
568 return $r[0]['total'];
573 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
576 $sql_extra = " order by rand() ";
578 $sql_extra = " order by `gcontact`.`name` asc ";
580 $r = q("SELECT `gcontact`.*
581 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
582 where `glink`.`zcid` = %d
583 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
584 $sql_extra limit %d, %d",
596 function count_all_friends($uid,$cid) {
598 $r = q("SELECT count(*) as `total`
599 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
600 where `glink`.`cid` = %d and `glink`.`uid` = %d ",
606 return $r[0]['total'];
612 function all_friends($uid,$cid,$start = 0, $limit = 80) {
614 $r = q("SELECT `gcontact`.*
615 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
616 where `glink`.`cid` = %d and `glink`.`uid` = %d
617 order by `gcontact`.`name` asc LIMIT %d, %d ",
629 function suggestion_query($uid, $start = 0, $limit = 80) {
634 $network = array(NETWORK_DFRN);
636 if (get_config('system','diaspora_enabled'))
637 $network[] = NETWORK_DIASPORA;
639 if (!get_config('system','ostatus_disabled'))
640 $network[] = NETWORK_OSTATUS;
642 $sql_network = implode("', '", $network);
643 //$sql_network = "'".$sql_network."', ''";
644 $sql_network = "'".$sql_network."'";
646 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
647 INNER JOIN glink on glink.gcid = gcontact.id
648 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
649 and not gcontact.name in ( select name from contact where uid = %d )
650 and not gcontact.id in ( select gcid from gcign where uid = %d )
651 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
652 AND `gcontact`.`network` IN (%s)
653 group by glink.gcid order by gcontact.updated desc,total desc limit %d, %d ",
663 if(count($r) && count($r) >= ($limit -1))
666 $r2 = q("SELECT gcontact.* from gcontact
667 INNER JOIN glink on glink.gcid = gcontact.id
668 where glink.uid = 0 and glink.cid = 0 and glink.zcid = 0 and not gcontact.nurl in ( select nurl from contact where uid = %d )
669 and not gcontact.name in ( select name from contact where uid = %d )
670 and not gcontact.id in ( select gcid from gcign where uid = %d )
671 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
672 AND `gcontact`.`network` IN (%s)
673 order by rand() limit %d, %d ",
683 foreach ($r2 AS $suggestion)
684 $list[$suggestion["nurl"]] = $suggestion;
686 foreach ($r AS $suggestion)
687 $list[$suggestion["nurl"]] = $suggestion;
692 function update_suggestions() {
698 poco_load(0,0,0,$a->get_baseurl() . '/poco');
700 $done[] = $a->get_baseurl() . '/poco';
702 if(strlen(get_config('system','directory_submit_url'))) {
703 $x = fetch_url('http://dir.friendica.com/pubsites');
705 $j = json_decode($x);
707 foreach($j->entries as $entry) {
708 $url = $entry->url . '/poco';
709 if(! in_array($url,$done))
710 poco_load(0,0,0,$entry->url . '/poco');
716 $r = q("select distinct(poco) as poco from contact where network = '%s'",
722 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
723 if(! in_array($base,$done))
724 poco_load(0,0,0,$base);