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"];
229 $created = "0000-00-00 00:00:00";
232 $urlparts = parse_url($profile_url);
233 $nick = end(explode("/", $urlparts["path"]));
236 if ((($network == "") OR ($name == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
237 AND poco_reachable($profile_url, $server_url, $network, true)) {
238 $data = probe_url($profile_url);
240 $network = $data["network"];
241 $name = $data["name"];
242 $nick = $data["nick"];
243 $profile_url = $data["url"];
244 $profile_photo = $data["photo"];
245 $server_url = $data["baseurl"];
247 if ($alternate AND ($network == NETWORK_OSTATUS))
248 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
251 if ($alternate AND ($network == NETWORK_OSTATUS))
254 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
255 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
257 dbesc(normalise_link($profile_url))
261 if (($name == "") OR ($profile_photo == ""))
264 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
267 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
269 poco_check_server($server_url, $network);
274 if (($location == "") AND ($x[0]['location'] != ""))
275 $location = $x[0]['location'];
277 if (($about == "") AND ($x[0]['about'] != ""))
278 $about = $x[0]['about'];
280 if (($gender == "") AND ($x[0]['gender'] != ""))
281 $gender = $x[0]['gender'];
283 if (($keywords == "") AND ($x[0]['keywords'] != ""))
284 $keywords = $x[0]['keywords'];
286 if (($generation == 0) AND ($x[0]['generation'] > 0))
287 $generation = $x[0]['generation'];
289 if($x[0]['name'] != $name || $x[0]['photo'] != $profile_photo || $x[0]['updated'] < $updated) {
290 q("UPDATE `gcontact` SET `name` = '%s', `network` = '%s', `photo` = '%s', `connect` = '%s', `url` = '%s', `server_url` = '%s',
291 `updated` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s', `generation` = %d
292 WHERE (`generation` >= %d OR `generation` = 0) AND `nurl` = '%s'",
295 dbesc($profile_photo),
306 dbesc(normalise_link($profile_url))
310 q("INSERT INTO `gcontact` (`name`, `nick`, `network`, `url`, `nurl`, `photo`, `connect`, `server_url`, `created`, `updated`, `location`, `about`, `keywords`, `gender`, `generation`)
311 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
316 dbesc(normalise_link($profile_url)),
317 dbesc($profile_photo),
320 dbesc(datetime_convert()),
328 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
329 dbesc(normalise_link($profile_url))
338 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
345 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
350 dbesc(datetime_convert())
353 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
354 dbesc(datetime_convert()),
362 // For unknown reasons there are sometimes duplicates
363 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d AND
364 NOT EXISTS (SELECT `gcid` FROM `glink` WHERE `gcid` = `gcontact`.`id`)",
365 dbesc(normalise_link($profile_url)),
372 function poco_reachable($profile, $server = "", $network = "", $force = false) {
375 $server = poco_detect_server($profile);
380 return poco_check_server($server, $network, $force);
383 function poco_detect_server($profile) {
385 // Try to detect the server path based upon some known standard paths
388 if ($server_url == "") {
389 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
390 if ($friendica != $profile) {
391 $server_url = $friendica;
392 $network = NETWORK_DFRN;
396 if ($server_url == "") {
397 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
398 if ($diaspora != $profile) {
399 $server_url = $diaspora;
400 $network = NETWORK_DIASPORA;
404 if ($server_url == "") {
405 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
406 if ($red != $profile) {
408 $network = NETWORK_DIASPORA;
415 function poco_alternate_ostatus_url($url) {
416 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
419 function poco_last_updated($profile, $force = false) {
421 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
422 dbesc(normalise_link($profile)));
424 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
425 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
426 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
428 if ($gcontacts[0]["server_url"] != "")
429 $server_url = $gcontacts[0]["server_url"];
431 $server_url = poco_detect_server($profile);
433 if ($server_url != "") {
434 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
437 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
438 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
443 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
444 dbesc($server_url), dbesc(normalise_link($profile)));
447 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
448 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
449 dbesc(normalise_link($server_url)));
452 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
453 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
458 // noscrape is really fast so we don't cache the call.
459 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
461 // Use noscrape if possible
462 $server = q("SELECT `noscrape` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
465 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
467 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
469 $noscrape = json_decode($noscraperet["body"], true);
471 if (($noscrape["fn"] != "") AND ($noscrape["fn"] != $gcontacts[0]["name"]))
472 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
473 dbesc($noscrape["fn"]), dbesc(normalise_link($profile)));
475 if (($noscrape["photo"] != "") AND ($noscrape["photo"] != $gcontacts[0]["photo"]))
476 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
477 dbesc($noscrape["photo"]), dbesc(normalise_link($profile)));
479 if (($noscrape["updated"] != "") AND ($noscrape["updated"] != $gcontacts[0]["updated"]))
480 q("UPDATE `gcontact` SET `updated` = '%s' WHERE `nurl` = '%s'",
481 dbesc($noscrape["updated"]), dbesc(normalise_link($profile)));
483 if (($noscrape["gender"] != "") AND ($noscrape["gender"] != $gcontacts[0]["gender"]))
484 q("UPDATE `gcontact` SET `gender` = '%s' WHERE `nurl` = '%s'",
485 dbesc($noscrape["gender"]), dbesc(normalise_link($profile)));
487 if (($noscrape["pdesc"] != "") AND ($noscrape["pdesc"] != $gcontacts[0]["about"]))
488 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
489 dbesc($noscrape["pdesc"]), dbesc(normalise_link($profile)));
491 if (($noscrape["about"] != "") AND ($noscrape["about"] != $gcontacts[0]["about"]))
492 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
493 dbesc($noscrape["about"]), dbesc(normalise_link($profile)));
495 if (isset($noscrape["comm"]) AND ($noscrape["comm"] != $gcontacts[0]["community"]))
496 q("UPDATE `gcontact` SET `community` = %d WHERE `nurl` = '%s'",
497 intval($noscrape["comm"]), dbesc(normalise_link($profile)));
499 if (isset($noscrape["tags"]))
500 $keywords = implode(" ", $noscrape["tags"]);
504 if (($keywords != "") AND ($keywords != $gcontacts[0]["keywords"]))
505 q("UPDATE `gcontact` SET `keywords` = '%s' WHERE `nurl` = '%s'",
506 dbesc($keywords), dbesc(normalise_link($profile)));
508 $location = $noscrape["locality"];
510 if ($noscrape["region"] != "") {
514 $location .= $noscrape["region"];
517 if ($noscrape["country-name"] != "") {
521 $location .= $noscrape["country-name"];
524 if (($location != "") AND ($location != $gcontacts[0]["location"]))
525 q("UPDATE `gcontact` SET `location` = '%s' WHERE `nurl` = '%s'",
526 dbesc($location), dbesc(normalise_link($profile)));
528 // If we got data from noscrape then mark the contact as reachable
529 if (is_array($noscrape) AND count($noscrape))
530 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
531 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
533 return $noscrape["updated"];
538 // If we only can poll the feed, then we only do this once a while
539 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"]))
540 return $gcontacts[0]["updated"];
542 $data = probe_url($profile);
544 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
545 // Then check the other link and delete this one
546 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
547 (normalise_link($profile) == normalise_link($data["alias"])) AND
548 (normalise_link($profile) != normalise_link($data["url"]))) {
550 // Delete the old entry
551 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
552 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
554 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
555 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
557 poco_last_updated($data["url"], $force);
562 if (($data["poll"] == "") OR ($data["network"] == NETWORK_FEED)) {
563 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
564 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
568 if (($data["name"] != "") AND ($data["name"] != $gcontacts[0]["name"]))
569 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
570 dbesc($data["name"]), dbesc(normalise_link($profile)));
572 if (($data["nick"] != "") AND ($data["nick"] != $gcontacts[0]["nick"]))
573 q("UPDATE `gcontact` SET `nick` = '%s' WHERE `nurl` = '%s'",
574 dbesc($data["nick"]), dbesc(normalise_link($profile)));
576 if (($data["addr"] != "") AND ($data["addr"] != $gcontacts[0]["connect"]))
577 q("UPDATE `gcontact` SET `connect` = '%s' WHERE `nurl` = '%s'",
578 dbesc($data["addr"]), dbesc(normalise_link($profile)));
580 if (($data["photo"] != "") AND ($data["photo"] != $gcontacts[0]["photo"]))
581 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
582 dbesc($data["photo"]), dbesc(normalise_link($profile)));
584 if (($data["baseurl"] != "") AND ($data["baseurl"] != $gcontacts[0]["server_url"]))
585 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
586 dbesc($data["baseurl"]), dbesc(normalise_link($profile)));
588 $feedret = z_fetch_url($data["poll"]);
590 if (!$feedret["success"]) {
591 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
592 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
596 $doc = new DOMDocument();
597 @$doc->loadXML($feedret["body"]);
599 $xpath = new DomXPath($doc);
600 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
602 $entries = $xpath->query('/atom:feed/atom:entry');
606 foreach ($entries AS $entry) {
607 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
608 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
610 if ($last_updated < $published)
611 $last_updated = $published;
613 if ($last_updated < $updated)
614 $last_updated = $updated;
617 // Maybe there aren't any entries. Then check if it is a valid feed
618 if ($last_updated == "")
619 if ($xpath->query('/atom:feed')->length > 0)
620 $last_updated = "0000-00-00 00:00:00";
622 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
623 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
625 if (($gcontacts[0]["generation"] == 0))
626 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
627 dbesc(normalise_link($profile)));
629 return($last_updated);
632 function poco_do_update($created, $updated, $last_failure, $last_contact) {
633 $now = strtotime(datetime_convert());
635 if ($updated > $last_contact)
636 $contact_time = strtotime($updated);
638 $contact_time = strtotime($last_contact);
640 $failure_time = strtotime($last_failure);
641 $created_time = strtotime($created);
643 // If there is no "created" time then use the current time
644 if ($created_time <= 0)
645 $created_time = $now;
647 // If the last contact was less than 24 hours then don't update
648 if (($now - $contact_time) < (60 * 60 * 24))
651 // If the last failure was less than 24 hours then don't update
652 if (($now - $failure_time) < (60 * 60 * 24))
655 // If the last contact was less than a week ago and the last failure is older than a week then don't update
656 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
659 // 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
660 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
663 // 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
664 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
670 function poco_to_boolean($val) {
671 if (($val == "true") OR ($val == 1))
673 if (($val == "false") OR ($val == 0))
679 function poco_check_server($server_url, $network = "", $force = false) {
681 if ($server_url == "")
684 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
687 if ($servers[0]["created"] == "0000-00-00 00:00:00")
688 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
689 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
691 $poco = $servers[0]["poco"];
692 $noscrape = $servers[0]["noscrape"];
695 $network = $servers[0]["network"];
697 $last_contact = $servers[0]["last_contact"];
698 $last_failure = $servers[0]["last_failure"];
699 $version = $servers[0]["version"];
700 $platform = $servers[0]["platform"];
701 $site_name = $servers[0]["site_name"];
702 $info = $servers[0]["info"];
703 $register_policy = $servers[0]["register_policy"];
705 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
706 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
707 return ($last_contact >= $last_failure);
716 $register_policy = -1;
718 $last_contact = "0000-00-00 00:00:00";
719 $last_failure = "0000-00-00 00:00:00";
721 logger("Server ".$server_url." is unknown. Start discovery.", LOGGER_DEBUG);
724 $orig_last_failure = $last_failure;
726 // Check if the page is accessible via SSL.
727 $server_url = str_replace("http://", "https://", $server_url);
728 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
730 // Maybe the page is unencrypted only?
731 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
732 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
733 $server_url = str_replace("https://", "http://", $server_url);
734 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
736 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
739 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
740 $last_failure = datetime_convert();
742 } elseif ($network == NETWORK_DIASPORA)
743 $last_contact = datetime_convert();
747 $serverret = z_fetch_url($server_url);
749 $lines = explode("\n",$serverret["header"]);
751 foreach($lines as $line) {
753 if(stristr($line,'X-Diaspora-Version:')) {
754 $platform = "Diaspora";
755 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
756 $version = trim(str_replace("x-diaspora-version:", "", $version));
757 $network = NETWORK_DIASPORA;
763 // Test for Statusnet
764 // Will also return data for Friendica and GNU Social - but it will be overwritten later
765 // The "not implemented" is a special treatment for really, really old Friendica versions
766 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
767 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
768 $platform = "StatusNet";
769 $version = trim($serverret["body"], '"');
770 $network = NETWORK_OSTATUS;
773 // Test for GNU Social
774 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
775 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
776 $platform = "GNU Social";
777 $version = trim($serverret["body"], '"');
778 $network = NETWORK_OSTATUS;
781 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
782 if ($serverret["success"]) {
783 $data = json_decode($serverret["body"]);
785 if (isset($data->site->server)) {
786 $last_contact = datetime_convert();
788 if (isset($data->site->hubzilla)) {
789 $platform = $data->site->hubzilla->PLATFORM_NAME;
790 $version = $data->site->hubzilla->RED_VERSION;
791 $network = NETWORK_DIASPORA;
793 if (isset($data->site->redmatrix)) {
794 if (isset($data->site->redmatrix->PLATFORM_NAME))
795 $platform = $data->site->redmatrix->PLATFORM_NAME;
796 elseif (isset($data->site->redmatrix->RED_PLATFORM))
797 $platform = $data->site->redmatrix->RED_PLATFORM;
799 $version = $data->site->redmatrix->RED_VERSION;
800 $network = NETWORK_DIASPORA;
802 if (isset($data->site->friendica)) {
803 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
804 $version = $data->site->friendica->FRIENDICA_VERSION;
805 $network = NETWORK_DFRN;
808 $site_name = $data->site->name;
810 $data->site->closed = poco_to_boolean($data->site->closed);
811 $data->site->private = poco_to_boolean($data->site->private);
812 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
814 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
815 $register_policy = REGISTER_APPROVE;
816 elseif (!$data->site->closed AND !$data->site->private)
817 $register_policy = REGISTER_OPEN;
819 $register_policy = REGISTER_CLOSED;
824 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
826 $serverret = z_fetch_url($server_url."/statistics.json");
827 if ($serverret["success"]) {
828 $data = json_decode($serverret["body"]);
830 $version = $data->version;
832 $site_name = $data->name;
834 if (isset($data->network) AND ($platform == ""))
835 $platform = $data->network;
837 if ($platform == "Diaspora")
838 $network = NETWORK_DIASPORA;
840 if ($data->registrations_open)
841 $register_policy = REGISTER_OPEN;
843 $register_policy = REGISTER_CLOSED;
845 if (isset($data->version))
846 $last_contact = datetime_convert();
850 // Check for noscrape
851 // Friendica servers could be detected as OStatus servers
852 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
853 $serverret = z_fetch_url($server_url."/friendica/json");
855 if (!$serverret["success"])
856 $serverret = z_fetch_url($server_url."/friendika/json");
858 if ($serverret["success"]) {
859 $data = json_decode($serverret["body"]);
861 if (isset($data->version)) {
862 $last_contact = datetime_convert();
863 $network = NETWORK_DFRN;
865 $noscrape = $data->no_scrape_url;
866 $version = $data->version;
867 $site_name = $data->site_name;
869 $register_policy_str = $data->register_policy;
870 $platform = $data->platform;
872 switch ($register_policy_str) {
873 case "REGISTER_CLOSED":
874 $register_policy = REGISTER_CLOSED;
876 case "REGISTER_APPROVE":
877 $register_policy = REGISTER_APPROVE;
879 case "REGISTER_OPEN":
880 $register_policy = REGISTER_OPEN;
889 $serverret = z_fetch_url($server_url."/poco");
890 if ($serverret["success"]) {
891 $data = json_decode($serverret["body"]);
892 if (isset($data->totalResults)) {
893 $poco = $server_url."/poco";
894 $last_contact = datetime_convert();
899 // Check again if the server exists
900 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
903 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
904 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
909 intval($register_policy),
914 dbesc($last_contact),
915 dbesc($last_failure),
916 dbesc(normalise_link($server_url))
919 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
920 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
922 dbesc(normalise_link($server_url)),
926 intval($register_policy),
931 dbesc(datetime_convert()),
932 dbesc($last_contact),
933 dbesc($last_failure),
934 dbesc(datetime_convert())
937 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
942 function poco_contact_from_body($body, $created, $cid, $uid) {
943 preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
944 function ($match) use ($created, $cid, $uid){
945 return(sub_poco_from_share($match, $created, $cid, $uid));
949 function sub_poco_from_share($share, $created, $cid, $uid) {
951 preg_match("/profile='(.*?)'/ism", $share[1], $matches);
952 if ($matches[1] != "")
953 $profile = $matches[1];
955 preg_match('/profile="(.*?)"/ism', $share[1], $matches);
956 if ($matches[1] != "")
957 $profile = $matches[1];
962 logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
963 poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
966 function poco_store($item) {
969 if ($item['private'])
972 // Or is it from a network where we don't store the global contacts?
973 if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
976 // Is it a global copy?
977 $store_gcontact = ($item["uid"] == 0);
979 // Is it a comment on a global copy?
980 if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
981 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
982 $store_gcontact = count($q);
985 if (!$store_gcontact)
988 // "3" means: We don't know this contact directly (Maybe a reshared item)
991 $profile_url = $item["author-link"];
993 // Is it a user from our server?
994 $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
995 dbesc(normalise_link($item["author-link"])));
997 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
999 $network = NETWORK_DFRN;
1000 } else { // Is it a contact from a user on our server?
1001 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
1002 AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
1003 dbesc(normalise_link($item["author-link"])),
1004 dbesc(normalise_link($item["author-link"])),
1005 dbesc($item["author-link"]),
1006 dbesc(NETWORK_STATUSNET));
1009 $network = $q[0]["network"];
1010 $profile_url = $q[0]["url"];
1011 logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
1015 if ($generation == 3)
1016 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
1018 poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
1020 // Maybe its a body with a shared item? Then extract a global contact from it.
1021 poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
1024 function count_common_friends($uid,$cid) {
1026 $r = q("SELECT count(*) as `total`
1027 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1028 where `glink`.`cid` = %d and `glink`.`uid` = %d
1029 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1036 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1038 return $r[0]['total'];
1044 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1047 $sql_extra = " order by rand() ";
1049 $sql_extra = " order by `gcontact`.`name` asc ";
1051 $r = q("SELECT `gcontact`.*
1052 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1053 where `glink`.`cid` = %d and `glink`.`uid` = %d
1054 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d )
1055 $sql_extra limit %d, %d",
1069 function count_common_friends_zcid($uid,$zcid) {
1071 $r = q("SELECT count(*) as `total`
1072 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1073 where `glink`.`zcid` = %d
1074 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1080 return $r[0]['total'];
1085 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1088 $sql_extra = " order by rand() ";
1090 $sql_extra = " order by `gcontact`.`name` asc ";
1092 $r = q("SELECT `gcontact`.*
1093 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1094 where `glink`.`zcid` = %d
1095 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1096 $sql_extra limit %d, %d",
1108 function count_all_friends($uid,$cid) {
1110 $r = q("SELECT count(*) as `total`
1111 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1112 where `glink`.`cid` = %d and `glink`.`uid` = %d ",
1118 return $r[0]['total'];
1124 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1126 $r = q("SELECT `gcontact`.*
1127 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1128 where `glink`.`cid` = %d and `glink`.`uid` = %d
1129 order by `gcontact`.`name` asc LIMIT %d, %d ",
1141 function suggestion_query($uid, $start = 0, $limit = 80) {
1146 $network = array(NETWORK_DFRN);
1148 if (get_config('system','diaspora_enabled'))
1149 $network[] = NETWORK_DIASPORA;
1151 if (!get_config('system','ostatus_disabled'))
1152 $network[] = NETWORK_OSTATUS;
1154 $sql_network = implode("', '", $network);
1155 //$sql_network = "'".$sql_network."', ''";
1156 $sql_network = "'".$sql_network."'";
1158 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1159 INNER JOIN glink on glink.gcid = gcontact.id
1160 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1161 and not gcontact.name in ( select name from contact where uid = %d )
1162 and not gcontact.id in ( select gcid from gcign where uid = %d )
1163 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1164 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1165 AND `gcontact`.`network` IN (%s)
1166 group by glink.gcid order by gcontact.updated desc,total desc limit %d, %d ",
1176 if(count($r) && count($r) >= ($limit -1))
1179 $r2 = q("SELECT gcontact.* from gcontact
1180 INNER JOIN glink on glink.gcid = gcontact.id
1181 where glink.uid = 0 and glink.cid = 0 and glink.zcid = 0 and not gcontact.nurl in ( select nurl from contact where uid = %d )
1182 and not gcontact.name in ( select name from contact where uid = %d )
1183 and not gcontact.id in ( select gcid from gcign where uid = %d )
1184 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1185 AND `gcontact`.`network` IN (%s)
1186 order by rand() limit %d, %d ",
1196 foreach ($r2 AS $suggestion)
1197 $list[$suggestion["nurl"]] = $suggestion;
1199 foreach ($r AS $suggestion)
1200 $list[$suggestion["nurl"]] = $suggestion;
1205 function update_suggestions() {
1211 // To-Do: Check if it is really neccessary to poll the own server
1212 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1214 $done[] = $a->get_baseurl() . '/poco';
1216 if(strlen(get_config('system','directory_submit_url'))) {
1217 $x = fetch_url(get_server()."/pubsites");
1219 $j = json_decode($x);
1221 foreach($j->entries as $entry) {
1223 poco_check_server($entry->url);
1225 $url = $entry->url . '/poco';
1226 if(! in_array($url,$done))
1227 poco_load(0,0,0,$entry->url . '/poco');
1233 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1234 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1235 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1239 foreach($r as $rr) {
1240 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1241 if(! in_array($base,$done))
1242 poco_load(0,0,0,$base);
1247 function poco_discover($complete = false) {
1251 $last_update = date("c", time() - (60 * 60 * 6)); // 24
1252 $last_update = date("c", time() - (60 * 60 * 24)); // 24
1254 $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));
1256 foreach ($r AS $server) {
1258 if (!poco_check_server($server["url"], $server["network"]))
1261 // Fetch all users from the other server
1262 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1264 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1266 $retdata = z_fetch_url($url);
1267 if ($retdata["success"]) {
1268 $data = json_decode($retdata["body"]);
1270 poco_discover_server($data, 2);
1272 if (get_config('system','poco_discovery') > 1) {
1274 $timeframe = get_config('system','poco_discovery_since');
1275 if ($timeframe == 0)
1278 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1280 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1281 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1285 $retdata = z_fetch_url($url);
1286 if ($retdata["success"]) {
1287 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1288 $success = poco_discover_server(json_decode($retdata["body"]));
1291 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1292 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1293 poco_discover_server_users($data, $server);
1297 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1298 if (!$complete AND (--$no_of_queries == 0))
1300 } else // If the server hadn't replied correctly, then force a sanity check
1301 poco_check_server($server["url"], $server["network"], true);
1305 function poco_discover_server_users($data, $server) {
1307 if (!isset($data->entry))
1310 foreach ($data->entry AS $entry) {
1312 if (isset($entry->urls)) {
1313 foreach($entry->urls as $url)
1314 if($url->type == 'profile') {
1315 $profile_url = $url->value;
1316 $urlparts = parse_url($profile_url);
1317 $username = end(explode("/", $urlparts["path"]));
1320 if ($username != "") {
1321 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1323 // Fetch all contacts from a given user from the other server
1324 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1326 $retdata = z_fetch_url($url);
1327 if ($retdata["success"])
1328 poco_discover_server(json_decode($retdata["body"]), 3);
1333 function poco_discover_server($data, $default_generation = 0) {
1335 if (!isset($data->entry) OR !count($data->entry))
1340 foreach ($data->entry AS $entry) {
1342 $profile_photo = '';
1346 $updated = '0000-00-00 00:00:00';
1351 $generation = $default_generation;
1353 $name = $entry->displayName;
1355 if(isset($entry->urls)) {
1356 foreach($entry->urls as $url) {
1357 if($url->type == 'profile') {
1358 $profile_url = $url->value;
1361 if($url->type == 'webfinger') {
1362 $connect_url = str_replace('acct:' , '', $url->value);
1368 if(isset($entry->photos)) {
1369 foreach($entry->photos as $photo) {
1370 if($photo->type == 'profile') {
1371 $profile_photo = $photo->value;
1377 if(isset($entry->updated))
1378 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1380 if(isset($entry->network))
1381 $network = $entry->network;
1383 if(isset($entry->currentLocation))
1384 $location = $entry->currentLocation;
1386 if(isset($entry->aboutMe))
1387 $about = html2bbcode($entry->aboutMe);
1389 if(isset($entry->gender))
1390 $gender = $entry->gender;
1392 if(isset($entry->generation) AND ($entry->generation > 0))
1393 $generation = ++$entry->generation;
1395 if(isset($entry->tags))
1396 foreach($entry->tags as $tag)
1397 $keywords = implode(", ", $tag);
1399 if ($generation > 0) {
1402 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1403 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1404 logger("Done for profile ".$profile_url, LOGGER_DEBUG);