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 if ($gcontacts[0]["server_url"] != "")
417 $server_url = $gcontacts[0]["server_url"];
419 $server_url = poco_detect_server($profile);
421 if ($server_url != "") {
422 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
425 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
426 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
431 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
432 dbesc($server_url), dbesc(normalise_link($profile)));
435 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
436 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
437 dbesc(normalise_link($server_url)));
440 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
441 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
446 // noscrape is really fast so we don't cache the call.
447 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
449 // Use noscrape if possible
450 $server = q("SELECT `noscrape` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
453 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
455 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
457 $noscrape = json_decode($noscraperet["body"], true);
459 if (($noscrape["fn"] != "") AND ($noscrape["fn"] != $gcontacts[0]["name"]))
460 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
461 dbesc($noscrape["fn"]), dbesc(normalise_link($profile)));
463 if (($noscrape["photo"] != "") AND ($noscrape["photo"] != $gcontacts[0]["photo"]))
464 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
465 dbesc($noscrape["photo"]), dbesc(normalise_link($profile)));
467 if (($noscrape["updated"] != "") AND ($noscrape["updated"] != $gcontacts[0]["updated"]))
468 q("UPDATE `gcontact` SET `updated` = '%s' WHERE `nurl` = '%s'",
469 dbesc($noscrape["updated"]), dbesc(normalise_link($profile)));
471 if (($noscrape["gender"] != "") AND ($noscrape["gender"] != $gcontacts[0]["gender"]))
472 q("UPDATE `gcontact` SET `gender` = '%s' WHERE `nurl` = '%s'",
473 dbesc($noscrape["gender"]), dbesc(normalise_link($profile)));
475 if (($noscrape["pdesc"] != "") AND ($noscrape["pdesc"] != $gcontacts[0]["about"]))
476 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
477 dbesc($noscrape["pdesc"]), dbesc(normalise_link($profile)));
479 if (($noscrape["about"] != "") AND ($noscrape["about"] != $gcontacts[0]["about"]))
480 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
481 dbesc($noscrape["about"]), dbesc(normalise_link($profile)));
483 if (isset($noscrape["comm"]) AND ($noscrape["comm"] != $gcontacts[0]["community"]))
484 q("UPDATE `gcontact` SET `community` = %d WHERE `nurl` = '%s'",
485 intval($noscrape["comm"]), dbesc(normalise_link($profile)));
487 if (isset($noscrape["tags"]))
488 $keywords = implode(" ", $noscrape["tags"]);
492 if (($keywords != "") AND ($keywords != $gcontacts[0]["keywords"]))
493 q("UPDATE `gcontact` SET `keywords` = '%s' WHERE `nurl` = '%s'",
494 dbesc($keywords), dbesc(normalise_link($profile)));
496 $location = $noscrape["locality"];
498 if ($noscrape["region"] != "") {
502 $location .= $noscrape["region"];
505 if ($noscrape["country-name"] != "") {
509 $location .= $noscrape["country-name"];
512 if (($location != "") AND ($location != $gcontacts[0]["location"]))
513 q("UPDATE `gcontact` SET `location` = '%s' WHERE `nurl` = '%s'",
514 dbesc($location), dbesc(normalise_link($profile)));
516 // If we got data from noscrape then mark the contact as reachable
517 if (is_array($noscrape) AND count($noscrape))
518 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
519 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
521 return $noscrape["updated"];
526 // If we only can poll the feed, then we only do this once a while
527 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"]))
528 return $gcontacts[0]["updated"];
530 $data = probe_url($profile);
532 if (($data["poll"] == "") OR ($data["network"] == NETWORK_FEED)) {
533 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
534 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
538 if (($data["name"] != "") AND ($data["name"] != $gcontacts[0]["name"]))
539 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
540 dbesc($data["name"]), dbesc(normalise_link($profile)));
542 if (($data["nick"] != "") AND ($data["nick"] != $gcontacts[0]["nick"]))
543 q("UPDATE `gcontact` SET `nick` = '%s' WHERE `nurl` = '%s'",
544 dbesc($data["nick"]), dbesc(normalise_link($profile)));
546 if (($data["addr"] != "") AND ($data["addr"] != $gcontacts[0]["connect"]))
547 q("UPDATE `gcontact` SET `connect` = '%s' WHERE `nurl` = '%s'",
548 dbesc($data["addr"]), dbesc(normalise_link($profile)));
550 if (($data["photo"] != "") AND ($data["photo"] != $gcontacts[0]["photo"]))
551 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
552 dbesc($data["photo"]), dbesc(normalise_link($profile)));
554 if (($data["baseurl"] != "") AND ($data["baseurl"] != $gcontacts[0]["server_url"]))
555 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
556 dbesc($data["baseurl"]), dbesc(normalise_link($profile)));
558 $feedret = z_fetch_url($data["poll"]);
560 if (!$feedret["success"]) {
561 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
562 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
566 $doc = new DOMDocument();
567 @$doc->loadXML($feedret["body"]);
569 $xpath = new DomXPath($doc);
570 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
572 $entries = $xpath->query('/atom:feed/atom:entry');
576 foreach ($entries AS $entry) {
577 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
578 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
580 if ($last_updated < $published)
581 $last_updated = $published;
583 if ($last_updated < $updated)
584 $last_updated = $updated;
587 // Maybe there aren't any entries. Then check if it is a valid feed
588 if ($last_updated == "")
589 if ($xpath->query('/atom:feed')->length > 0)
590 $last_updated = "0000-00-00 00:00:00";
592 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
593 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
595 if (($gcontacts[0]["generation"] == 0))
596 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
597 dbesc(normalise_link($profile)));
599 return($last_updated);
602 function poco_do_update($created, $updated, $last_failure, $last_contact) {
603 $now = strtotime(datetime_convert());
605 if ($updated > $last_contact)
606 $contact_time = strtotime($updated);
608 $contact_time = strtotime($last_contact);
610 $failure_time = strtotime($last_failure);
611 $created_time = strtotime($created);
613 // If there is no "created" time then use the current time
614 if ($created_time <= 0)
615 $created_time = $now;
617 // If the last contact was less than 24 hours then don't update
618 if (($now - $contact_time) < (60 * 60 * 24))
621 // If the last failure was less than 24 hours then don't update
622 if (($now - $failure_time) < (60 * 60 * 24))
625 // If the last contact was less than a week ago and the last failure is older than a week then don't update
626 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
629 // 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
630 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
633 // 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
634 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
640 function poco_to_boolean($val) {
641 if (($val == "true") OR ($val == 1))
643 if (($val == "false") OR ($val == 0))
649 function poco_check_server($server_url, $network = "", $force = false) {
651 if ($server_url == "")
654 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
657 if ($servers[0]["created"] == "0000-00-00 00:00:00")
658 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
659 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
661 $poco = $servers[0]["poco"];
662 $noscrape = $servers[0]["noscrape"];
665 $network = $servers[0]["network"];
667 $last_contact = $servers[0]["last_contact"];
668 $last_failure = $servers[0]["last_failure"];
669 $version = $servers[0]["version"];
670 $platform = $servers[0]["platform"];
671 $site_name = $servers[0]["site_name"];
672 $info = $servers[0]["info"];
673 $register_policy = $servers[0]["register_policy"];
675 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
676 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
677 return ($last_contact >= $last_failure);
686 $register_policy = -1;
688 $last_contact = "0000-00-00 00:00:00";
689 $last_failure = "0000-00-00 00:00:00";
691 logger("Server ".$server_url." is unknown. Start discovery.", LOGGER_DEBUG);
694 $orig_last_failure = $last_failure;
696 // Check if the page is accessible via SSL.
697 $server_url = str_replace("http://", "https://", $server_url);
698 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
700 // Maybe the page is unencrypted only?
701 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
702 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
703 $server_url = str_replace("https://", "http://", $server_url);
704 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
706 $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 $last_failure = datetime_convert();
712 } elseif ($network == NETWORK_DIASPORA)
713 $last_contact = datetime_convert();
717 $serverret = z_fetch_url($server_url);
719 $lines = explode("\n",$serverret["header"]);
721 foreach($lines as $line) {
723 if(stristr($line,'X-Diaspora-Version:')) {
724 $platform = "Diaspora";
725 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
726 $version = trim(str_replace("x-diaspora-version:", "", $version));
727 $network = NETWORK_DIASPORA;
733 // Test for Statusnet
734 // Will also return data for Friendica and GNU Social - but it will be overwritten later
735 // The "not implemented" is a special treatment for really, really old Friendica versions
736 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
737 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
738 $platform = "StatusNet";
739 $version = trim($serverret["body"], '"');
740 $network = NETWORK_OSTATUS;
743 // Test for GNU Social
744 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
745 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
746 $platform = "GNU Social";
747 $version = trim($serverret["body"], '"');
748 $network = NETWORK_OSTATUS;
751 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
752 if ($serverret["success"]) {
753 $data = json_decode($serverret["body"]);
755 if (isset($data->site->server)) {
756 $last_contact = datetime_convert();
758 if (isset($data->site->hubzilla)) {
759 $platform = $data->site->hubzilla->PLATFORM_NAME;
760 $version = $data->site->hubzilla->RED_VERSION;
761 $network = NETWORK_DIASPORA;
763 if (isset($data->site->redmatrix)) {
764 if (isset($data->site->redmatrix->PLATFORM_NAME))
765 $platform = $data->site->redmatrix->PLATFORM_NAME;
766 elseif (isset($data->site->redmatrix->RED_PLATFORM))
767 $platform = $data->site->redmatrix->RED_PLATFORM;
769 $version = $data->site->redmatrix->RED_VERSION;
770 $network = NETWORK_DIASPORA;
772 if (isset($data->site->friendica)) {
773 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
774 $version = $data->site->friendica->FRIENDICA_VERSION;
775 $network = NETWORK_DFRN;
778 $site_name = $data->site->name;
780 $data->site->closed = poco_to_boolean($data->site->closed);
781 $data->site->private = poco_to_boolean($data->site->private);
782 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
784 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
785 $register_policy = REGISTER_APPROVE;
786 elseif (!$data->site->closed AND !$data->site->private)
787 $register_policy = REGISTER_OPEN;
789 $register_policy = REGISTER_CLOSED;
794 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
796 $serverret = z_fetch_url($server_url."/statistics.json");
797 if ($serverret["success"]) {
798 $data = json_decode($serverret["body"]);
800 $version = $data->version;
802 $site_name = $data->name;
804 if (isset($data->network) AND ($platform == ""))
805 $platform = $data->network;
807 if ($platform == "Diaspora")
808 $network = NETWORK_DIASPORA;
810 if ($data->registrations_open)
811 $register_policy = REGISTER_OPEN;
813 $register_policy = REGISTER_CLOSED;
815 if (isset($data->version))
816 $last_contact = datetime_convert();
820 // Check for noscrape
821 // Friendica servers could be detected as OStatus servers
822 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
823 $serverret = z_fetch_url($server_url."/friendica/json");
825 if (!$serverret["success"])
826 $serverret = z_fetch_url($server_url."/friendika/json");
828 if ($serverret["success"]) {
829 $data = json_decode($serverret["body"]);
831 if (isset($data->version)) {
832 $last_contact = datetime_convert();
833 $network = NETWORK_DFRN;
835 $noscrape = $data->no_scrape_url;
836 $version = $data->version;
837 $site_name = $data->site_name;
839 $register_policy_str = $data->register_policy;
840 $platform = $data->platform;
842 switch ($register_policy_str) {
843 case "REGISTER_CLOSED":
844 $register_policy = REGISTER_CLOSED;
846 case "REGISTER_APPROVE":
847 $register_policy = REGISTER_APPROVE;
849 case "REGISTER_OPEN":
850 $register_policy = REGISTER_OPEN;
859 $serverret = z_fetch_url($server_url."/poco");
860 if ($serverret["success"]) {
861 $data = json_decode($serverret["body"]);
862 if (isset($data->totalResults)) {
863 $poco = $server_url."/poco";
864 $last_contact = datetime_convert();
869 // Check again if the server exists
870 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
873 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
874 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
879 intval($register_policy),
884 dbesc($last_contact),
885 dbesc($last_failure),
886 dbesc(normalise_link($server_url))
889 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
890 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
892 dbesc(normalise_link($server_url)),
896 intval($register_policy),
901 dbesc(datetime_convert()),
902 dbesc($last_contact),
903 dbesc($last_failure),
904 dbesc(datetime_convert())
907 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
912 function poco_contact_from_body($body, $created, $cid, $uid) {
913 preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
914 function ($match) use ($created, $cid, $uid){
915 return(sub_poco_from_share($match, $created, $cid, $uid));
919 function sub_poco_from_share($share, $created, $cid, $uid) {
921 preg_match("/profile='(.*?)'/ism", $share[1], $matches);
922 if ($matches[1] != "")
923 $profile = $matches[1];
925 preg_match('/profile="(.*?)"/ism', $share[1], $matches);
926 if ($matches[1] != "")
927 $profile = $matches[1];
932 logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
933 poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
936 function poco_store($item) {
939 if ($item['private'])
942 // Or is it from a network where we don't store the global contacts?
943 if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
946 // Is it a global copy?
947 $store_gcontact = ($item["uid"] == 0);
949 // Is it a comment on a global copy?
950 if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
951 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
952 $store_gcontact = count($q);
955 if (!$store_gcontact)
958 // "3" means: We don't know this contact directly (Maybe a reshared item)
961 $profile_url = $item["author-link"];
963 // Is it a user from our server?
964 $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
965 dbesc(normalise_link($item["author-link"])));
967 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
969 $network = NETWORK_DFRN;
970 } else { // Is it a contact from a user on our server?
971 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
972 AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
973 dbesc(normalise_link($item["author-link"])),
974 dbesc(normalise_link($item["author-link"])),
975 dbesc($item["author-link"]),
976 dbesc(NETWORK_STATUSNET));
979 $network = $q[0]["network"];
980 $profile_url = $q[0]["url"];
981 logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
985 if ($generation == 3)
986 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
988 poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
990 // Maybe its a body with a shared item? Then extract a global contact from it.
991 poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
994 function count_common_friends($uid,$cid) {
996 $r = q("SELECT count(*) as `total`
997 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
998 where `glink`.`cid` = %d and `glink`.`uid` = %d
999 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1006 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1008 return $r[0]['total'];
1014 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1017 $sql_extra = " order by rand() ";
1019 $sql_extra = " order by `gcontact`.`name` asc ";
1021 $r = q("SELECT `gcontact`.*
1022 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1023 where `glink`.`cid` = %d and `glink`.`uid` = %d
1024 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d )
1025 $sql_extra limit %d, %d",
1039 function count_common_friends_zcid($uid,$zcid) {
1041 $r = q("SELECT count(*) as `total`
1042 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1043 where `glink`.`zcid` = %d
1044 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1050 return $r[0]['total'];
1055 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1058 $sql_extra = " order by rand() ";
1060 $sql_extra = " order by `gcontact`.`name` asc ";
1062 $r = q("SELECT `gcontact`.*
1063 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1064 where `glink`.`zcid` = %d
1065 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1066 $sql_extra limit %d, %d",
1078 function count_all_friends($uid,$cid) {
1080 $r = q("SELECT count(*) as `total`
1081 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1082 where `glink`.`cid` = %d and `glink`.`uid` = %d ",
1088 return $r[0]['total'];
1094 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1096 $r = q("SELECT `gcontact`.*
1097 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1098 where `glink`.`cid` = %d and `glink`.`uid` = %d
1099 order by `gcontact`.`name` asc LIMIT %d, %d ",
1111 function suggestion_query($uid, $start = 0, $limit = 80) {
1116 $network = array(NETWORK_DFRN);
1118 if (get_config('system','diaspora_enabled'))
1119 $network[] = NETWORK_DIASPORA;
1121 if (!get_config('system','ostatus_disabled'))
1122 $network[] = NETWORK_OSTATUS;
1124 $sql_network = implode("', '", $network);
1125 //$sql_network = "'".$sql_network."', ''";
1126 $sql_network = "'".$sql_network."'";
1128 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1129 INNER JOIN glink on glink.gcid = gcontact.id
1130 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1131 and not gcontact.name in ( select name from contact where uid = %d )
1132 and not gcontact.id in ( select gcid from gcign where uid = %d )
1133 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1134 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1135 AND `gcontact`.`network` IN (%s)
1136 group by glink.gcid order by gcontact.updated desc,total desc limit %d, %d ",
1146 if(count($r) && count($r) >= ($limit -1))
1149 $r2 = q("SELECT gcontact.* from gcontact
1150 INNER JOIN glink on glink.gcid = gcontact.id
1151 where glink.uid = 0 and glink.cid = 0 and glink.zcid = 0 and not gcontact.nurl in ( select nurl from contact where uid = %d )
1152 and not gcontact.name in ( select name from contact where uid = %d )
1153 and not gcontact.id in ( select gcid from gcign where uid = %d )
1154 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1155 AND `gcontact`.`network` IN (%s)
1156 order by rand() limit %d, %d ",
1166 foreach ($r2 AS $suggestion)
1167 $list[$suggestion["nurl"]] = $suggestion;
1169 foreach ($r AS $suggestion)
1170 $list[$suggestion["nurl"]] = $suggestion;
1175 function update_suggestions() {
1181 // To-Do: Check if it is really neccessary to poll the own server
1182 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1184 $done[] = $a->get_baseurl() . '/poco';
1186 if(strlen(get_config('system','directory_submit_url'))) {
1187 $x = fetch_url(get_server()."/pubsites");
1189 $j = json_decode($x);
1191 foreach($j->entries as $entry) {
1193 poco_check_server($entry->url);
1195 $url = $entry->url . '/poco';
1196 if(! in_array($url,$done))
1197 poco_load(0,0,0,$entry->url . '/poco');
1203 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1204 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1205 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1209 foreach($r as $rr) {
1210 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1211 if(! in_array($base,$done))
1212 poco_load(0,0,0,$base);
1217 function poco_discover($complete = false) {
1221 $last_update = date("c", time() - (60 * 60 * 6)); // 24
1222 $last_update = date("c", time() - (60 * 60 * 24)); // 24
1224 $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));
1226 foreach ($r AS $server) {
1228 if (!poco_check_server($server["url"], $server["network"]))
1231 // Fetch all users from the other server
1232 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1234 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1236 $retdata = z_fetch_url($url);
1237 if ($retdata["success"]) {
1238 $data = json_decode($retdata["body"]);
1240 poco_discover_server($data, 2);
1242 if (get_config('system','poco_discovery') > 1) {
1244 $timeframe = get_config('system','poco_discovery_since');
1245 if ($timeframe == 0)
1248 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1250 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1251 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1255 $retdata = z_fetch_url($url);
1256 if ($retdata["success"]) {
1257 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1258 $success = poco_discover_server(json_decode($retdata["body"]));
1261 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1262 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1263 poco_discover_server_users($data, $server);
1267 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1268 if (!$complete AND (--$no_of_queries == 0))
1270 } else // If the server hadn't replied correctly, then force a sanity check
1271 poco_check_server($server["url"], $server["network"], true);
1275 function poco_discover_server_users($data, $server) {
1277 if (!isset($data->entry))
1280 foreach ($data->entry AS $entry) {
1282 if (isset($entry->urls)) {
1283 foreach($entry->urls as $url)
1284 if($url->type == 'profile') {
1285 $profile_url = $url->value;
1286 $urlparts = parse_url($profile_url);
1287 $username = end(explode("/", $urlparts["path"]));
1290 if ($username != "") {
1291 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1293 // Fetch all contacts from a given user from the other server
1294 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1296 $retdata = z_fetch_url($url);
1297 if ($retdata["success"])
1298 poco_discover_server(json_decode($retdata["body"]), 3);
1303 function poco_discover_server($data, $default_generation = 0) {
1305 if (!isset($data->entry) OR !count($data->entry))
1310 foreach ($data->entry AS $entry) {
1312 $profile_photo = '';
1316 $updated = '0000-00-00 00:00:00';
1321 $generation = $default_generation;
1323 $name = $entry->displayName;
1325 if(isset($entry->urls)) {
1326 foreach($entry->urls as $url) {
1327 if($url->type == 'profile') {
1328 $profile_url = $url->value;
1331 if($url->type == 'webfinger') {
1332 $connect_url = str_replace('acct:' , '', $url->value);
1338 if(isset($entry->photos)) {
1339 foreach($entry->photos as $photo) {
1340 if($photo->type == 'profile') {
1341 $profile_photo = $photo->value;
1347 if(isset($entry->updated))
1348 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1350 if(isset($entry->network))
1351 $network = $entry->network;
1353 if(isset($entry->currentLocation))
1354 $location = $entry->currentLocation;
1356 if(isset($entry->aboutMe))
1357 $about = html2bbcode($entry->aboutMe);
1359 if(isset($entry->gender))
1360 $gender = $entry->gender;
1362 if(isset($entry->generation) AND ($entry->generation > 0))
1363 $generation = ++$entry->generation;
1365 if(isset($entry->tags))
1366 foreach($entry->tags as $tag)
1367 $keywords = implode(", ", $tag);
1369 if ($generation > 0) {
1372 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1373 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1374 logger("Done for profile ".$profile_url, LOGGER_DEBUG);