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, false)) {
238 $data = probe_url($profile_url);
240 $orig_profile = $profile_url;
242 $network = $data["network"];
243 $name = $data["name"];
244 $nick = $data["nick"];
245 $profile_url = $data["url"];
246 $profile_photo = $data["photo"];
247 $server_url = $data["baseurl"];
249 if ($alternate AND ($network == NETWORK_OSTATUS)) {
250 // Delete the old entry - if it exists
251 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
253 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
254 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
257 // possibly create a new entry
258 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
262 if ($alternate AND ($network == NETWORK_OSTATUS))
265 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
266 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
268 dbesc(normalise_link($profile_url))
272 if (($name == "") OR ($profile_photo == ""))
275 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
278 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
280 poco_check_server($server_url, $network);
285 if (($location == "") AND ($x[0]['location'] != ""))
286 $location = $x[0]['location'];
288 if (($about == "") AND ($x[0]['about'] != ""))
289 $about = $x[0]['about'];
291 if (($gender == "") AND ($x[0]['gender'] != ""))
292 $gender = $x[0]['gender'];
294 if (($keywords == "") AND ($x[0]['keywords'] != ""))
295 $keywords = $x[0]['keywords'];
297 if (($generation == 0) AND ($x[0]['generation'] > 0))
298 $generation = $x[0]['generation'];
300 if($x[0]['name'] != $name || $x[0]['photo'] != $profile_photo || $x[0]['updated'] < $updated) {
301 q("UPDATE `gcontact` SET `name` = '%s', `network` = '%s', `photo` = '%s', `connect` = '%s', `url` = '%s', `server_url` = '%s',
302 `updated` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s', `generation` = %d
303 WHERE (`generation` >= %d OR `generation` = 0) AND `nurl` = '%s'",
306 dbesc($profile_photo),
317 dbesc(normalise_link($profile_url))
321 q("INSERT INTO `gcontact` (`name`, `nick`, `network`, `url`, `nurl`, `photo`, `connect`, `server_url`, `created`, `updated`, `location`, `about`, `keywords`, `gender`, `generation`)
322 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
327 dbesc(normalise_link($profile_url)),
328 dbesc($profile_photo),
331 dbesc(datetime_convert()),
339 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
340 dbesc(normalise_link($profile_url))
349 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
356 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
361 dbesc(datetime_convert())
364 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
365 dbesc(datetime_convert()),
373 // For unknown reasons there are sometimes duplicates
374 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d AND
375 NOT EXISTS (SELECT `gcid` FROM `glink` WHERE `gcid` = `gcontact`.`id`)",
376 dbesc(normalise_link($profile_url)),
383 function poco_reachable($profile, $server = "", $network = "", $force = false) {
386 $server = poco_detect_server($profile);
391 return poco_check_server($server, $network, $force);
394 function poco_detect_server($profile) {
396 // Try to detect the server path based upon some known standard paths
399 if ($server_url == "") {
400 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
401 if ($friendica != $profile) {
402 $server_url = $friendica;
403 $network = NETWORK_DFRN;
407 if ($server_url == "") {
408 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
409 if ($diaspora != $profile) {
410 $server_url = $diaspora;
411 $network = NETWORK_DIASPORA;
415 if ($server_url == "") {
416 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
417 if ($red != $profile) {
419 $network = NETWORK_DIASPORA;
426 function poco_alternate_ostatus_url($url) {
427 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
430 function poco_last_updated($profile, $force = false) {
432 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
433 dbesc(normalise_link($profile)));
435 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
436 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
437 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
439 if ($gcontacts[0]["server_url"] != "")
440 $server_url = $gcontacts[0]["server_url"];
442 $server_url = poco_detect_server($profile);
444 if ($server_url != "") {
445 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
448 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
449 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
454 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
455 dbesc($server_url), dbesc(normalise_link($profile)));
458 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
459 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
460 dbesc(normalise_link($server_url)));
463 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
464 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
469 // noscrape is really fast so we don't cache the call.
470 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
472 // Use noscrape if possible
473 $server = q("SELECT `noscrape` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
476 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
478 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
480 $noscrape = json_decode($noscraperet["body"], true);
482 if (($noscrape["fn"] != "") AND ($noscrape["fn"] != $gcontacts[0]["name"]))
483 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
484 dbesc($noscrape["fn"]), dbesc(normalise_link($profile)));
486 if (($noscrape["photo"] != "") AND ($noscrape["photo"] != $gcontacts[0]["photo"]))
487 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
488 dbesc($noscrape["photo"]), dbesc(normalise_link($profile)));
490 if (($noscrape["updated"] != "") AND ($noscrape["updated"] != $gcontacts[0]["updated"]))
491 q("UPDATE `gcontact` SET `updated` = '%s' WHERE `nurl` = '%s'",
492 dbesc($noscrape["updated"]), dbesc(normalise_link($profile)));
494 if (($noscrape["gender"] != "") AND ($noscrape["gender"] != $gcontacts[0]["gender"]))
495 q("UPDATE `gcontact` SET `gender` = '%s' WHERE `nurl` = '%s'",
496 dbesc($noscrape["gender"]), dbesc(normalise_link($profile)));
498 if (($noscrape["pdesc"] != "") AND ($noscrape["pdesc"] != $gcontacts[0]["about"]))
499 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
500 dbesc($noscrape["pdesc"]), dbesc(normalise_link($profile)));
502 if (($noscrape["about"] != "") AND ($noscrape["about"] != $gcontacts[0]["about"]))
503 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
504 dbesc($noscrape["about"]), dbesc(normalise_link($profile)));
506 if (isset($noscrape["comm"]) AND ($noscrape["comm"] != $gcontacts[0]["community"]))
507 q("UPDATE `gcontact` SET `community` = %d WHERE `nurl` = '%s'",
508 intval($noscrape["comm"]), dbesc(normalise_link($profile)));
510 if (isset($noscrape["tags"]))
511 $keywords = implode(" ", $noscrape["tags"]);
515 if (($keywords != "") AND ($keywords != $gcontacts[0]["keywords"]))
516 q("UPDATE `gcontact` SET `keywords` = '%s' WHERE `nurl` = '%s'",
517 dbesc($keywords), dbesc(normalise_link($profile)));
519 $location = $noscrape["locality"];
521 if ($noscrape["region"] != "") {
525 $location .= $noscrape["region"];
528 if ($noscrape["country-name"] != "") {
532 $location .= $noscrape["country-name"];
535 if (($location != "") AND ($location != $gcontacts[0]["location"]))
536 q("UPDATE `gcontact` SET `location` = '%s' WHERE `nurl` = '%s'",
537 dbesc($location), dbesc(normalise_link($profile)));
539 // If we got data from noscrape then mark the contact as reachable
540 if (is_array($noscrape) AND count($noscrape))
541 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
542 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
544 return $noscrape["updated"];
549 // If we only can poll the feed, then we only do this once a while
550 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"]))
551 return $gcontacts[0]["updated"];
553 $data = probe_url($profile);
555 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
556 // Then check the other link and delete this one
557 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
558 (normalise_link($profile) == normalise_link($data["alias"])) AND
559 (normalise_link($profile) != normalise_link($data["url"]))) {
561 // Delete the old entry
562 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
563 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
565 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
566 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
568 poco_last_updated($data["url"], $force);
573 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
574 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
575 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
579 if (($data["name"] != "") AND ($data["name"] != $gcontacts[0]["name"]))
580 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
581 dbesc($data["name"]), dbesc(normalise_link($profile)));
583 if (($data["nick"] != "") AND ($data["nick"] != $gcontacts[0]["nick"]))
584 q("UPDATE `gcontact` SET `nick` = '%s' WHERE `nurl` = '%s'",
585 dbesc($data["nick"]), dbesc(normalise_link($profile)));
587 if (($data["addr"] != "") AND ($data["addr"] != $gcontacts[0]["connect"]))
588 q("UPDATE `gcontact` SET `connect` = '%s' WHERE `nurl` = '%s'",
589 dbesc($data["addr"]), dbesc(normalise_link($profile)));
591 if (($data["photo"] != "") AND ($data["photo"] != $gcontacts[0]["photo"]))
592 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
593 dbesc($data["photo"]), dbesc(normalise_link($profile)));
595 if (($data["baseurl"] != "") AND ($data["baseurl"] != $gcontacts[0]["server_url"]))
596 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
597 dbesc($data["baseurl"]), dbesc(normalise_link($profile)));
599 $feedret = z_fetch_url($data["poll"]);
601 if (!$feedret["success"]) {
602 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
603 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
607 $doc = new DOMDocument();
608 @$doc->loadXML($feedret["body"]);
610 $xpath = new DomXPath($doc);
611 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
613 $entries = $xpath->query('/atom:feed/atom:entry');
617 foreach ($entries AS $entry) {
618 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
619 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
621 if ($last_updated < $published)
622 $last_updated = $published;
624 if ($last_updated < $updated)
625 $last_updated = $updated;
628 // Maybe there aren't any entries. Then check if it is a valid feed
629 if ($last_updated == "")
630 if ($xpath->query('/atom:feed')->length > 0)
631 $last_updated = "0000-00-00 00:00:00";
633 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
634 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
636 if (($gcontacts[0]["generation"] == 0))
637 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
638 dbesc(normalise_link($profile)));
640 return($last_updated);
643 function poco_do_update($created, $updated, $last_failure, $last_contact) {
644 $now = strtotime(datetime_convert());
646 if ($updated > $last_contact)
647 $contact_time = strtotime($updated);
649 $contact_time = strtotime($last_contact);
651 $failure_time = strtotime($last_failure);
652 $created_time = strtotime($created);
654 // If there is no "created" time then use the current time
655 if ($created_time <= 0)
656 $created_time = $now;
658 // If the last contact was less than 24 hours then don't update
659 if (($now - $contact_time) < (60 * 60 * 24))
662 // If the last failure was less than 24 hours then don't update
663 if (($now - $failure_time) < (60 * 60 * 24))
666 // If the last contact was less than a week ago and the last failure is older than a week then don't update
667 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
670 // 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
671 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
674 // 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
675 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
681 function poco_to_boolean($val) {
682 if (($val == "true") OR ($val == 1))
684 if (($val == "false") OR ($val == 0))
690 function poco_check_server($server_url, $network = "", $force = false) {
692 if ($server_url == "")
695 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
698 if ($servers[0]["created"] == "0000-00-00 00:00:00")
699 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
700 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
702 $poco = $servers[0]["poco"];
703 $noscrape = $servers[0]["noscrape"];
706 $network = $servers[0]["network"];
708 $last_contact = $servers[0]["last_contact"];
709 $last_failure = $servers[0]["last_failure"];
710 $version = $servers[0]["version"];
711 $platform = $servers[0]["platform"];
712 $site_name = $servers[0]["site_name"];
713 $info = $servers[0]["info"];
714 $register_policy = $servers[0]["register_policy"];
716 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
717 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
718 return ($last_contact >= $last_failure);
727 $register_policy = -1;
729 $last_contact = "0000-00-00 00:00:00";
730 $last_failure = "0000-00-00 00:00:00";
732 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
735 $orig_last_failure = $last_failure;
737 // Check if the page is accessible via SSL.
738 $server_url = str_replace("http://", "https://", $server_url);
739 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
741 // Maybe the page is unencrypted only?
742 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
743 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
744 $server_url = str_replace("https://", "http://", $server_url);
745 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
747 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
750 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
751 // Workaround for bad configured servers (known nginx problem)
752 if ($serverret["debug"]["http_code"] != "403") {
753 $last_failure = datetime_convert();
756 } elseif ($network == NETWORK_DIASPORA)
757 $last_contact = datetime_convert();
761 $serverret = z_fetch_url($server_url);
763 $lines = explode("\n",$serverret["header"]);
765 foreach($lines as $line) {
767 if(stristr($line,'X-Diaspora-Version:')) {
768 $platform = "Diaspora";
769 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
770 $version = trim(str_replace("x-diaspora-version:", "", $version));
771 $network = NETWORK_DIASPORA;
777 // Test for Statusnet
778 // Will also return data for Friendica and GNU Social - but it will be overwritten later
779 // The "not implemented" is a special treatment for really, really old Friendica versions
780 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
781 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
782 $platform = "StatusNet";
783 $version = trim($serverret["body"], '"');
784 $network = NETWORK_OSTATUS;
787 // Test for GNU Social
788 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
789 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
790 $platform = "GNU Social";
791 $version = trim($serverret["body"], '"');
792 $network = NETWORK_OSTATUS;
795 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
796 if ($serverret["success"]) {
797 $data = json_decode($serverret["body"]);
799 if (isset($data->site->server)) {
800 $last_contact = datetime_convert();
802 if (isset($data->site->hubzilla)) {
803 $platform = $data->site->hubzilla->PLATFORM_NAME;
804 $version = $data->site->hubzilla->RED_VERSION;
805 $network = NETWORK_DIASPORA;
807 if (isset($data->site->redmatrix)) {
808 if (isset($data->site->redmatrix->PLATFORM_NAME))
809 $platform = $data->site->redmatrix->PLATFORM_NAME;
810 elseif (isset($data->site->redmatrix->RED_PLATFORM))
811 $platform = $data->site->redmatrix->RED_PLATFORM;
813 $version = $data->site->redmatrix->RED_VERSION;
814 $network = NETWORK_DIASPORA;
816 if (isset($data->site->friendica)) {
817 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
818 $version = $data->site->friendica->FRIENDICA_VERSION;
819 $network = NETWORK_DFRN;
822 $site_name = $data->site->name;
824 $data->site->closed = poco_to_boolean($data->site->closed);
825 $data->site->private = poco_to_boolean($data->site->private);
826 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
828 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
829 $register_policy = REGISTER_APPROVE;
830 elseif (!$data->site->closed AND !$data->site->private)
831 $register_policy = REGISTER_OPEN;
833 $register_policy = REGISTER_CLOSED;
838 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
840 $serverret = z_fetch_url($server_url."/statistics.json");
841 if ($serverret["success"]) {
842 $data = json_decode($serverret["body"]);
844 $version = $data->version;
846 $site_name = $data->name;
848 if (isset($data->network) AND ($platform == ""))
849 $platform = $data->network;
851 if ($platform == "Diaspora")
852 $network = NETWORK_DIASPORA;
854 if ($data->registrations_open)
855 $register_policy = REGISTER_OPEN;
857 $register_policy = REGISTER_CLOSED;
859 if (isset($data->version))
860 $last_contact = datetime_convert();
864 // Check for noscrape
865 // Friendica servers could be detected as OStatus servers
866 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
867 $serverret = z_fetch_url($server_url."/friendica/json");
869 if (!$serverret["success"])
870 $serverret = z_fetch_url($server_url."/friendika/json");
872 if ($serverret["success"]) {
873 $data = json_decode($serverret["body"]);
875 if (isset($data->version)) {
876 $last_contact = datetime_convert();
877 $network = NETWORK_DFRN;
879 $noscrape = $data->no_scrape_url;
880 $version = $data->version;
881 $site_name = $data->site_name;
883 $register_policy_str = $data->register_policy;
884 $platform = $data->platform;
886 switch ($register_policy_str) {
887 case "REGISTER_CLOSED":
888 $register_policy = REGISTER_CLOSED;
890 case "REGISTER_APPROVE":
891 $register_policy = REGISTER_APPROVE;
893 case "REGISTER_OPEN":
894 $register_policy = REGISTER_OPEN;
903 $serverret = z_fetch_url($server_url."/poco");
904 if ($serverret["success"]) {
905 $data = json_decode($serverret["body"]);
906 if (isset($data->totalResults)) {
907 $poco = $server_url."/poco";
908 $last_contact = datetime_convert();
913 // Check again if the server exists
914 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
917 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
918 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
923 intval($register_policy),
928 dbesc($last_contact),
929 dbesc($last_failure),
930 dbesc(normalise_link($server_url))
933 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
934 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
936 dbesc(normalise_link($server_url)),
940 intval($register_policy),
945 dbesc(datetime_convert()),
946 dbesc($last_contact),
947 dbesc($last_failure),
948 dbesc(datetime_convert())
951 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
956 function poco_contact_from_body($body, $created, $cid, $uid) {
957 preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
958 function ($match) use ($created, $cid, $uid){
959 return(sub_poco_from_share($match, $created, $cid, $uid));
963 function sub_poco_from_share($share, $created, $cid, $uid) {
965 preg_match("/profile='(.*?)'/ism", $share[1], $matches);
966 if ($matches[1] != "")
967 $profile = $matches[1];
969 preg_match('/profile="(.*?)"/ism', $share[1], $matches);
970 if ($matches[1] != "")
971 $profile = $matches[1];
976 logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
977 poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
980 function poco_store($item) {
983 if ($item['private'])
986 // Or is it from a network where we don't store the global contacts?
987 if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
990 // Is it a global copy?
991 $store_gcontact = ($item["uid"] == 0);
993 // Is it a comment on a global copy?
994 if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
995 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
996 $store_gcontact = count($q);
999 if (!$store_gcontact)
1002 // "3" means: We don't know this contact directly (Maybe a reshared item)
1005 $profile_url = $item["author-link"];
1007 // Is it a user from our server?
1008 $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
1009 dbesc(normalise_link($item["author-link"])));
1011 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
1013 $network = NETWORK_DFRN;
1014 } else { // Is it a contact from a user on our server?
1015 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
1016 AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
1017 dbesc(normalise_link($item["author-link"])),
1018 dbesc(normalise_link($item["author-link"])),
1019 dbesc($item["author-link"]),
1020 dbesc(NETWORK_STATUSNET));
1023 $network = $q[0]["network"];
1024 $profile_url = $q[0]["url"];
1025 logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
1029 if ($generation == 3)
1030 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
1032 poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
1034 // Maybe its a body with a shared item? Then extract a global contact from it.
1035 poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
1038 function count_common_friends($uid,$cid) {
1040 $r = q("SELECT count(*) as `total`
1041 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1042 where `glink`.`cid` = %d and `glink`.`uid` = %d
1043 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1050 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1052 return $r[0]['total'];
1058 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1061 $sql_extra = " order by rand() ";
1063 $sql_extra = " order by `gcontact`.`name` asc ";
1065 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1067 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1068 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1069 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1070 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1071 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1072 $sql_extra LIMIT %d, %d",
1086 function count_common_friends_zcid($uid,$zcid) {
1088 $r = q("SELECT count(*) as `total`
1089 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1090 where `glink`.`zcid` = %d
1091 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1097 return $r[0]['total'];
1102 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1105 $sql_extra = " order by rand() ";
1107 $sql_extra = " order by `gcontact`.`name` asc ";
1109 $r = q("SELECT `gcontact`.*
1110 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1111 where `glink`.`zcid` = %d
1112 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1113 $sql_extra limit %d, %d",
1125 function count_all_friends($uid,$cid) {
1127 $r = q("SELECT count(*) as `total`
1128 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1129 where `glink`.`cid` = %d and `glink`.`uid` = %d ",
1135 return $r[0]['total'];
1141 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1143 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1145 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1146 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1147 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d
1148 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1161 function suggestion_query($uid, $start = 0, $limit = 80) {
1166 $network = array(NETWORK_DFRN);
1168 if (get_config('system','diaspora_enabled'))
1169 $network[] = NETWORK_DIASPORA;
1171 if (!get_config('system','ostatus_disabled'))
1172 $network[] = NETWORK_OSTATUS;
1174 $sql_network = implode("', '", $network);
1175 //$sql_network = "'".$sql_network."', ''";
1176 $sql_network = "'".$sql_network."'";
1178 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1179 INNER JOIN glink on glink.gcid = gcontact.id
1180 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1181 and not gcontact.name in ( select name from contact where uid = %d )
1182 and not gcontact.id in ( select gcid from gcign where uid = %d )
1183 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1184 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1185 AND `gcontact`.`network` IN (%s)
1186 group by glink.gcid order by gcontact.updated desc,total desc limit %d, %d ",
1196 if(count($r) && count($r) >= ($limit -1))
1199 $r2 = q("SELECT gcontact.* from gcontact
1200 INNER JOIN glink on glink.gcid = gcontact.id
1201 where glink.uid = 0 and glink.cid = 0 and glink.zcid = 0 and not gcontact.nurl in ( select nurl from contact where uid = %d )
1202 and not gcontact.name in ( select name from contact where uid = %d )
1203 and not gcontact.id in ( select gcid from gcign where uid = %d )
1204 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1205 AND `gcontact`.`network` IN (%s)
1206 order by rand() limit %d, %d ",
1216 foreach ($r2 AS $suggestion)
1217 $list[$suggestion["nurl"]] = $suggestion;
1219 foreach ($r AS $suggestion)
1220 $list[$suggestion["nurl"]] = $suggestion;
1225 function update_suggestions() {
1231 // To-Do: Check if it is really neccessary to poll the own server
1232 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1234 $done[] = $a->get_baseurl() . '/poco';
1236 if(strlen(get_config('system','directory'))) {
1237 $x = fetch_url(get_server()."/pubsites");
1239 $j = json_decode($x);
1241 foreach($j->entries as $entry) {
1243 poco_check_server($entry->url);
1245 $url = $entry->url . '/poco';
1246 if(! in_array($url,$done))
1247 poco_load(0,0,0,$entry->url . '/poco');
1253 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1254 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1255 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1259 foreach($r as $rr) {
1260 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1261 if(! in_array($base,$done))
1262 poco_load(0,0,0,$base);
1267 function poco_discover_federation() {
1268 $last = get_config('poco','last_federation_discovery');
1271 $next = $last + (24 * 60 * 60);
1276 $serverdata = fetch_url("http://the-federation.info/pods.json");
1281 $servers = json_decode($serverdata);
1283 foreach($servers->pods AS $server)
1284 poco_check_server("https://".$server->host);
1286 set_config('poco','last_federation_discovery', time());
1290 function poco_discover($complete = false) {
1292 // Update the server list
1293 poco_discover_federation();
1297 $requery_days = intval(get_config("system", "poco_requery_days"));
1299 if ($requery_days == 0)
1302 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1304 $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));
1306 foreach ($r AS $server) {
1308 if (!poco_check_server($server["url"], $server["network"])) {
1309 // The server is not reachable? Okay, then we will try it later
1310 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1314 // Fetch all users from the other server
1315 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1317 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1319 $retdata = z_fetch_url($url);
1320 if ($retdata["success"]) {
1321 $data = json_decode($retdata["body"]);
1323 poco_discover_server($data, 2);
1325 if (get_config('system','poco_discovery') > 1) {
1327 $timeframe = get_config('system','poco_discovery_since');
1328 if ($timeframe == 0)
1331 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1333 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1334 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1338 $retdata = z_fetch_url($url);
1339 if ($retdata["success"]) {
1340 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1341 $success = poco_discover_server(json_decode($retdata["body"]));
1344 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1345 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1346 poco_discover_server_users($data, $server);
1350 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1351 if (!$complete AND (--$no_of_queries == 0))
1354 // If the server hadn't replied correctly, then force a sanity check
1355 poco_check_server($server["url"], $server["network"], true);
1357 // If we couldn't reach the server, we will try it some time later
1358 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1363 function poco_discover_server_users($data, $server) {
1365 if (!isset($data->entry))
1368 foreach ($data->entry AS $entry) {
1370 if (isset($entry->urls)) {
1371 foreach($entry->urls as $url)
1372 if($url->type == 'profile') {
1373 $profile_url = $url->value;
1374 $urlparts = parse_url($profile_url);
1375 $username = end(explode("/", $urlparts["path"]));
1378 if ($username != "") {
1379 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1381 // Fetch all contacts from a given user from the other server
1382 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1384 $retdata = z_fetch_url($url);
1385 if ($retdata["success"])
1386 poco_discover_server(json_decode($retdata["body"]), 3);
1391 function poco_discover_server($data, $default_generation = 0) {
1393 if (!isset($data->entry) OR !count($data->entry))
1398 foreach ($data->entry AS $entry) {
1400 $profile_photo = '';
1404 $updated = '0000-00-00 00:00:00';
1409 $generation = $default_generation;
1411 $name = $entry->displayName;
1413 if(isset($entry->urls)) {
1414 foreach($entry->urls as $url) {
1415 if($url->type == 'profile') {
1416 $profile_url = $url->value;
1419 if($url->type == 'webfinger') {
1420 $connect_url = str_replace('acct:' , '', $url->value);
1426 if(isset($entry->photos)) {
1427 foreach($entry->photos as $photo) {
1428 if($photo->type == 'profile') {
1429 $profile_photo = $photo->value;
1435 if(isset($entry->updated))
1436 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1438 if(isset($entry->network))
1439 $network = $entry->network;
1441 if(isset($entry->currentLocation))
1442 $location = $entry->currentLocation;
1444 if(isset($entry->aboutMe))
1445 $about = html2bbcode($entry->aboutMe);
1447 if(isset($entry->gender))
1448 $gender = $entry->gender;
1450 if(isset($entry->generation) AND ($entry->generation > 0))
1451 $generation = ++$entry->generation;
1453 if(isset($entry->tags))
1454 foreach($entry->tags as $tag)
1455 $keywords = implode(", ", $tag);
1457 if ($generation > 0) {
1460 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1461 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1462 logger("Done for profile ".$profile_url, LOGGER_DEBUG);