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 $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 ($data["network"] == NETWORK_FEED)) {
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 $last_failure = datetime_convert();
753 } elseif ($network == NETWORK_DIASPORA)
754 $last_contact = datetime_convert();
758 $serverret = z_fetch_url($server_url);
760 $lines = explode("\n",$serverret["header"]);
762 foreach($lines as $line) {
764 if(stristr($line,'X-Diaspora-Version:')) {
765 $platform = "Diaspora";
766 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
767 $version = trim(str_replace("x-diaspora-version:", "", $version));
768 $network = NETWORK_DIASPORA;
774 // Test for Statusnet
775 // Will also return data for Friendica and GNU Social - but it will be overwritten later
776 // The "not implemented" is a special treatment for really, really old Friendica versions
777 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
778 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
779 $platform = "StatusNet";
780 $version = trim($serverret["body"], '"');
781 $network = NETWORK_OSTATUS;
784 // Test for GNU Social
785 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
786 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
787 $platform = "GNU Social";
788 $version = trim($serverret["body"], '"');
789 $network = NETWORK_OSTATUS;
792 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
793 if ($serverret["success"]) {
794 $data = json_decode($serverret["body"]);
796 if (isset($data->site->server)) {
797 $last_contact = datetime_convert();
799 if (isset($data->site->hubzilla)) {
800 $platform = $data->site->hubzilla->PLATFORM_NAME;
801 $version = $data->site->hubzilla->RED_VERSION;
802 $network = NETWORK_DIASPORA;
804 if (isset($data->site->redmatrix)) {
805 if (isset($data->site->redmatrix->PLATFORM_NAME))
806 $platform = $data->site->redmatrix->PLATFORM_NAME;
807 elseif (isset($data->site->redmatrix->RED_PLATFORM))
808 $platform = $data->site->redmatrix->RED_PLATFORM;
810 $version = $data->site->redmatrix->RED_VERSION;
811 $network = NETWORK_DIASPORA;
813 if (isset($data->site->friendica)) {
814 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
815 $version = $data->site->friendica->FRIENDICA_VERSION;
816 $network = NETWORK_DFRN;
819 $site_name = $data->site->name;
821 $data->site->closed = poco_to_boolean($data->site->closed);
822 $data->site->private = poco_to_boolean($data->site->private);
823 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
825 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
826 $register_policy = REGISTER_APPROVE;
827 elseif (!$data->site->closed AND !$data->site->private)
828 $register_policy = REGISTER_OPEN;
830 $register_policy = REGISTER_CLOSED;
835 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
837 $serverret = z_fetch_url($server_url."/statistics.json");
838 if ($serverret["success"]) {
839 $data = json_decode($serverret["body"]);
841 $version = $data->version;
843 $site_name = $data->name;
845 if (isset($data->network) AND ($platform == ""))
846 $platform = $data->network;
848 if ($platform == "Diaspora")
849 $network = NETWORK_DIASPORA;
851 if ($data->registrations_open)
852 $register_policy = REGISTER_OPEN;
854 $register_policy = REGISTER_CLOSED;
856 if (isset($data->version))
857 $last_contact = datetime_convert();
861 // Check for noscrape
862 // Friendica servers could be detected as OStatus servers
863 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
864 $serverret = z_fetch_url($server_url."/friendica/json");
866 if (!$serverret["success"])
867 $serverret = z_fetch_url($server_url."/friendika/json");
869 if ($serverret["success"]) {
870 $data = json_decode($serverret["body"]);
872 if (isset($data->version)) {
873 $last_contact = datetime_convert();
874 $network = NETWORK_DFRN;
876 $noscrape = $data->no_scrape_url;
877 $version = $data->version;
878 $site_name = $data->site_name;
880 $register_policy_str = $data->register_policy;
881 $platform = $data->platform;
883 switch ($register_policy_str) {
884 case "REGISTER_CLOSED":
885 $register_policy = REGISTER_CLOSED;
887 case "REGISTER_APPROVE":
888 $register_policy = REGISTER_APPROVE;
890 case "REGISTER_OPEN":
891 $register_policy = REGISTER_OPEN;
900 $serverret = z_fetch_url($server_url."/poco");
901 if ($serverret["success"]) {
902 $data = json_decode($serverret["body"]);
903 if (isset($data->totalResults)) {
904 $poco = $server_url."/poco";
905 $last_contact = datetime_convert();
910 // Check again if the server exists
911 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
914 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
915 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
920 intval($register_policy),
925 dbesc($last_contact),
926 dbesc($last_failure),
927 dbesc(normalise_link($server_url))
930 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
931 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
933 dbesc(normalise_link($server_url)),
937 intval($register_policy),
942 dbesc(datetime_convert()),
943 dbesc($last_contact),
944 dbesc($last_failure),
945 dbesc(datetime_convert())
948 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
953 function poco_contact_from_body($body, $created, $cid, $uid) {
954 preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
955 function ($match) use ($created, $cid, $uid){
956 return(sub_poco_from_share($match, $created, $cid, $uid));
960 function sub_poco_from_share($share, $created, $cid, $uid) {
962 preg_match("/profile='(.*?)'/ism", $share[1], $matches);
963 if ($matches[1] != "")
964 $profile = $matches[1];
966 preg_match('/profile="(.*?)"/ism', $share[1], $matches);
967 if ($matches[1] != "")
968 $profile = $matches[1];
973 logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
974 poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
977 function poco_store($item) {
980 if ($item['private'])
983 // Or is it from a network where we don't store the global contacts?
984 if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
987 // Is it a global copy?
988 $store_gcontact = ($item["uid"] == 0);
990 // Is it a comment on a global copy?
991 if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
992 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
993 $store_gcontact = count($q);
996 if (!$store_gcontact)
999 // "3" means: We don't know this contact directly (Maybe a reshared item)
1002 $profile_url = $item["author-link"];
1004 // Is it a user from our server?
1005 $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
1006 dbesc(normalise_link($item["author-link"])));
1008 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
1010 $network = NETWORK_DFRN;
1011 } else { // Is it a contact from a user on our server?
1012 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
1013 AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
1014 dbesc(normalise_link($item["author-link"])),
1015 dbesc(normalise_link($item["author-link"])),
1016 dbesc($item["author-link"]),
1017 dbesc(NETWORK_STATUSNET));
1020 $network = $q[0]["network"];
1021 $profile_url = $q[0]["url"];
1022 logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
1026 if ($generation == 3)
1027 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
1029 poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
1031 // Maybe its a body with a shared item? Then extract a global contact from it.
1032 poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
1035 function count_common_friends($uid,$cid) {
1037 $r = q("SELECT count(*) as `total`
1038 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1039 where `glink`.`cid` = %d and `glink`.`uid` = %d
1040 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1047 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1049 return $r[0]['total'];
1055 function common_friends($uid,$cid,$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`.`cid` = %d and `glink`.`uid` = %d
1065 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d )
1066 $sql_extra limit %d, %d",
1080 function count_common_friends_zcid($uid,$zcid) {
1082 $r = q("SELECT count(*) as `total`
1083 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1084 where `glink`.`zcid` = %d
1085 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1091 return $r[0]['total'];
1096 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1099 $sql_extra = " order by rand() ";
1101 $sql_extra = " order by `gcontact`.`name` asc ";
1103 $r = q("SELECT `gcontact`.*
1104 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1105 where `glink`.`zcid` = %d
1106 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1107 $sql_extra limit %d, %d",
1119 function count_all_friends($uid,$cid) {
1121 $r = q("SELECT count(*) as `total`
1122 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1123 where `glink`.`cid` = %d and `glink`.`uid` = %d ",
1129 return $r[0]['total'];
1135 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1137 $r = q("SELECT `gcontact`.*
1138 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1139 where `glink`.`cid` = %d and `glink`.`uid` = %d
1140 order by `gcontact`.`name` asc LIMIT %d, %d ",
1152 function suggestion_query($uid, $start = 0, $limit = 80) {
1157 $network = array(NETWORK_DFRN);
1159 if (get_config('system','diaspora_enabled'))
1160 $network[] = NETWORK_DIASPORA;
1162 if (!get_config('system','ostatus_disabled'))
1163 $network[] = NETWORK_OSTATUS;
1165 $sql_network = implode("', '", $network);
1166 //$sql_network = "'".$sql_network."', ''";
1167 $sql_network = "'".$sql_network."'";
1169 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1170 INNER JOIN glink on glink.gcid = gcontact.id
1171 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1172 and not gcontact.name in ( select name from contact where uid = %d )
1173 and not gcontact.id in ( select gcid from gcign where uid = %d )
1174 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1175 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1176 AND `gcontact`.`network` IN (%s)
1177 group by glink.gcid order by gcontact.updated desc,total desc limit %d, %d ",
1187 if(count($r) && count($r) >= ($limit -1))
1190 $r2 = q("SELECT gcontact.* from gcontact
1191 INNER JOIN glink on glink.gcid = gcontact.id
1192 where glink.uid = 0 and glink.cid = 0 and glink.zcid = 0 and not gcontact.nurl in ( select nurl from contact where uid = %d )
1193 and not gcontact.name in ( select name from contact where uid = %d )
1194 and not gcontact.id in ( select gcid from gcign where uid = %d )
1195 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1196 AND `gcontact`.`network` IN (%s)
1197 order by rand() limit %d, %d ",
1207 foreach ($r2 AS $suggestion)
1208 $list[$suggestion["nurl"]] = $suggestion;
1210 foreach ($r AS $suggestion)
1211 $list[$suggestion["nurl"]] = $suggestion;
1216 function update_suggestions() {
1222 // To-Do: Check if it is really neccessary to poll the own server
1223 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1225 $done[] = $a->get_baseurl() . '/poco';
1227 if(strlen(get_config('system','directory_submit_url'))) {
1228 $x = fetch_url(get_server()."/pubsites");
1230 $j = json_decode($x);
1232 foreach($j->entries as $entry) {
1234 poco_check_server($entry->url);
1236 $url = $entry->url . '/poco';
1237 if(! in_array($url,$done))
1238 poco_load(0,0,0,$entry->url . '/poco');
1244 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1245 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1246 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1250 foreach($r as $rr) {
1251 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1252 if(! in_array($base,$done))
1253 poco_load(0,0,0,$base);
1258 function poco_discover($complete = false) {
1262 $requery_days = intval(get_config("system", "poco_requery_days"));
1264 if ($requery_days == 0)
1267 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1269 $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));
1271 foreach ($r AS $server) {
1273 if (!poco_check_server($server["url"], $server["network"]))
1276 // Fetch all users from the other server
1277 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1279 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1281 $retdata = z_fetch_url($url);
1282 if ($retdata["success"]) {
1283 $data = json_decode($retdata["body"]);
1285 poco_discover_server($data, 2);
1287 if (get_config('system','poco_discovery') > 1) {
1289 $timeframe = get_config('system','poco_discovery_since');
1290 if ($timeframe == 0)
1293 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1295 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1296 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1300 $retdata = z_fetch_url($url);
1301 if ($retdata["success"]) {
1302 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1303 $success = poco_discover_server(json_decode($retdata["body"]));
1306 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1307 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1308 poco_discover_server_users($data, $server);
1312 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1313 if (!$complete AND (--$no_of_queries == 0))
1315 } else // If the server hadn't replied correctly, then force a sanity check
1316 poco_check_server($server["url"], $server["network"], true);
1320 function poco_discover_server_users($data, $server) {
1322 if (!isset($data->entry))
1325 foreach ($data->entry AS $entry) {
1327 if (isset($entry->urls)) {
1328 foreach($entry->urls as $url)
1329 if($url->type == 'profile') {
1330 $profile_url = $url->value;
1331 $urlparts = parse_url($profile_url);
1332 $username = end(explode("/", $urlparts["path"]));
1335 if ($username != "") {
1336 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1338 // Fetch all contacts from a given user from the other server
1339 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1341 $retdata = z_fetch_url($url);
1342 if ($retdata["success"])
1343 poco_discover_server(json_decode($retdata["body"]), 3);
1348 function poco_discover_server($data, $default_generation = 0) {
1350 if (!isset($data->entry) OR !count($data->entry))
1355 foreach ($data->entry AS $entry) {
1357 $profile_photo = '';
1361 $updated = '0000-00-00 00:00:00';
1366 $generation = $default_generation;
1368 $name = $entry->displayName;
1370 if(isset($entry->urls)) {
1371 foreach($entry->urls as $url) {
1372 if($url->type == 'profile') {
1373 $profile_url = $url->value;
1376 if($url->type == 'webfinger') {
1377 $connect_url = str_replace('acct:' , '', $url->value);
1383 if(isset($entry->photos)) {
1384 foreach($entry->photos as $photo) {
1385 if($photo->type == 'profile') {
1386 $profile_photo = $photo->value;
1392 if(isset($entry->updated))
1393 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1395 if(isset($entry->network))
1396 $network = $entry->network;
1398 if(isset($entry->currentLocation))
1399 $location = $entry->currentLocation;
1401 if(isset($entry->aboutMe))
1402 $about = html2bbcode($entry->aboutMe);
1404 if(isset($entry->gender))
1405 $gender = $entry->gender;
1407 if(isset($entry->generation) AND ($entry->generation > 0))
1408 $generation = ++$entry->generation;
1410 if(isset($entry->tags))
1411 foreach($entry->tags as $tag)
1412 $keywords = implode(", ", $tag);
1414 if ($generation > 0) {
1417 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1418 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1419 logger("Done for profile ".$profile_url, LOGGER_DEBUG);