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 if ($profile_url == "")
177 $urlparts = parse_url($profile_url);
178 if (!isset($urlparts["scheme"]))
181 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
182 "identi.ca", "alpha.app.net")))
185 $orig_updated = $updated;
187 // Don't store the statusnet connector as network
188 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
189 if ($network == NETWORK_STATUSNET)
192 // The global contacts should contain the original picture, not the cached one
193 if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link($a->get_baseurl()."/photo/")))
196 $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
197 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
200 $network = $r[0]["network"];
202 if (($network == "") OR ($network == NETWORK_OSTATUS)) {
203 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
204 dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
207 $network = $r[0]["network"];
208 $profile_url = $r[0]["url"];
212 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
213 dbesc(normalise_link($profile_url))
217 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
218 $network = $x[0]["network"];
220 if ($updated == "0000-00-00 00:00:00")
221 $updated = $x[0]["updated"];
223 $created = $x[0]["created"];
224 $server_url = $x[0]["server_url"];
225 $nick = $x[0]["nick"];
227 $created = "0000-00-00 00:00:00";
230 $urlparts = parse_url($profile_url);
231 $nick = end(explode("/", $urlparts["path"]));
234 if ((($network == "") OR ($name == "") OR ($profile_photo == "") OR ($server_url == ""))
235 AND poco_reachable($profile_url, $server_url, $network, true)) {
236 $data = probe_url($profile_url);
238 $network = $data["network"];
239 $name = $data["name"];
240 $nick = $data["nick"];
241 $profile_url = $data["url"];
242 $profile_photo = $data["photo"];
243 $server_url = $data["baseurl"];
246 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
247 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
249 dbesc(normalise_link($profile_url))
253 if (($name == "") OR ($profile_photo == ""))
256 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
259 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
261 poco_check_server($server_url, $network);
266 if (($location == "") AND ($x[0]['location'] != ""))
267 $location = $x[0]['location'];
269 if (($about == "") AND ($x[0]['about'] != ""))
270 $about = $x[0]['about'];
272 if (($gender == "") AND ($x[0]['gender'] != ""))
273 $gender = $x[0]['gender'];
275 if (($keywords == "") AND ($x[0]['keywords'] != ""))
276 $keywords = $x[0]['keywords'];
278 if (($generation == 0) AND ($x[0]['generation'] > 0))
279 $generation = $x[0]['generation'];
281 if($x[0]['name'] != $name || $x[0]['photo'] != $profile_photo || $x[0]['updated'] < $updated) {
282 q("UPDATE `gcontact` SET `name` = '%s', `network` = '%s', `photo` = '%s', `connect` = '%s', `url` = '%s', `server_url` = '%s',
283 `updated` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s', `generation` = %d
284 WHERE (`generation` >= %d OR `generation` = 0) AND `nurl` = '%s'",
287 dbesc($profile_photo),
298 dbesc(normalise_link($profile_url))
302 q("INSERT INTO `gcontact` (`name`, `nick`, `network`, `url`, `nurl`, `photo`, `connect`, `server_url`, `created`, `updated`, `location`, `about`, `keywords`, `gender`, `generation`)
303 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
308 dbesc(normalise_link($profile_url)),
309 dbesc($profile_photo),
312 dbesc(datetime_convert()),
320 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
321 dbesc(normalise_link($profile_url))
330 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
337 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
342 dbesc(datetime_convert())
345 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
346 dbesc(datetime_convert()),
354 // For unknown reasons there are sometimes duplicates
355 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d AND
356 NOT EXISTS (SELECT `gcid` FROM `glink` WHERE `gcid` = `gcontact`.`id`)",
357 dbesc(normalise_link($profile_url)),
364 function poco_reachable($profile, $server = "", $network = "", $force = false) {
367 $server = poco_detect_server($profile);
372 return poco_check_server($server, $network, $force);
375 function poco_detect_server($profile) {
377 // Try to detect the server path based upon some known standard paths
380 if ($server_url == "") {
381 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
382 if ($friendica != $profile) {
383 $server_url = $friendica;
384 $network = NETWORK_DFRN;
388 if ($server_url == "") {
389 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
390 if ($diaspora != $profile) {
391 $server_url = $diaspora;
392 $network = NETWORK_DIASPORA;
396 if ($server_url == "") {
397 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
398 if ($red != $profile) {
400 $network = NETWORK_DIASPORA;
407 function poco_last_updated($profile, $force = false) {
409 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
410 dbesc(normalise_link($profile)));
412 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
413 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
414 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
416 $urlparts = parse_url($profile);
417 if (!isset($urlparts["scheme"]))
420 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
421 "identi.ca", "alpha.app.net"))) {
422 $networks = array("www.facebook.com" => NETWORK_FACEBOOK,
423 "facebook.com" => NETWORK_FACEBOOK,
424 "twitter.com" => NETWORK_TWITTER,
425 "identi.ca" => NETWORK_PUMPIO,
426 "alpha.app.net" => NETWORK_APPNET);
428 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
429 dbesc($networks[$urlparts["host"]]), dbesc(normalise_link($profile)));
433 if ($gcontacts[0]["server_url"] != "")
434 $server_url = $gcontacts[0]["server_url"];
436 $server_url = poco_detect_server($profile);
438 if ($server_url != "") {
439 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
442 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
443 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
448 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
449 dbesc($server_url), dbesc(normalise_link($profile)));
452 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
453 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
454 dbesc(normalise_link($server_url)));
457 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
458 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
463 // noscrape is really fast so we don't cache the call.
464 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
466 // Use noscrape if possible
467 $server = q("SELECT `noscrape` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
470 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
471 if ($noscraperet["success"] AND ($noscraperet["body"] = "")) {
472 $noscrape = json_decode($noscraperet["body"], true);
474 if (($noscrape["name"] != "") AND ($noscrape["name"] != $gcontacts[0]["name"]))
475 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
476 dbesc($noscrape["name"]), dbesc(normalise_link($profile)));
478 if (($noscrape["photo"] != "") AND ($noscrape["photo"] != $gcontacts[0]["photo"]))
479 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
480 dbesc($noscrape["photo"]), dbesc(normalise_link($profile)));
482 if (($noscrape["updated"] != "") AND ($noscrape["updated"] != $gcontacts[0]["updated"]))
483 q("UPDATE `gcontact` SET `updated` = '%s' WHERE `nurl` = '%s'",
484 dbesc($noscrape["updated"]), dbesc(normalise_link($profile)));
486 if (($noscrape["gender"] != "") AND ($noscrape["gender"] != $gcontacts[0]["gender"]))
487 q("UPDATE `gcontact` SET `gender` = '%s' WHERE `nurl` = '%s'",
488 dbesc($noscrape["gender"]), dbesc(normalise_link($profile)));
490 if (($noscrape["about"] != "") AND ($noscrape["about"] != $gcontacts[0]["name"]))
491 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
492 dbesc($noscrape["about"]), dbesc(normalise_link($profile)));
494 if (isset($noscrape["tags"]))
495 $keywords = implode(" ", $noscrape["tags"]);
499 if (($keywords != "") AND ($keywords != $gcontacts[0]["keywords"]))
500 q("UPDATE `gcontact` SET `keywords` = '%s' WHERE `nurl` = '%s'",
501 dbesc($keywords), dbesc(normalise_link($profile)));
503 $location = $noscrape["locality"];
505 if ($noscrape["region"] != "") {
509 $location .= $noscrape["region"];
512 if ($noscrape["country-name"] != "") {
516 $location .= $noscrape["country-name"];
519 if (($location != "") AND ($location != $gcontacts[0]["location"]))
520 q("UPDATE `gcontact` SET `location` = '%s' WHERE `nurl` = '%s'",
521 dbesc($location), dbesc(normalise_link($profile)));
523 // If we got data from noscrape then mark the contact as reachable
524 if (is_array($noscrape) AND count($noscrape))
525 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
526 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
528 return $noscrape["updated"];
533 // If we only can poll the feed, then we only do this once a while
534 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"]))
535 return $gcontacts[0]["updated"];
537 $data = probe_url($profile);
539 if (($data["poll"] == "") OR ($data["network"] == NETWORK_FEED)) {
540 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
541 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
545 if (($data["name"] != "") AND ($data["name"] != $gcontacts[0]["name"]))
546 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
547 dbesc($data["name"]), dbesc(normalise_link($profile)));
549 if (($data["nick"] != "") AND ($data["nick"] != $gcontacts[0]["nick"]))
550 q("UPDATE `gcontact` SET `nick` = '%s' WHERE `nurl` = '%s'",
551 dbesc($data["nick"]), dbesc(normalise_link($profile)));
553 if (($data["addr"] != "") AND ($data["addr"] != $gcontacts[0]["connect"]))
554 q("UPDATE `gcontact` SET `connect` = '%s' WHERE `nurl` = '%s'",
555 dbesc($data["addr"]), dbesc(normalise_link($profile)));
557 if (($data["photo"] != "") AND ($data["photo"] != $gcontacts[0]["photo"]))
558 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
559 dbesc($data["photo"]), dbesc(normalise_link($profile)));
561 if (($data["baseurl"] != "") AND ($data["baseurl"] != $gcontacts[0]["server_url"]))
562 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
563 dbesc($data["baseurl"]), dbesc(normalise_link($profile)));
565 $feedret = z_fetch_url($data["poll"]);
567 if (!$feedret["success"]) {
568 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
569 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
573 $doc = new DOMDocument();
574 @$doc->loadXML($feedret["body"]);
576 $xpath = new DomXPath($doc);
577 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
579 $entries = $xpath->query('/atom:feed/atom:entry');
583 foreach ($entries AS $entry) {
584 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
585 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
587 if ($last_updated < $published)
588 $last_updated = $published;
590 if ($last_updated < $updated)
591 $last_updated = $updated;
594 // Maybe there aren't any entries. Then check if it is a valid feed
595 if ($last_updated == "")
596 if ($xpath->query('/atom:feed')->length > 0)
597 $last_updated = "0000-00-00 00:00:00";
599 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
600 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
602 if (($gcontacts[0]["generation"] == 0))
603 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
604 dbesc(normalise_link($profile)));
606 return($last_updated);
609 function poco_do_update($created, $updated, $last_failure, $last_contact) {
610 $now = strtotime(datetime_convert());
612 if ($updated > $last_contact)
613 $contact_time = strtotime($updated);
615 $contact_time = strtotime($last_contact);
617 $failure_time = strtotime($last_failure);
618 $created_time = strtotime($created);
620 // If there is no "created" time then use the current time
621 if ($created_time <= 0)
622 $created_time = $now;
624 // If the last contact was less than 24 hours then don't update
625 if (($now - $contact_time) < (60 * 60 * 24))
628 // If the last failure was less than 24 hours then don't update
629 if (($now - $failure_time) < (60 * 60 * 24))
632 // If the last contact was less than a week ago and the last failure is older than a week then don't update
633 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
636 // 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
637 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
640 // 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
641 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
647 function poco_to_boolean($val) {
648 if (($val == "true") OR ($val == 1))
650 if (($val == "false") OR ($val == 0))
656 function poco_check_server($server_url, $network = "", $force = false) {
658 if ($server_url == "")
661 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
664 if ($servers[0]["created"] == "0000-00-00 00:00:00")
665 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
666 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
668 $poco = $servers[0]["poco"];
669 $noscrape = $servers[0]["noscrape"];
672 $network = $servers[0]["network"];
674 $last_contact = $servers[0]["last_contact"];
675 $last_failure = $servers[0]["last_failure"];
676 $version = $servers[0]["version"];
677 $platform = $servers[0]["platform"];
678 $site_name = $servers[0]["site_name"];
679 $info = $servers[0]["info"];
680 $register_policy = $servers[0]["register_policy"];
682 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
683 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
684 return ($last_contact >= $last_failure);
693 $register_policy = -1;
695 $last_contact = "0000-00-00 00:00:00";
696 $last_failure = "0000-00-00 00:00:00";
698 logger("Server ".$server_url." is unknown. Start discovery.", LOGGER_DEBUG);
701 $orig_last_failure = $last_failure;
703 // Check if the page is accessible via SSL.
704 $server_url = str_replace("http://", "https://", $server_url);
705 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
707 // Maybe the page is unencrypted only?
708 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
709 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
710 $server_url = str_replace("https://", "http://", $server_url);
711 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
713 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
716 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
717 $last_failure = datetime_convert();
719 } elseif ($network == NETWORK_DIASPORA)
720 $last_contact = datetime_convert();
724 $serverret = z_fetch_url($server_url);
726 $lines = explode("\n",$serverret["header"]);
728 foreach($lines as $line) {
730 if(stristr($line,'X-Diaspora-Version:')) {
731 $platform = "Diaspora";
732 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
733 $version = trim(str_replace("x-diaspora-version:", "", $version));
734 $network = NETWORK_DIASPORA;
740 // Test for Statusnet
741 // Will also return data for Friendica and GNU Social - but it will be overwritten later
742 // The "not implemented" is a special treatment for really, really old Friendica versions
743 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
744 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
745 $platform = "StatusNet";
746 $version = trim($serverret["body"], '"');
747 $network = NETWORK_OSTATUS;
750 // Test for GNU Social
751 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
752 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
753 $platform = "GNU Social";
754 $version = trim($serverret["body"], '"');
755 $network = NETWORK_OSTATUS;
758 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
759 if ($serverret["success"]) {
760 $data = json_decode($serverret["body"]);
762 if (isset($data->site->server)) {
763 $last_contact = datetime_convert();
765 if (isset($data->site->hubzilla)) {
766 $platform = $data->site->hubzilla->PLATFORM_NAME;
767 $version = $data->site->hubzilla->RED_VERSION;
768 $network = NETWORK_DIASPORA;
770 if (isset($data->site->redmatrix)) {
771 if (isset($data->site->redmatrix->PLATFORM_NAME))
772 $platform = $data->site->redmatrix->PLATFORM_NAME;
773 elseif (isset($data->site->redmatrix->RED_PLATFORM))
774 $platform = $data->site->redmatrix->RED_PLATFORM;
776 $version = $data->site->redmatrix->RED_VERSION;
777 $network = NETWORK_DIASPORA;
779 if (isset($data->site->friendica)) {
780 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
781 $version = $data->site->friendica->FRIENDICA_VERSION;
782 $network = NETWORK_DFRN;
785 $site_name = $data->site->name;
787 $data->site->closed = poco_to_boolean($data->site->closed);
788 $data->site->private = poco_to_boolean($data->site->private);
789 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
791 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
792 $register_policy = REGISTER_APPROVE;
793 elseif (!$data->site->closed AND !$data->site->private)
794 $register_policy = REGISTER_OPEN;
796 $register_policy = REGISTER_CLOSED;
801 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
803 $serverret = z_fetch_url($server_url."/statistics.json");
804 if ($serverret["success"]) {
805 $data = json_decode($serverret["body"]);
807 $version = $data->version;
809 $site_name = $data->name;
811 if (isset($data->network) AND ($platform == ""))
812 $platform = $data->network;
814 if ($platform == "Diaspora")
815 $network = NETWORK_DIASPORA;
817 if ($data->registrations_open)
818 $register_policy = REGISTER_OPEN;
820 $register_policy = REGISTER_CLOSED;
822 if (isset($data->version))
823 $last_contact = datetime_convert();
827 // Check for noscrape
828 // Friendica servers could be detected as OStatus servers
829 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
830 $serverret = z_fetch_url($server_url."/friendica/json");
832 if (!$serverret["success"])
833 $serverret = z_fetch_url($server_url."/friendika/json");
835 if ($serverret["success"]) {
836 $data = json_decode($serverret["body"]);
838 if (isset($data->version)) {
839 $last_contact = datetime_convert();
840 $network = NETWORK_DFRN;
842 $noscrape = $data->no_scrape_url;
843 $version = $data->version;
844 $site_name = $data->site_name;
846 $register_policy_str = $data->register_policy;
847 $platform = $data->platform;
849 switch ($register_policy_str) {
850 case "REGISTER_CLOSED":
851 $register_policy = REGISTER_CLOSED;
853 case "REGISTER_APPROVE":
854 $register_policy = REGISTER_APPROVE;
856 case "REGISTER_OPEN":
857 $register_policy = REGISTER_OPEN;
866 $serverret = z_fetch_url($server_url."/poco");
867 if ($serverret["success"]) {
868 $data = json_decode($serverret["body"]);
869 if (isset($data->totalResults)) {
870 $poco = $server_url."/poco";
871 $last_contact = datetime_convert();
876 // Check again if the server exists
877 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
880 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
881 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
886 intval($register_policy),
891 dbesc($last_contact),
892 dbesc($last_failure),
893 dbesc(normalise_link($server_url))
896 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
897 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
899 dbesc(normalise_link($server_url)),
903 intval($register_policy),
908 dbesc(datetime_convert()),
909 dbesc($last_contact),
910 dbesc($last_failure),
911 dbesc(datetime_convert())
914 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
919 function poco_contact_from_body($body, $created, $cid, $uid) {
920 preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
921 function ($match) use ($created, $cid, $uid){
922 return(sub_poco_from_share($match, $created, $cid, $uid));
926 function sub_poco_from_share($share, $created, $cid, $uid) {
928 preg_match("/profile='(.*?)'/ism", $share[1], $matches);
929 if ($matches[1] != "")
930 $profile = $matches[1];
932 preg_match('/profile="(.*?)"/ism', $share[1], $matches);
933 if ($matches[1] != "")
934 $profile = $matches[1];
939 logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
940 poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
943 function poco_store($item) {
946 if ($item['private'])
949 // Or is it from a network where we don't store the global contacts?
950 if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
953 // Is it a global copy?
954 $store_gcontact = ($item["uid"] == 0);
956 // Is it a comment on a global copy?
957 if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
958 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
959 $store_gcontact = count($q);
962 if (!$store_gcontact)
965 // "3" means: We don't know this contact directly (Maybe a reshared item)
968 $profile_url = $item["author-link"];
970 // Is it a user from our server?
971 $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
972 dbesc(normalise_link($item["author-link"])));
974 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
976 $network = NETWORK_DFRN;
977 } else { // Is it a contact from a user on our server?
978 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
979 AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
980 dbesc(normalise_link($item["author-link"])),
981 dbesc(normalise_link($item["author-link"])),
982 dbesc($item["author-link"]),
983 dbesc(NETWORK_STATUSNET));
986 $network = $q[0]["network"];
987 $profile_url = $q[0]["url"];
988 logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
992 if ($generation == 3)
993 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
995 poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
997 // Maybe its a body with a shared item? Then extract a global contact from it.
998 poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
1001 function count_common_friends($uid,$cid) {
1003 $r = q("SELECT count(*) as `total`
1004 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1005 where `glink`.`cid` = %d and `glink`.`uid` = %d
1006 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1013 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1015 return $r[0]['total'];
1021 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1024 $sql_extra = " order by rand() ";
1026 $sql_extra = " order by `gcontact`.`name` asc ";
1028 $r = q("SELECT `gcontact`.*
1029 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1030 where `glink`.`cid` = %d and `glink`.`uid` = %d
1031 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d )
1032 $sql_extra limit %d, %d",
1046 function count_common_friends_zcid($uid,$zcid) {
1048 $r = q("SELECT count(*) as `total`
1049 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1050 where `glink`.`zcid` = %d
1051 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1057 return $r[0]['total'];
1062 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1065 $sql_extra = " order by rand() ";
1067 $sql_extra = " order by `gcontact`.`name` asc ";
1069 $r = q("SELECT `gcontact`.*
1070 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1071 where `glink`.`zcid` = %d
1072 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1073 $sql_extra limit %d, %d",
1085 function count_all_friends($uid,$cid) {
1087 $r = q("SELECT count(*) as `total`
1088 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1089 where `glink`.`cid` = %d and `glink`.`uid` = %d ",
1095 return $r[0]['total'];
1101 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1103 $r = q("SELECT `gcontact`.*
1104 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1105 where `glink`.`cid` = %d and `glink`.`uid` = %d
1106 order by `gcontact`.`name` asc LIMIT %d, %d ",
1118 function suggestion_query($uid, $start = 0, $limit = 80) {
1123 $network = array(NETWORK_DFRN);
1125 if (get_config('system','diaspora_enabled'))
1126 $network[] = NETWORK_DIASPORA;
1128 if (!get_config('system','ostatus_disabled'))
1129 $network[] = NETWORK_OSTATUS;
1131 $sql_network = implode("', '", $network);
1132 //$sql_network = "'".$sql_network."', ''";
1133 $sql_network = "'".$sql_network."'";
1135 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1136 INNER JOIN glink on glink.gcid = gcontact.id
1137 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1138 and not gcontact.name in ( select name from contact where uid = %d )
1139 and not gcontact.id in ( select gcid from gcign where uid = %d )
1140 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1141 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1142 AND `gcontact`.`network` IN (%s)
1143 group by glink.gcid order by gcontact.updated desc,total desc limit %d, %d ",
1153 if(count($r) && count($r) >= ($limit -1))
1156 $r2 = q("SELECT gcontact.* from gcontact
1157 INNER JOIN glink on glink.gcid = gcontact.id
1158 where glink.uid = 0 and glink.cid = 0 and glink.zcid = 0 and not gcontact.nurl in ( select nurl from contact where uid = %d )
1159 and not gcontact.name in ( select name from contact where uid = %d )
1160 and not gcontact.id in ( select gcid from gcign where uid = %d )
1161 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1162 AND `gcontact`.`network` IN (%s)
1163 order by rand() limit %d, %d ",
1173 foreach ($r2 AS $suggestion)
1174 $list[$suggestion["nurl"]] = $suggestion;
1176 foreach ($r AS $suggestion)
1177 $list[$suggestion["nurl"]] = $suggestion;
1182 function update_suggestions() {
1188 // To-Do: Check if it is really neccessary to poll the own server
1189 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1191 $done[] = $a->get_baseurl() . '/poco';
1193 if(strlen(get_config('system','directory_submit_url'))) {
1194 $x = fetch_url('http://dir.friendica.com/pubsites');
1196 $j = json_decode($x);
1198 foreach($j->entries as $entry) {
1200 poco_check_server($entry->url);
1202 $url = $entry->url . '/poco';
1203 if(! in_array($url,$done))
1204 poco_load(0,0,0,$entry->url . '/poco');
1210 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1211 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1212 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1216 foreach($r as $rr) {
1217 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1218 if(! in_array($base,$done))
1219 poco_load(0,0,0,$base);
1224 function poco_discover($complete = false) {
1228 $last_update = date("c", time() - (60 * 60 * 6)); // 24
1229 $last_update = date("c", time() - (60 * 60 * 24)); // 24
1231 $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));
1233 foreach ($r AS $server) {
1235 if (!poco_check_server($server["url"], $server["network"]))
1238 // Fetch all users from the other server
1239 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1241 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1243 $retdata = z_fetch_url($url);
1244 if ($retdata["success"]) {
1245 $data = json_decode($retdata["body"]);
1247 poco_discover_server($data, 2);
1249 if (get_config('system','poco_discovery') > 1) {
1251 $timeframe = get_config('system','poco_discovery_since');
1252 if ($timeframe == 0)
1255 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1257 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1258 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1262 $retdata = z_fetch_url($url);
1263 if ($retdata["success"]) {
1264 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1265 $success = poco_discover_server(json_decode($retdata["body"]));
1268 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1269 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1270 poco_discover_server_users($data, $server);
1274 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1275 if (!$complete AND (--$no_of_queries == 0))
1277 } else // If the server hadn't replied correctly, then force a sanity check
1278 poco_check_server($server["url"], $server["network"], true);
1282 function poco_discover_server_users($data, $server) {
1284 if (!isset($data->entry))
1287 foreach ($data->entry AS $entry) {
1289 if (isset($entry->urls)) {
1290 foreach($entry->urls as $url)
1291 if($url->type == 'profile') {
1292 $profile_url = $url->value;
1293 $urlparts = parse_url($profile_url);
1294 $username = end(explode("/", $urlparts["path"]));
1297 if ($username != "") {
1298 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1300 // Fetch all contacts from a given user from the other server
1301 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1303 $retdata = z_fetch_url($url);
1304 if ($retdata["success"])
1305 poco_discover_server(json_decode($retdata["body"]), 3);
1310 function poco_discover_server($data, $default_generation = 0) {
1312 if (!isset($data->entry) OR !count($data->entry))
1317 foreach ($data->entry AS $entry) {
1319 $profile_photo = '';
1323 $updated = '0000-00-00 00:00:00';
1328 $generation = $default_generation;
1330 $name = $entry->displayName;
1332 if(isset($entry->urls)) {
1333 foreach($entry->urls as $url) {
1334 if($url->type == 'profile') {
1335 $profile_url = $url->value;
1338 if($url->type == 'webfinger') {
1339 $connect_url = str_replace('acct:' , '', $url->value);
1345 if(isset($entry->photos)) {
1346 foreach($entry->photos as $photo) {
1347 if($photo->type == 'profile') {
1348 $profile_photo = $photo->value;
1354 if(isset($entry->updated))
1355 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1357 if(isset($entry->network))
1358 $network = $entry->network;
1360 if(isset($entry->currentLocation))
1361 $location = $entry->currentLocation;
1363 if(isset($entry->aboutMe))
1364 $about = html2bbcode($entry->aboutMe);
1366 if(isset($entry->gender))
1367 $gender = $entry->gender;
1369 if(isset($entry->generation) AND ($entry->generation > 0))
1370 $generation = ++$entry->generation;
1372 if(isset($entry->tags))
1373 foreach($entry->tags as $tag)
1374 $keywords = implode(", ", $tag);
1376 if ($generation > 0) {
1379 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1380 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1381 logger("Done for profile ".$profile_url, LOGGER_DEBUG);