3 require_once('include/datetime.php');
4 require_once("include/Scrape.php");
5 require_once("include/html2bbcode.php");
9 - Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
10 - Fetch profile data from profile page for Redmatrix users
11 - Detect if it is a forum
17 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
18 * and add the entries to the gcontact (Global Contact) table, or update existing entries
19 * if anything (name or photo) has changed.
20 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
22 * Once the global contact is stored add (if necessary) the contact linkage which associates
23 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
24 * pointing to the same global contact id.
31 function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
36 if((! $url) || (! $uid)) {
37 $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
52 $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') ;
54 logger('poco_load: ' . $url, LOGGER_DEBUG);
58 logger('poco_load: returns ' . $s, LOGGER_DATA);
60 logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
62 if(($a->get_curl_code() > 299) || (! $s))
67 logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
69 if(! isset($j->entry))
73 foreach($j->entry as $entry) {
81 $updated = '0000-00-00 00:00:00';
88 $name = $entry->displayName;
90 if(isset($entry->urls)) {
91 foreach($entry->urls as $url) {
92 if($url->type == 'profile') {
93 $profile_url = $url->value;
96 if($url->type == 'webfinger') {
97 $connect_url = str_replace('acct:' , '', $url->value);
102 if(isset($entry->photos)) {
103 foreach($entry->photos as $photo) {
104 if($photo->type == 'profile') {
105 $profile_photo = $photo->value;
111 if(isset($entry->updated))
112 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
114 if(isset($entry->network))
115 $network = $entry->network;
117 if(isset($entry->currentLocation))
118 $location = $entry->currentLocation;
120 if(isset($entry->aboutMe))
121 $about = html2bbcode($entry->aboutMe);
123 if(isset($entry->gender))
124 $gender = $entry->gender;
126 if(isset($entry->generation) AND ($entry->generation > 0))
127 $generation = ++$entry->generation;
129 if(isset($entry->tags))
130 foreach($entry->tags as $tag)
131 $keywords = implode(", ", $tag);
133 // If you query a Friendica server for its profiles, the network has to be Friendica
134 // To-Do: It could also be a Redmatrix server
136 // $network = NETWORK_DFRN;
138 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
140 // Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
141 if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
142 q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
143 WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
148 dbesc(normalise_link($profile_url)),
149 dbesc(NETWORK_DFRN));
151 logger("poco_load: loaded $total entries",LOGGER_DEBUG);
153 q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
161 function poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid = 0, $uid = 0, $zcid = 0) {
167 // 1: Profiles on this server
168 // 2: Contacts of profiles on this server
169 // 3: Contacts of contacts of profiles on this server
174 $alternate = poco_alternate_ostatus_url($profile_url);
176 if ($profile_url == "")
179 $urlparts = parse_url($profile_url);
180 if (!isset($urlparts["scheme"]))
183 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
184 "identi.ca", "alpha.app.net")))
187 $orig_updated = $updated;
189 // Don't store the statusnet connector as network
190 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
191 if ($network == NETWORK_STATUSNET)
194 // The global contacts should contain the original picture, not the cached one
195 if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link($a->get_baseurl()."/photo/")))
198 $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
199 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
202 $network = $r[0]["network"];
204 if (($network == "") OR ($network == NETWORK_OSTATUS)) {
205 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
206 dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
209 $network = $r[0]["network"];
210 //$profile_url = $r[0]["url"];
214 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
215 dbesc(normalise_link($profile_url))
219 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
220 $network = $x[0]["network"];
222 if ($updated == "0000-00-00 00:00:00")
223 $updated = $x[0]["updated"];
225 $created = $x[0]["created"];
226 $server_url = $x[0]["server_url"];
227 $nick = $x[0]["nick"];
228 $addr = $x[0]["addr"];
230 $created = "0000-00-00 00:00:00";
233 $urlparts = parse_url($profile_url);
234 $nick = end(explode("/", $urlparts["path"]));
238 if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
239 AND poco_reachable($profile_url, $server_url, $network, false)) {
240 $data = probe_url($profile_url);
242 $orig_profile = $profile_url;
244 $network = $data["network"];
245 $name = $data["name"];
246 $nick = $data["nick"];
247 $addr = $data["addr"];
248 $profile_url = $data["url"];
249 $profile_photo = $data["photo"];
250 $server_url = $data["baseurl"];
252 if ($alternate AND ($network == NETWORK_OSTATUS)) {
253 // Delete the old entry - if it exists
254 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
256 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
257 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
260 // possibly create a new entry
261 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
265 if ($alternate AND ($network == NETWORK_OSTATUS))
268 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
269 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
271 dbesc(normalise_link($profile_url))
275 if (($name == "") OR ($profile_photo == ""))
278 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
281 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
283 poco_check_server($server_url, $network);
288 if (($location == "") AND ($x[0]['location'] != ""))
289 $location = $x[0]['location'];
291 if (($about == "") AND ($x[0]['about'] != ""))
292 $about = $x[0]['about'];
294 if (($gender == "") AND ($x[0]['gender'] != ""))
295 $gender = $x[0]['gender'];
297 if (($keywords == "") AND ($x[0]['keywords'] != ""))
298 $keywords = $x[0]['keywords'];
300 if (($addr == "") AND ($x[0]['addr'] != ""))
301 $addr = $x[0]['addr'];
303 if (($generation == 0) AND ($x[0]['generation'] > 0))
304 $generation = $x[0]['generation'];
306 if($x[0]['name'] != $name || $x[0]['photo'] != $profile_photo || $x[0]['updated'] < $updated) {
307 q("UPDATE `gcontact` SET `name` = '%s', `addr` = '%s', `network` = '%s', `photo` = '%s', `connect` = '%s', `url` = '%s', `server_url` = '%s',
308 `updated` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s', `generation` = %d
309 WHERE (`generation` >= %d OR `generation` = 0) AND `nurl` = '%s'",
313 dbesc($profile_photo),
324 dbesc(normalise_link($profile_url))
328 q("INSERT INTO `gcontact` (`name`, `nick`, `addr`, `network`, `url`, `nurl`, `photo`, `connect`, `server_url`, `created`, `updated`, `location`, `about`, `keywords`, `gender`, `generation`)
329 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
335 dbesc(normalise_link($profile_url)),
336 dbesc($profile_photo),
339 dbesc(datetime_convert()),
347 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
348 dbesc(normalise_link($profile_url))
357 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
364 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
369 dbesc(datetime_convert())
372 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
373 dbesc(datetime_convert()),
381 // For unknown reasons there are sometimes duplicates
382 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d AND
383 NOT EXISTS (SELECT `gcid` FROM `glink` WHERE `gcid` = `gcontact`.`id`)",
384 dbesc(normalise_link($profile_url)),
391 function poco_reachable($profile, $server = "", $network = "", $force = false) {
394 $server = poco_detect_server($profile);
399 return poco_check_server($server, $network, $force);
402 function poco_detect_server($profile) {
404 // Try to detect the server path based upon some known standard paths
407 if ($server_url == "") {
408 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
409 if ($friendica != $profile) {
410 $server_url = $friendica;
411 $network = NETWORK_DFRN;
415 if ($server_url == "") {
416 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
417 if ($diaspora != $profile) {
418 $server_url = $diaspora;
419 $network = NETWORK_DIASPORA;
423 if ($server_url == "") {
424 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
425 if ($red != $profile) {
427 $network = NETWORK_DIASPORA;
434 function poco_alternate_ostatus_url($url) {
435 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
438 function poco_last_updated($profile, $force = false) {
440 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
441 dbesc(normalise_link($profile)));
443 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
444 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
445 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
447 if ($gcontacts[0]["server_url"] != "")
448 $server_url = $gcontacts[0]["server_url"];
450 $server_url = poco_detect_server($profile);
452 if ($server_url != "") {
453 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
456 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
457 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
462 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
463 dbesc($server_url), dbesc(normalise_link($profile)));
466 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
467 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
468 dbesc(normalise_link($server_url)));
471 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
472 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
477 // noscrape is really fast so we don't cache the call.
478 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
480 // Use noscrape if possible
481 $server = q("SELECT `noscrape` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
484 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
486 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
488 $noscrape = json_decode($noscraperet["body"], true);
490 if (($noscrape["fn"] != "") AND ($noscrape["fn"] != $gcontacts[0]["name"]))
491 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
492 dbesc($noscrape["fn"]), dbesc(normalise_link($profile)));
494 if (($noscrape["photo"] != "") AND ($noscrape["photo"] != $gcontacts[0]["photo"]))
495 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
496 dbesc($noscrape["photo"]), dbesc(normalise_link($profile)));
498 if (($noscrape["updated"] != "") AND ($noscrape["updated"] != $gcontacts[0]["updated"]))
499 q("UPDATE `gcontact` SET `updated` = '%s' WHERE `nurl` = '%s'",
500 dbesc($noscrape["updated"]), dbesc(normalise_link($profile)));
502 if (($noscrape["gender"] != "") AND ($noscrape["gender"] != $gcontacts[0]["gender"]))
503 q("UPDATE `gcontact` SET `gender` = '%s' WHERE `nurl` = '%s'",
504 dbesc($noscrape["gender"]), dbesc(normalise_link($profile)));
506 if (($noscrape["pdesc"] != "") AND ($noscrape["pdesc"] != $gcontacts[0]["about"]))
507 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
508 dbesc($noscrape["pdesc"]), dbesc(normalise_link($profile)));
510 if (($noscrape["about"] != "") AND ($noscrape["about"] != $gcontacts[0]["about"]))
511 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
512 dbesc($noscrape["about"]), dbesc(normalise_link($profile)));
514 if (isset($noscrape["comm"]) AND ($noscrape["comm"] != $gcontacts[0]["community"]))
515 q("UPDATE `gcontact` SET `community` = %d WHERE `nurl` = '%s'",
516 intval($noscrape["comm"]), dbesc(normalise_link($profile)));
518 if (isset($noscrape["tags"]))
519 $keywords = implode(" ", $noscrape["tags"]);
523 if (($keywords != "") AND ($keywords != $gcontacts[0]["keywords"]))
524 q("UPDATE `gcontact` SET `keywords` = '%s' WHERE `nurl` = '%s'",
525 dbesc($keywords), dbesc(normalise_link($profile)));
527 $location = $noscrape["locality"];
529 if ($noscrape["region"] != "") {
533 $location .= $noscrape["region"];
536 if ($noscrape["country-name"] != "") {
540 $location .= $noscrape["country-name"];
543 if (($location != "") AND ($location != $gcontacts[0]["location"]))
544 q("UPDATE `gcontact` SET `location` = '%s' WHERE `nurl` = '%s'",
545 dbesc($location), dbesc(normalise_link($profile)));
547 // If we got data from noscrape then mark the contact as reachable
548 if (is_array($noscrape) AND count($noscrape))
549 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
550 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
552 return $noscrape["updated"];
557 // If we only can poll the feed, then we only do this once a while
558 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"]))
559 return $gcontacts[0]["updated"];
561 $data = probe_url($profile);
563 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
564 // Then check the other link and delete this one
565 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
566 (normalise_link($profile) == normalise_link($data["alias"])) AND
567 (normalise_link($profile) != normalise_link($data["url"]))) {
569 // Delete the old entry
570 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
571 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
573 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
574 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
576 poco_last_updated($data["url"], $force);
581 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
582 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
583 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
587 if (($data["name"] != "") AND ($data["name"] != $gcontacts[0]["name"]))
588 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
589 dbesc($data["name"]), dbesc(normalise_link($profile)));
591 if (($data["nick"] != "") AND ($data["nick"] != $gcontacts[0]["nick"]))
592 q("UPDATE `gcontact` SET `nick` = '%s' WHERE `nurl` = '%s'",
593 dbesc($data["nick"]), dbesc(normalise_link($profile)));
595 if (($data["addr"] != "") AND ($data["addr"] != $gcontacts[0]["connect"]))
596 q("UPDATE `gcontact` SET `connect` = '%s' WHERE `nurl` = '%s'",
597 dbesc($data["addr"]), dbesc(normalise_link($profile)));
599 if (($data["photo"] != "") AND ($data["photo"] != $gcontacts[0]["photo"]))
600 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
601 dbesc($data["photo"]), dbesc(normalise_link($profile)));
603 if (($data["baseurl"] != "") AND ($data["baseurl"] != $gcontacts[0]["server_url"]))
604 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
605 dbesc($data["baseurl"]), dbesc(normalise_link($profile)));
607 $feedret = z_fetch_url($data["poll"]);
609 if (!$feedret["success"]) {
610 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
611 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
615 $doc = new DOMDocument();
616 @$doc->loadXML($feedret["body"]);
618 $xpath = new DomXPath($doc);
619 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
621 $entries = $xpath->query('/atom:feed/atom:entry');
625 foreach ($entries AS $entry) {
626 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
627 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
629 if ($last_updated < $published)
630 $last_updated = $published;
632 if ($last_updated < $updated)
633 $last_updated = $updated;
636 // Maybe there aren't any entries. Then check if it is a valid feed
637 if ($last_updated == "")
638 if ($xpath->query('/atom:feed')->length > 0)
639 $last_updated = "0000-00-00 00:00:00";
641 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
642 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
644 if (($gcontacts[0]["generation"] == 0))
645 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
646 dbesc(normalise_link($profile)));
648 return($last_updated);
651 function poco_do_update($created, $updated, $last_failure, $last_contact) {
652 $now = strtotime(datetime_convert());
654 if ($updated > $last_contact)
655 $contact_time = strtotime($updated);
657 $contact_time = strtotime($last_contact);
659 $failure_time = strtotime($last_failure);
660 $created_time = strtotime($created);
662 // If there is no "created" time then use the current time
663 if ($created_time <= 0)
664 $created_time = $now;
666 // If the last contact was less than 24 hours then don't update
667 if (($now - $contact_time) < (60 * 60 * 24))
670 // If the last failure was less than 24 hours then don't update
671 if (($now - $failure_time) < (60 * 60 * 24))
674 // If the last contact was less than a week ago and the last failure is older than a week then don't update
675 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
678 // 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
679 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
682 // 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
683 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
689 function poco_to_boolean($val) {
690 if (($val == "true") OR ($val == 1))
692 if (($val == "false") OR ($val == 0))
698 function poco_check_server($server_url, $network = "", $force = false) {
700 if ($server_url == "")
703 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
706 if ($servers[0]["created"] == "0000-00-00 00:00:00")
707 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
708 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
710 $poco = $servers[0]["poco"];
711 $noscrape = $servers[0]["noscrape"];
714 $network = $servers[0]["network"];
716 $last_contact = $servers[0]["last_contact"];
717 $last_failure = $servers[0]["last_failure"];
718 $version = $servers[0]["version"];
719 $platform = $servers[0]["platform"];
720 $site_name = $servers[0]["site_name"];
721 $info = $servers[0]["info"];
722 $register_policy = $servers[0]["register_policy"];
724 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
725 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
726 return ($last_contact >= $last_failure);
735 $register_policy = -1;
737 $last_contact = "0000-00-00 00:00:00";
738 $last_failure = "0000-00-00 00:00:00";
740 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
743 $orig_last_failure = $last_failure;
745 // Check if the page is accessible via SSL.
746 $server_url = str_replace("http://", "https://", $server_url);
747 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
749 // Maybe the page is unencrypted only?
750 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
751 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
752 $server_url = str_replace("https://", "http://", $server_url);
753 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
755 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
758 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
759 // Workaround for bad configured servers (known nginx problem)
760 if ($serverret["debug"]["http_code"] != "403") {
761 $last_failure = datetime_convert();
764 } elseif ($network == NETWORK_DIASPORA)
765 $last_contact = datetime_convert();
769 $serverret = z_fetch_url($server_url);
771 $lines = explode("\n",$serverret["header"]);
773 foreach($lines as $line) {
775 if(stristr($line,'X-Diaspora-Version:')) {
776 $platform = "Diaspora";
777 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
778 $version = trim(str_replace("x-diaspora-version:", "", $version));
779 $network = NETWORK_DIASPORA;
785 // Test for Statusnet
786 // Will also return data for Friendica and GNU Social - but it will be overwritten later
787 // The "not implemented" is a special treatment for really, really old Friendica versions
788 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
789 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
790 $platform = "StatusNet";
791 $version = trim($serverret["body"], '"');
792 $network = NETWORK_OSTATUS;
795 // Test for GNU Social
796 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
797 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
798 $platform = "GNU Social";
799 $version = trim($serverret["body"], '"');
800 $network = NETWORK_OSTATUS;
803 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
804 if ($serverret["success"]) {
805 $data = json_decode($serverret["body"]);
807 if (isset($data->site->server)) {
808 $last_contact = datetime_convert();
810 if (isset($data->site->hubzilla)) {
811 $platform = $data->site->hubzilla->PLATFORM_NAME;
812 $version = $data->site->hubzilla->RED_VERSION;
813 $network = NETWORK_DIASPORA;
815 if (isset($data->site->redmatrix)) {
816 if (isset($data->site->redmatrix->PLATFORM_NAME))
817 $platform = $data->site->redmatrix->PLATFORM_NAME;
818 elseif (isset($data->site->redmatrix->RED_PLATFORM))
819 $platform = $data->site->redmatrix->RED_PLATFORM;
821 $version = $data->site->redmatrix->RED_VERSION;
822 $network = NETWORK_DIASPORA;
824 if (isset($data->site->friendica)) {
825 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
826 $version = $data->site->friendica->FRIENDICA_VERSION;
827 $network = NETWORK_DFRN;
830 $site_name = $data->site->name;
832 $data->site->closed = poco_to_boolean($data->site->closed);
833 $data->site->private = poco_to_boolean($data->site->private);
834 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
836 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
837 $register_policy = REGISTER_APPROVE;
838 elseif (!$data->site->closed AND !$data->site->private)
839 $register_policy = REGISTER_OPEN;
841 $register_policy = REGISTER_CLOSED;
846 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
848 $serverret = z_fetch_url($server_url."/statistics.json");
849 if ($serverret["success"]) {
850 $data = json_decode($serverret["body"]);
852 $version = $data->version;
854 $site_name = $data->name;
856 if (isset($data->network) AND ($platform == ""))
857 $platform = $data->network;
859 if ($platform == "Diaspora")
860 $network = NETWORK_DIASPORA;
862 if ($data->registrations_open)
863 $register_policy = REGISTER_OPEN;
865 $register_policy = REGISTER_CLOSED;
867 if (isset($data->version))
868 $last_contact = datetime_convert();
872 // Check for noscrape
873 // Friendica servers could be detected as OStatus servers
874 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
875 $serverret = z_fetch_url($server_url."/friendica/json");
877 if (!$serverret["success"])
878 $serverret = z_fetch_url($server_url."/friendika/json");
880 if ($serverret["success"]) {
881 $data = json_decode($serverret["body"]);
883 if (isset($data->version)) {
884 $last_contact = datetime_convert();
885 $network = NETWORK_DFRN;
887 $noscrape = $data->no_scrape_url;
888 $version = $data->version;
889 $site_name = $data->site_name;
891 $register_policy_str = $data->register_policy;
892 $platform = $data->platform;
894 switch ($register_policy_str) {
895 case "REGISTER_CLOSED":
896 $register_policy = REGISTER_CLOSED;
898 case "REGISTER_APPROVE":
899 $register_policy = REGISTER_APPROVE;
901 case "REGISTER_OPEN":
902 $register_policy = REGISTER_OPEN;
911 $serverret = z_fetch_url($server_url."/poco");
912 if ($serverret["success"]) {
913 $data = json_decode($serverret["body"]);
914 if (isset($data->totalResults)) {
915 $poco = $server_url."/poco";
916 $last_contact = datetime_convert();
921 // Check again if the server exists
922 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
925 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
926 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
931 intval($register_policy),
936 dbesc($last_contact),
937 dbesc($last_failure),
938 dbesc(normalise_link($server_url))
941 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
942 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
944 dbesc(normalise_link($server_url)),
948 intval($register_policy),
953 dbesc(datetime_convert()),
954 dbesc($last_contact),
955 dbesc($last_failure),
956 dbesc(datetime_convert())
959 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
964 function poco_contact_from_body($body, $created, $cid, $uid) {
965 preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
966 function ($match) use ($created, $cid, $uid){
967 return(sub_poco_from_share($match, $created, $cid, $uid));
971 function sub_poco_from_share($share, $created, $cid, $uid) {
973 preg_match("/profile='(.*?)'/ism", $share[1], $matches);
974 if ($matches[1] != "")
975 $profile = $matches[1];
977 preg_match('/profile="(.*?)"/ism', $share[1], $matches);
978 if ($matches[1] != "")
979 $profile = $matches[1];
984 logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
985 poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
988 function poco_store($item) {
991 if ($item['private'])
994 // Or is it from a network where we don't store the global contacts?
995 if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
998 // Is it a global copy?
999 $store_gcontact = ($item["uid"] == 0);
1001 // Is it a comment on a global copy?
1002 if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
1003 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
1004 $store_gcontact = count($q);
1007 if (!$store_gcontact)
1010 // "3" means: We don't know this contact directly (Maybe a reshared item)
1013 $profile_url = $item["author-link"];
1015 // Is it a user from our server?
1016 $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
1017 dbesc(normalise_link($item["author-link"])));
1019 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
1021 $network = NETWORK_DFRN;
1022 } else { // Is it a contact from a user on our server?
1023 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
1024 AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
1025 dbesc(normalise_link($item["author-link"])),
1026 dbesc(normalise_link($item["author-link"])),
1027 dbesc($item["author-link"]),
1028 dbesc(NETWORK_STATUSNET));
1031 $network = $q[0]["network"];
1032 $profile_url = $q[0]["url"];
1033 logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
1037 if ($generation == 3)
1038 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
1040 poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
1042 // Maybe its a body with a shared item? Then extract a global contact from it.
1043 poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
1046 function count_common_friends($uid,$cid) {
1048 $r = q("SELECT count(*) as `total`
1049 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1050 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1051 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1052 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1059 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1061 return $r[0]['total'];
1067 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1070 $sql_extra = " order by rand() ";
1072 $sql_extra = " order by `gcontact`.`name` asc ";
1074 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1076 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1077 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1078 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1079 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1080 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1081 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1082 $sql_extra LIMIT %d, %d",
1096 function count_common_friends_zcid($uid,$zcid) {
1098 $r = q("SELECT count(*) as `total`
1099 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1100 where `glink`.`zcid` = %d
1101 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1107 return $r[0]['total'];
1112 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1115 $sql_extra = " order by rand() ";
1117 $sql_extra = " order by `gcontact`.`name` asc ";
1119 $r = q("SELECT `gcontact`.*
1120 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1121 where `glink`.`zcid` = %d
1122 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1123 $sql_extra limit %d, %d",
1135 function count_all_friends($uid,$cid) {
1137 $r = q("SELECT count(*) as `total`
1138 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1139 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1140 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1146 return $r[0]['total'];
1152 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1154 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1156 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1157 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1158 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1159 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1160 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1173 function suggestion_query($uid, $start = 0, $limit = 80) {
1178 $network = array(NETWORK_DFRN);
1180 if (get_config('system','diaspora_enabled'))
1181 $network[] = NETWORK_DIASPORA;
1183 if (!get_config('system','ostatus_disabled'))
1184 $network[] = NETWORK_OSTATUS;
1186 $sql_network = implode("', '", $network);
1187 //$sql_network = "'".$sql_network."', ''";
1188 $sql_network = "'".$sql_network."'";
1190 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1191 INNER JOIN glink on glink.gcid = gcontact.id
1192 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1193 and not gcontact.name in ( select name from contact where uid = %d )
1194 and not gcontact.id in ( select gcid from gcign where uid = %d )
1195 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1196 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1197 AND `gcontact`.`network` IN (%s)
1198 group by glink.gcid order by gcontact.updated desc,total desc limit %d, %d ",
1208 if(count($r) && count($r) >= ($limit -1))
1211 $r2 = q("SELECT gcontact.* from gcontact
1212 INNER JOIN glink on glink.gcid = gcontact.id
1213 where glink.uid = 0 and glink.cid = 0 and glink.zcid = 0 and not gcontact.nurl in ( select nurl from contact where uid = %d )
1214 and not gcontact.name in ( select name from contact where uid = %d )
1215 and not gcontact.id in ( select gcid from gcign where uid = %d )
1216 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1217 AND `gcontact`.`network` IN (%s)
1218 order by rand() limit %d, %d ",
1228 foreach ($r2 AS $suggestion)
1229 $list[$suggestion["nurl"]] = $suggestion;
1231 foreach ($r AS $suggestion)
1232 $list[$suggestion["nurl"]] = $suggestion;
1237 function update_suggestions() {
1243 // To-Do: Check if it is really neccessary to poll the own server
1244 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1246 $done[] = $a->get_baseurl() . '/poco';
1248 if(strlen(get_config('system','directory'))) {
1249 $x = fetch_url(get_server()."/pubsites");
1251 $j = json_decode($x);
1253 foreach($j->entries as $entry) {
1255 poco_check_server($entry->url);
1257 $url = $entry->url . '/poco';
1258 if(! in_array($url,$done))
1259 poco_load(0,0,0,$entry->url . '/poco');
1265 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1266 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1267 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1271 foreach($r as $rr) {
1272 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1273 if(! in_array($base,$done))
1274 poco_load(0,0,0,$base);
1279 function poco_discover_federation() {
1280 $last = get_config('poco','last_federation_discovery');
1283 $next = $last + (24 * 60 * 60);
1288 $serverdata = fetch_url("http://the-federation.info/pods.json");
1293 $servers = json_decode($serverdata);
1295 foreach($servers->pods AS $server)
1296 poco_check_server("https://".$server->host);
1298 set_config('poco','last_federation_discovery', time());
1302 function poco_discover($complete = false) {
1304 // Update the server list
1305 poco_discover_federation();
1309 $requery_days = intval(get_config("system", "poco_requery_days"));
1311 if ($requery_days == 0)
1314 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1316 $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));
1318 foreach ($r AS $server) {
1320 if (!poco_check_server($server["url"], $server["network"])) {
1321 // The server is not reachable? Okay, then we will try it later
1322 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1326 // Fetch all users from the other server
1327 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1329 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1331 $retdata = z_fetch_url($url);
1332 if ($retdata["success"]) {
1333 $data = json_decode($retdata["body"]);
1335 poco_discover_server($data, 2);
1337 if (get_config('system','poco_discovery') > 1) {
1339 $timeframe = get_config('system','poco_discovery_since');
1340 if ($timeframe == 0)
1343 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1345 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1346 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1350 $retdata = z_fetch_url($url);
1351 if ($retdata["success"]) {
1352 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1353 $success = poco_discover_server(json_decode($retdata["body"]));
1356 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1357 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1358 poco_discover_server_users($data, $server);
1362 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1363 if (!$complete AND (--$no_of_queries == 0))
1366 // If the server hadn't replied correctly, then force a sanity check
1367 poco_check_server($server["url"], $server["network"], true);
1369 // If we couldn't reach the server, we will try it some time later
1370 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1375 function poco_discover_server_users($data, $server) {
1377 if (!isset($data->entry))
1380 foreach ($data->entry AS $entry) {
1382 if (isset($entry->urls)) {
1383 foreach($entry->urls as $url)
1384 if($url->type == 'profile') {
1385 $profile_url = $url->value;
1386 $urlparts = parse_url($profile_url);
1387 $username = end(explode("/", $urlparts["path"]));
1390 if ($username != "") {
1391 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1393 // Fetch all contacts from a given user from the other server
1394 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1396 $retdata = z_fetch_url($url);
1397 if ($retdata["success"])
1398 poco_discover_server(json_decode($retdata["body"]), 3);
1403 function poco_discover_server($data, $default_generation = 0) {
1405 if (!isset($data->entry) OR !count($data->entry))
1410 foreach ($data->entry AS $entry) {
1412 $profile_photo = '';
1416 $updated = '0000-00-00 00:00:00';
1421 $generation = $default_generation;
1423 $name = $entry->displayName;
1425 if(isset($entry->urls)) {
1426 foreach($entry->urls as $url) {
1427 if($url->type == 'profile') {
1428 $profile_url = $url->value;
1431 if($url->type == 'webfinger') {
1432 $connect_url = str_replace('acct:' , '', $url->value);
1438 if(isset($entry->photos)) {
1439 foreach($entry->photos as $photo) {
1440 if($photo->type == 'profile') {
1441 $profile_photo = $photo->value;
1447 if(isset($entry->updated))
1448 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1450 if(isset($entry->network))
1451 $network = $entry->network;
1453 if(isset($entry->currentLocation))
1454 $location = $entry->currentLocation;
1456 if(isset($entry->aboutMe))
1457 $about = html2bbcode($entry->aboutMe);
1459 if(isset($entry->gender))
1460 $gender = $entry->gender;
1462 if(isset($entry->generation) AND ($entry->generation > 0))
1463 $generation = ++$entry->generation;
1465 if(isset($entry->tags))
1466 foreach($entry->tags as $tag)
1467 $keywords = implode(", ", $tag);
1469 if ($generation > 0) {
1472 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1473 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1474 logger("Done for profile ".$profile_url, LOGGER_DEBUG);