3 * @file include/socgraph.php
5 * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6 * @todo Fetch profile data from profile page for Redmatrix users
7 * @todo Detect if it is a forum
10 require_once('include/datetime.php');
11 require_once("include/Scrape.php");
12 require_once("include/html2bbcode.php");
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 /// TODO 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"];
228 $addr = $x[0]["addr"];
229 $alias = $x[0]["alias"];
230 $notify = $x[0]["notify"];
232 $created = "0000-00-00 00:00:00";
235 $urlparts = parse_url($profile_url);
236 $nick = end(explode("/", $urlparts["path"]));
242 if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
243 AND poco_reachable($profile_url, $server_url, $network, false)) {
244 $data = probe_url($profile_url);
246 $orig_profile = $profile_url;
248 $network = $data["network"];
249 $name = $data["name"];
250 $nick = $data["nick"];
251 $addr = $data["addr"];
252 $alias = $data["alias"];
253 $notify = $data["notify"];
254 $profile_url = $data["url"];
255 $profile_photo = $data["photo"];
256 $server_url = $data["baseurl"];
258 if ($alternate AND ($network == NETWORK_OSTATUS)) {
259 // Delete the old entry - if it exists
260 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
262 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
263 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
266 // possibly create a new entry
267 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
271 if ($alternate AND ($network == NETWORK_OSTATUS))
274 if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
275 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
277 dbesc(normalise_link($profile_url))
281 if (($name == "") OR ($profile_photo == ""))
284 if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
287 logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
289 poco_check_server($server_url, $network);
291 $gcontact = array("url" => $profile_url,
295 "network" => $network,
296 "photo" => $profile_photo,
298 "location" => $location,
300 "keywords" => $keywords,
301 "server_url" => $server_url,
302 "connect" => $connect_url,
304 "updated" => $updated,
305 "generation" => $generation);
307 $gcid = update_gcontact($gcontact);
312 $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
319 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
324 dbesc(datetime_convert())
327 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
328 dbesc(datetime_convert()),
339 function poco_reachable($profile, $server = "", $network = "", $force = false) {
342 $server = poco_detect_server($profile);
347 return poco_check_server($server, $network, $force);
350 function poco_detect_server($profile) {
352 // Try to detect the server path based upon some known standard paths
355 if ($server_url == "") {
356 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
357 if ($friendica != $profile) {
358 $server_url = $friendica;
359 $network = NETWORK_DFRN;
363 if ($server_url == "") {
364 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
365 if ($diaspora != $profile) {
366 $server_url = $diaspora;
367 $network = NETWORK_DIASPORA;
371 if ($server_url == "") {
372 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
373 if ($red != $profile) {
375 $network = NETWORK_DIASPORA;
382 function poco_alternate_ostatus_url($url) {
383 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
386 function poco_last_updated($profile, $force = false) {
388 $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
389 dbesc(normalise_link($profile)));
391 if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
392 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
393 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
395 if ($gcontacts[0]["server_url"] != "")
396 $server_url = $gcontacts[0]["server_url"];
398 $server_url = poco_detect_server($profile);
400 if ($server_url != "") {
401 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
404 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
405 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
410 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
411 dbesc($server_url), dbesc(normalise_link($profile)));
414 if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
415 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
416 dbesc(normalise_link($server_url)));
419 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
420 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
425 // noscrape is really fast so we don't cache the call.
426 if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
428 // Use noscrape if possible
429 $server = q("SELECT `noscrape` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
432 $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
434 if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
436 $noscrape = json_decode($noscraperet["body"], true);
438 if (($noscrape["fn"] != "") AND ($noscrape["fn"] != $gcontacts[0]["name"]))
439 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
440 dbesc($noscrape["fn"]), dbesc(normalise_link($profile)));
442 if (($noscrape["photo"] != "") AND ($noscrape["photo"] != $gcontacts[0]["photo"]))
443 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
444 dbesc($noscrape["photo"]), dbesc(normalise_link($profile)));
446 if (($noscrape["updated"] != "") AND ($noscrape["updated"] != $gcontacts[0]["updated"]))
447 q("UPDATE `gcontact` SET `updated` = '%s' WHERE `nurl` = '%s'",
448 dbesc($noscrape["updated"]), dbesc(normalise_link($profile)));
450 if (($noscrape["gender"] != "") AND ($noscrape["gender"] != $gcontacts[0]["gender"]))
451 q("UPDATE `gcontact` SET `gender` = '%s' WHERE `nurl` = '%s'",
452 dbesc($noscrape["gender"]), dbesc(normalise_link($profile)));
454 if (($noscrape["pdesc"] != "") AND ($noscrape["pdesc"] != $gcontacts[0]["about"]))
455 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
456 dbesc($noscrape["pdesc"]), dbesc(normalise_link($profile)));
458 if (($noscrape["about"] != "") AND ($noscrape["about"] != $gcontacts[0]["about"]))
459 q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
460 dbesc($noscrape["about"]), dbesc(normalise_link($profile)));
462 if (isset($noscrape["comm"]) AND ($noscrape["comm"] != $gcontacts[0]["community"]))
463 q("UPDATE `gcontact` SET `community` = %d WHERE `nurl` = '%s'",
464 intval($noscrape["comm"]), dbesc(normalise_link($profile)));
466 if (isset($noscrape["tags"]))
467 $keywords = implode(" ", $noscrape["tags"]);
471 if (($keywords != "") AND ($keywords != $gcontacts[0]["keywords"]))
472 q("UPDATE `gcontact` SET `keywords` = '%s' WHERE `nurl` = '%s'",
473 dbesc($keywords), dbesc(normalise_link($profile)));
475 $location = $noscrape["locality"];
477 if ($noscrape["region"] != "") {
481 $location .= $noscrape["region"];
484 if ($noscrape["country-name"] != "") {
488 $location .= $noscrape["country-name"];
491 if (($location != "") AND ($location != $gcontacts[0]["location"]))
492 q("UPDATE `gcontact` SET `location` = '%s' WHERE `nurl` = '%s'",
493 dbesc($location), dbesc(normalise_link($profile)));
495 // If we got data from noscrape then mark the contact as reachable
496 if (is_array($noscrape) AND count($noscrape))
497 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
498 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
500 return $noscrape["updated"];
505 // If we only can poll the feed, then we only do this once a while
506 if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"]))
507 return $gcontacts[0]["updated"];
509 $data = probe_url($profile);
511 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
512 // Then check the other link and delete this one
513 if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
514 (normalise_link($profile) == normalise_link($data["alias"])) AND
515 (normalise_link($profile) != normalise_link($data["url"]))) {
517 // Delete the old entry
518 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
519 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
521 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
522 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
524 poco_last_updated($data["url"], $force);
529 if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
530 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
531 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
535 if (($data["name"] != "") AND ($data["name"] != $gcontacts[0]["name"]))
536 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
537 dbesc($data["name"]), dbesc(normalise_link($profile)));
539 if (($data["nick"] != "") AND ($data["nick"] != $gcontacts[0]["nick"]))
540 q("UPDATE `gcontact` SET `nick` = '%s' WHERE `nurl` = '%s'",
541 dbesc($data["nick"]), dbesc(normalise_link($profile)));
543 if (($data["addr"] != "") AND ($data["addr"] != $gcontacts[0]["connect"]))
544 q("UPDATE `gcontact` SET `connect` = '%s' WHERE `nurl` = '%s'",
545 dbesc($data["addr"]), dbesc(normalise_link($profile)));
547 if (($data["photo"] != "") AND ($data["photo"] != $gcontacts[0]["photo"]))
548 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
549 dbesc($data["photo"]), dbesc(normalise_link($profile)));
551 if (($data["baseurl"] != "") AND ($data["baseurl"] != $gcontacts[0]["server_url"]))
552 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
553 dbesc($data["baseurl"]), dbesc(normalise_link($profile)));
555 $feedret = z_fetch_url($data["poll"]);
557 if (!$feedret["success"]) {
558 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
559 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
563 $doc = new DOMDocument();
564 @$doc->loadXML($feedret["body"]);
566 $xpath = new DomXPath($doc);
567 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
569 $entries = $xpath->query('/atom:feed/atom:entry');
573 foreach ($entries AS $entry) {
574 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
575 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
577 if ($last_updated < $published)
578 $last_updated = $published;
580 if ($last_updated < $updated)
581 $last_updated = $updated;
584 // Maybe there aren't any entries. Then check if it is a valid feed
585 if ($last_updated == "")
586 if ($xpath->query('/atom:feed')->length > 0)
587 $last_updated = "0000-00-00 00:00:00";
589 q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
590 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
592 if (($gcontacts[0]["generation"] == 0))
593 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
594 dbesc(normalise_link($profile)));
596 return($last_updated);
599 function poco_do_update($created, $updated, $last_failure, $last_contact) {
600 $now = strtotime(datetime_convert());
602 if ($updated > $last_contact)
603 $contact_time = strtotime($updated);
605 $contact_time = strtotime($last_contact);
607 $failure_time = strtotime($last_failure);
608 $created_time = strtotime($created);
610 // If there is no "created" time then use the current time
611 if ($created_time <= 0)
612 $created_time = $now;
614 // If the last contact was less than 24 hours then don't update
615 if (($now - $contact_time) < (60 * 60 * 24))
618 // If the last failure was less than 24 hours then don't update
619 if (($now - $failure_time) < (60 * 60 * 24))
622 // If the last contact was less than a week ago and the last failure is older than a week then don't update
623 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
626 // 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
627 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
630 // 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
631 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
637 function poco_to_boolean($val) {
638 if (($val == "true") OR ($val == 1))
640 if (($val == "false") OR ($val == 0))
646 function poco_check_server($server_url, $network = "", $force = false) {
648 // Unify the server address
649 $server_url = trim($server_url, "/");
650 $server_url = str_replace("/index.php", "", $server_url);
652 if ($server_url == "")
655 $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
658 if ($servers[0]["created"] == "0000-00-00 00:00:00")
659 q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
660 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
662 $poco = $servers[0]["poco"];
663 $noscrape = $servers[0]["noscrape"];
666 $network = $servers[0]["network"];
668 $last_contact = $servers[0]["last_contact"];
669 $last_failure = $servers[0]["last_failure"];
670 $version = $servers[0]["version"];
671 $platform = $servers[0]["platform"];
672 $site_name = $servers[0]["site_name"];
673 $info = $servers[0]["info"];
674 $register_policy = $servers[0]["register_policy"];
676 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
677 logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
678 return ($last_contact >= $last_failure);
687 $register_policy = -1;
689 $last_contact = "0000-00-00 00:00:00";
690 $last_failure = "0000-00-00 00:00:00";
692 logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
695 $orig_last_failure = $last_failure;
697 // Check if the page is accessible via SSL.
698 $server_url = str_replace("http://", "https://", $server_url);
699 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
701 // Maybe the page is unencrypted only?
702 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
703 if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
704 $server_url = str_replace("https://", "http://", $server_url);
705 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
707 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
710 if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
711 // Workaround for bad configured servers (known nginx problem)
712 if ($serverret["debug"]["http_code"] != "403") {
713 $last_failure = datetime_convert();
716 } elseif ($network == NETWORK_DIASPORA)
717 $last_contact = datetime_convert();
721 $serverret = z_fetch_url($server_url);
723 if (!$serverret["success"] OR ($serverret["body"] == ""))
726 $lines = explode("\n",$serverret["header"]);
728 foreach($lines as $line) {
730 if(stristr($line,'X-Diaspora-Version:')) {
731 $platform = "Diaspora";
732 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
733 $version = trim(str_replace("x-diaspora-version:", "", $version));
734 $network = NETWORK_DIASPORA;
735 $versionparts = explode("-", $version);
736 $version = $versionparts[0];
743 // Test for Statusnet
744 // Will also return data for Friendica and GNU Social - but it will be overwritten later
745 // The "not implemented" is a special treatment for really, really old Friendica versions
746 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
747 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
748 $platform = "StatusNet";
749 $version = trim($serverret["body"], '"');
750 $network = NETWORK_OSTATUS;
753 // Test for GNU Social
754 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
755 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
756 $platform = "GNU Social";
757 $version = trim($serverret["body"], '"');
758 $network = NETWORK_OSTATUS;
761 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
762 if ($serverret["success"]) {
763 $data = json_decode($serverret["body"]);
765 if (isset($data->site->server)) {
766 $last_contact = datetime_convert();
768 if (isset($data->site->hubzilla)) {
769 $platform = $data->site->hubzilla->PLATFORM_NAME;
770 $version = $data->site->hubzilla->RED_VERSION;
771 $network = NETWORK_DIASPORA;
773 if (isset($data->site->redmatrix)) {
774 if (isset($data->site->redmatrix->PLATFORM_NAME))
775 $platform = $data->site->redmatrix->PLATFORM_NAME;
776 elseif (isset($data->site->redmatrix->RED_PLATFORM))
777 $platform = $data->site->redmatrix->RED_PLATFORM;
779 $version = $data->site->redmatrix->RED_VERSION;
780 $network = NETWORK_DIASPORA;
782 if (isset($data->site->friendica)) {
783 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
784 $version = $data->site->friendica->FRIENDICA_VERSION;
785 $network = NETWORK_DFRN;
788 $site_name = $data->site->name;
790 $data->site->closed = poco_to_boolean($data->site->closed);
791 $data->site->private = poco_to_boolean($data->site->private);
792 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
794 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
795 $register_policy = REGISTER_APPROVE;
796 elseif (!$data->site->closed AND !$data->site->private)
797 $register_policy = REGISTER_OPEN;
799 $register_policy = REGISTER_CLOSED;
804 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
806 $serverret = z_fetch_url($server_url."/statistics.json");
807 if ($serverret["success"]) {
808 $data = json_decode($serverret["body"]);
810 $version = $data->version;
812 $site_name = $data->name;
814 if (isset($data->network) AND ($platform == ""))
815 $platform = $data->network;
817 if ($platform == "Diaspora")
818 $network = NETWORK_DIASPORA;
820 if ($data->registrations_open)
821 $register_policy = REGISTER_OPEN;
823 $register_policy = REGISTER_CLOSED;
825 if (isset($data->version))
826 $last_contact = datetime_convert();
830 // Check for noscrape
831 // Friendica servers could be detected as OStatus servers
832 if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
833 $serverret = z_fetch_url($server_url."/friendica/json");
835 if (!$serverret["success"])
836 $serverret = z_fetch_url($server_url."/friendika/json");
838 if ($serverret["success"]) {
839 $data = json_decode($serverret["body"]);
841 if (isset($data->version)) {
842 $last_contact = datetime_convert();
843 $network = NETWORK_DFRN;
845 $noscrape = $data->no_scrape_url;
846 $version = $data->version;
847 $site_name = $data->site_name;
849 $register_policy_str = $data->register_policy;
850 $platform = $data->platform;
852 switch ($register_policy_str) {
853 case "REGISTER_CLOSED":
854 $register_policy = REGISTER_CLOSED;
856 case "REGISTER_APPROVE":
857 $register_policy = REGISTER_APPROVE;
859 case "REGISTER_OPEN":
860 $register_policy = REGISTER_OPEN;
869 $serverret = z_fetch_url($server_url."/poco");
870 if ($serverret["success"]) {
871 $data = json_decode($serverret["body"]);
872 if (isset($data->totalResults)) {
873 $poco = $server_url."/poco";
874 $last_contact = datetime_convert();
879 // Check again if the server exists
880 $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
883 q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
884 `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
889 intval($register_policy),
894 dbesc($last_contact),
895 dbesc($last_failure),
896 dbesc(normalise_link($server_url))
899 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
900 VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
902 dbesc(normalise_link($server_url)),
906 intval($register_policy),
911 dbesc(datetime_convert()),
912 dbesc($last_contact),
913 dbesc($last_failure),
914 dbesc(datetime_convert())
917 logger("End discovery for server ".$server_url, LOGGER_DEBUG);
922 function poco_contact_from_body($body, $created, $cid, $uid) {
923 preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
924 function ($match) use ($created, $cid, $uid){
925 return(sub_poco_from_share($match, $created, $cid, $uid));
929 function sub_poco_from_share($share, $created, $cid, $uid) {
931 preg_match("/profile='(.*?)'/ism", $share[1], $matches);
932 if ($matches[1] != "")
933 $profile = $matches[1];
935 preg_match('/profile="(.*?)"/ism', $share[1], $matches);
936 if ($matches[1] != "")
937 $profile = $matches[1];
942 logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
943 poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
946 function poco_store($item) {
949 if ($item['private'])
952 // Or is it from a network where we don't store the global contacts?
953 if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
956 // Is it a global copy?
957 $store_gcontact = ($item["uid"] == 0);
959 // Is it a comment on a global copy?
960 if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
961 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
962 $store_gcontact = count($q);
965 if (!$store_gcontact)
968 // "3" means: We don't know this contact directly (Maybe a reshared item)
971 $profile_url = $item["author-link"];
973 // Is it a user from our server?
974 $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
975 dbesc(normalise_link($item["author-link"])));
977 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
979 $network = NETWORK_DFRN;
980 } else { // Is it a contact from a user on our server?
981 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
982 AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
983 dbesc(normalise_link($item["author-link"])),
984 dbesc(normalise_link($item["author-link"])),
985 dbesc($item["author-link"]),
986 dbesc(NETWORK_STATUSNET));
989 $network = $q[0]["network"];
990 $profile_url = $q[0]["url"];
991 logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
995 if ($generation == 3)
996 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
998 poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
1000 // Maybe its a body with a shared item? Then extract a global contact from it.
1001 poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
1004 function count_common_friends($uid,$cid) {
1006 $r = q("SELECT count(*) as `total`
1007 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1008 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1009 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1010 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1017 // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1019 return $r[0]['total'];
1025 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1028 $sql_extra = " order by rand() ";
1030 $sql_extra = " order by `gcontact`.`name` asc ";
1032 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1034 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1035 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1036 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1037 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1038 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1039 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1040 $sql_extra LIMIT %d, %d",
1054 function count_common_friends_zcid($uid,$zcid) {
1056 $r = q("SELECT count(*) as `total`
1057 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1058 where `glink`.`zcid` = %d
1059 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1065 return $r[0]['total'];
1070 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1073 $sql_extra = " order by rand() ";
1075 $sql_extra = " order by `gcontact`.`name` asc ";
1077 $r = q("SELECT `gcontact`.*
1078 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1079 where `glink`.`zcid` = %d
1080 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1081 $sql_extra limit %d, %d",
1093 function count_all_friends($uid,$cid) {
1095 $r = q("SELECT count(*) as `total`
1096 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1097 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1098 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1104 return $r[0]['total'];
1110 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1112 $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1114 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1115 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1116 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1117 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1118 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1131 function suggestion_query($uid, $start = 0, $limit = 80) {
1136 $network = array(NETWORK_DFRN);
1138 if (get_config('system','diaspora_enabled'))
1139 $network[] = NETWORK_DIASPORA;
1141 if (!get_config('system','ostatus_disabled'))
1142 $network[] = NETWORK_OSTATUS;
1144 $sql_network = implode("', '", $network);
1145 //$sql_network = "'".$sql_network."', ''";
1146 $sql_network = "'".$sql_network."'";
1148 $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1149 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1150 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1151 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1152 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1153 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1154 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1155 AND `gcontact`.`network` IN (%s)
1156 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1166 if(count($r) && count($r) >= ($limit -1))
1169 $r2 = q("SELECT gcontact.* FROM gcontact
1170 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1171 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 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 ORDER BY rand() LIMIT %d, %d",
1187 foreach ($r2 AS $suggestion)
1188 $list[$suggestion["nurl"]] = $suggestion;
1190 foreach ($r AS $suggestion)
1191 $list[$suggestion["nurl"]] = $suggestion;
1193 while (sizeof($list) > ($limit))
1199 function update_suggestions() {
1205 /// TODO Check if it is really neccessary to poll the own server
1206 poco_load(0,0,0,$a->get_baseurl() . '/poco');
1208 $done[] = $a->get_baseurl() . '/poco';
1210 if(strlen(get_config('system','directory'))) {
1211 $x = fetch_url(get_server()."/pubsites");
1213 $j = json_decode($x);
1215 foreach($j->entries as $entry) {
1217 poco_check_server($entry->url);
1219 $url = $entry->url . '/poco';
1220 if(! in_array($url,$done))
1221 poco_load(0,0,0,$entry->url . '/poco');
1227 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1228 $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1229 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1233 foreach($r as $rr) {
1234 $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1235 if(! in_array($base,$done))
1236 poco_load(0,0,0,$base);
1241 function poco_discover_federation() {
1242 $last = get_config('poco','last_federation_discovery');
1245 $next = $last + (24 * 60 * 60);
1250 // Discover Friendica, Hubzilla and Diaspora servers
1251 $serverdata = fetch_url("http://the-federation.info/pods.json");
1254 $servers = json_decode($serverdata);
1256 foreach($servers->pods AS $server)
1257 poco_check_server("https://".$server->host);
1260 // Discover GNU Social Servers
1261 if (!get_config('system','ostatus_disabled')) {
1262 $serverdata = "http://gstools.org/api/get_open_instances/";
1264 $result = z_fetch_url($serverdata);
1265 if ($result["success"]) {
1266 $servers = json_decode($result["body"]);
1268 foreach($servers->data AS $server)
1269 poco_check_server($server->instance_address);
1273 set_config('poco','last_federation_discovery', time());
1276 function poco_discover($complete = false) {
1278 // Update the server list
1279 poco_discover_federation();
1283 $requery_days = intval(get_config("system", "poco_requery_days"));
1285 if ($requery_days == 0)
1288 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1290 $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));
1292 foreach ($r AS $server) {
1294 if (!poco_check_server($server["url"], $server["network"])) {
1295 // The server is not reachable? Okay, then we will try it later
1296 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1300 // Fetch all users from the other server
1301 $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1303 logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1305 $retdata = z_fetch_url($url);
1306 if ($retdata["success"]) {
1307 $data = json_decode($retdata["body"]);
1309 poco_discover_server($data, 2);
1311 if (get_config('system','poco_discovery') > 1) {
1313 $timeframe = get_config('system','poco_discovery_since');
1314 if ($timeframe == 0)
1317 $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1319 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1320 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1324 $retdata = z_fetch_url($url);
1325 if ($retdata["success"]) {
1326 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1327 $success = poco_discover_server(json_decode($retdata["body"]));
1330 if (!$success AND (get_config('system','poco_discovery') > 2)) {
1331 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1332 poco_discover_server_users($data, $server);
1336 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1337 if (!$complete AND (--$no_of_queries == 0))
1340 // If the server hadn't replied correctly, then force a sanity check
1341 poco_check_server($server["url"], $server["network"], true);
1343 // If we couldn't reach the server, we will try it some time later
1344 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1349 function poco_discover_server_users($data, $server) {
1351 if (!isset($data->entry))
1354 foreach ($data->entry AS $entry) {
1356 if (isset($entry->urls)) {
1357 foreach($entry->urls as $url)
1358 if($url->type == 'profile') {
1359 $profile_url = $url->value;
1360 $urlparts = parse_url($profile_url);
1361 $username = end(explode("/", $urlparts["path"]));
1364 if ($username != "") {
1365 logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1367 // Fetch all contacts from a given user from the other server
1368 $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1370 $retdata = z_fetch_url($url);
1371 if ($retdata["success"])
1372 poco_discover_server(json_decode($retdata["body"]), 3);
1377 function poco_discover_server($data, $default_generation = 0) {
1379 if (!isset($data->entry) OR !count($data->entry))
1384 foreach ($data->entry AS $entry) {
1386 $profile_photo = '';
1390 $updated = '0000-00-00 00:00:00';
1395 $generation = $default_generation;
1397 $name = $entry->displayName;
1399 if(isset($entry->urls)) {
1400 foreach($entry->urls as $url) {
1401 if($url->type == 'profile') {
1402 $profile_url = $url->value;
1405 if($url->type == 'webfinger') {
1406 $connect_url = str_replace('acct:' , '', $url->value);
1412 if(isset($entry->photos)) {
1413 foreach($entry->photos as $photo) {
1414 if($photo->type == 'profile') {
1415 $profile_photo = $photo->value;
1421 if(isset($entry->updated))
1422 $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1424 if(isset($entry->network))
1425 $network = $entry->network;
1427 if(isset($entry->currentLocation))
1428 $location = $entry->currentLocation;
1430 if(isset($entry->aboutMe))
1431 $about = html2bbcode($entry->aboutMe);
1433 if(isset($entry->gender))
1434 $gender = $entry->gender;
1436 if(isset($entry->generation) AND ($entry->generation > 0))
1437 $generation = ++$entry->generation;
1439 if(isset($entry->tags))
1440 foreach($entry->tags as $tag)
1441 $keywords = implode(", ", $tag);
1443 if ($generation > 0) {
1446 logger("Store profile ".$profile_url, LOGGER_DEBUG);
1447 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1448 logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1455 * @brief Fetch the gcontact id, add an entry if not existed
1457 * @param arr $contact contact array
1458 * @return bool|int Returns false if not found, integer if contact was found
1460 function get_gcontact_id($contact) {
1464 if ($contact["network"] == NETWORK_STATUSNET)
1465 $contact["network"] = NETWORK_OSTATUS;
1467 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1468 dbesc(normalise_link($contact["url"])));
1471 $gcontact_id = $r[0]["id"];
1473 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `generation`)
1474 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
1475 dbesc($contact["name"]),
1476 dbesc($contact["nick"]),
1477 dbesc($contact["addr"]),
1478 dbesc($contact["network"]),
1479 dbesc($contact["url"]),
1480 dbesc(normalise_link($contact["url"])),
1481 dbesc($contact["photo"]),
1482 dbesc(datetime_convert()),
1483 dbesc(datetime_convert()),
1484 dbesc($contact["location"]),
1485 dbesc($contact["about"]),
1486 intval($contact["generation"])
1489 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1490 dbesc(normalise_link($contact["url"])));
1493 $gcontact_id = $r[0]["id"];
1496 if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1497 q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1498 dbesc(normalise_link($contact["url"])),
1499 intval($gcontact_id));
1501 return $gcontact_id;
1505 * @brief Updates the gcontact table from a given array
1507 * @param arr $contact contact array
1508 * @return bool|int Returns false if not found, integer if contact was found
1510 function update_gcontact($contact) {
1512 /// @todo update contact table as well
1514 $gcontact_id = get_gcontact_id($contact);
1519 $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1520 `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1521 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1522 intval($gcontact_id));
1524 // Get all field names
1526 foreach ($r[0] AS $field => $data)
1527 $fields[$field] = $data;
1529 unset($fields["url"]);
1530 unset($fields["updated"]);
1532 // assign all unassigned fields from the database entry
1533 foreach ($fields AS $field => $data)
1534 if (!isset($contact[$field]))
1535 $contact[$field] = $r[0][$field];
1537 if ($contact["network"] == NETWORK_STATUSNET)
1538 $contact["network"] = NETWORK_OSTATUS;
1540 if (!isset($contact["updated"]))
1541 $contact["updated"] = datetime_convert();
1543 // Check if any field changed
1545 unset($fields["generation"]);
1547 foreach ($fields AS $field => $data)
1548 if ($contact[$field] != $r[0][$field])
1551 if ($contact["generation"] < $r[0]["generation"])
1555 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1556 `birthday` = '%s', `gender` = '%s', `keywords` = %d, `hide` = %d, `nsfw` = %d,
1557 `alias` = '%s', `notify` = '%s', `url` = '%s',
1558 `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1559 `server_url` = '%s', `connect` = '%s'
1560 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1561 dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1562 dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1563 dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1564 intval($contact["nsfw"]), dbesc($contact["alias"]), dbesc($contact["notify"]),
1565 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1566 intval($contact["generation"]), dbesc($contact["updated"]),
1567 dbesc($contact["server_url"]), dbesc($contact["connect"]),
1568 dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1571 return $gcontact_id;
1575 * @brief Updates the gcontact entry from probe
1577 * @param str $url profile link
1579 function update_gcontact_from_probe($url) {
1580 $data = probe_url($url);
1582 if ($data["network"] != NETWORK_PHANTOM)
1583 update_gcontact($data);
1587 * @brief Fetches users of given GNU Social server
1589 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1591 * @param str $server Server address
1593 function gs_fetch_users($server) {
1595 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1599 $url = $server."/main/statistics";
1601 $result = z_fetch_url($url);
1602 if (!$result["success"])
1605 $statistics = json_decode($result["body"]);
1607 if (is_object($statistics->config)) {
1608 if ($statistics->config->instance_with_ssl)
1609 $server = "https://";
1611 $server = "http://";
1613 $server .= $statistics->config->instance_address;
1615 $hostname = $statistics->config->instance_address;
1617 if ($statistics->instance_with_ssl)
1618 $server = "https://";
1620 $server = "http://";
1622 $server .= $statistics->instance_address;
1624 $hostname = $statistics->instance_address;
1627 if (is_object($statistics->users))
1628 foreach ($statistics->users AS $nick => $user) {
1629 $profile_url = $server."/".$user->nickname;
1631 $contact = array("url" => $profile_url,
1632 "name" => $user->fullname,
1633 "addr" => $user->nickname."@".$hostname,
1634 "nick" => $user->nickname,
1635 "about" => $user->bio,
1636 "network" => NETWORK_OSTATUS,
1637 "photo" => $a->get_baseurl()."/images/person-175.jpg");
1638 get_gcontact_id($contact);
1643 * @brief Asking GNU Social server on a regular base for their user data
1646 function gs_discover() {
1648 $requery_days = intval(get_config("system", "poco_requery_days"));
1650 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1652 $r = q("SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
1653 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1658 foreach ($r AS $server) {
1659 gs_fetch_users($server["url"]);
1660 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));