3 * @file src/Model/GlobalContact.php
4 * @brief This file includes the GlobalContact class with directory related functions
6 namespace Friendica\Model;
8 use Friendica\Core\Config;
9 use Friendica\Core\System;
10 use Friendica\Database\DBM;
11 use Friendica\Network\Probe;
12 use Friendica\Protocol\PortableContact;
16 require_once 'include/datetime.php';
17 require_once 'include/network.php';
18 require_once 'include/html2bbcode.php';
19 require_once 'include/Contact.php';
20 require_once 'include/Photo.php';
23 * @brief This class handles GlobalContact related functions
28 * @brief Search global contact table by nick or name
30 * @param string $search Name or nick
31 * @param string $mode Search mode (e.g. "community")
33 * @return array with search results
35 public static function searchByName($search, $mode = '')
38 // check supported networks
39 if (Config::get('system', 'diaspora_enabled')) {
40 $diaspora = NETWORK_DIASPORA;
42 $diaspora = NETWORK_DFRN;
45 if (!Config::get('system', 'ostatus_disabled')) {
46 $ostatus = NETWORK_OSTATUS;
48 $ostatus = NETWORK_DFRN;
51 // check if we search only communities or every contact
52 if ($mode === "community") {
53 $extra_sql = " AND `community`";
61 "SELECT `contact`.`id` AS `cid`, `gcontact`.`url`, `gcontact`.`name`, `gcontact`.`nick`, `gcontact`.`photo`,
62 `gcontact`.`network`, `gcontact`.`keywords`, `gcontact`.`addr`, `gcontact`.`community`
64 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl`
65 AND `contact`.`uid` = %d AND NOT `contact`.`blocked`
66 AND NOT `contact`.`pending` AND `contact`.`rel` IN ('%s', '%s')
67 WHERE (`contact`.`id` > 0 OR (NOT `gcontact`.`hide` AND `gcontact`.`network` IN ('%s', '%s', '%s') AND
68 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
69 (`gcontact`.`updated` >= `gcontact`.`last_failure`)))) AND
70 (`gcontact`.`addr` LIKE '%s' OR `gcontact`.`name` LIKE '%s' OR `gcontact`.`nick` LIKE '%s') $extra_sql
71 GROUP BY `gcontact`.`nurl`
72 ORDER BY `gcontact`.`nurl` DESC
75 dbesc(CONTACT_IS_SHARING),
76 dbesc(CONTACT_IS_FRIEND),
80 dbesc(escape_tags($search)),
81 dbesc(escape_tags($search)),
82 dbesc(escape_tags($search))
90 * @brief Link the gcontact entry with user, contact and global contact
92 * @param integer $gcid Global contact ID
93 * @param integer $uid User ID
94 * @param integer $cid Contact ID
95 * @param integer $zcid Global Contact ID
97 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
104 "SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
111 if (!DBM::is_result($r)) {
113 "INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
118 dbesc(datetime_convert())
122 "UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
123 dbesc(datetime_convert()),
133 * @brief Sanitize the given gcontact data
135 * @param array $gcontact array with gcontact data
140 * 1: Profiles on this server
141 * 2: Contacts of profiles on this server
142 * 3: Contacts of contacts of profiles on this server
145 public static function sanitize($gcontact)
147 if ($gcontact['url'] == "") {
148 throw new Exception('URL is empty');
151 $urlparts = parse_url($gcontact['url']);
152 if (!isset($urlparts["scheme"])) {
153 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
156 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com", "identi.ca", "alpha.app.net"))) {
157 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
160 // Don't store the statusnet connector as network
161 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
162 if ($gcontact['network'] == NETWORK_STATUSNET) {
163 $gcontact['network'] = "";
166 // Assure that there are no parameter fragments in the profile url
167 if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
168 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
171 $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
173 // The global contacts should contain the original picture, not the cached one
174 if (($gcontact['generation'] != 1) && stristr(normalise_link($gcontact['photo']), normalise_link(System::baseUrl()."/photo/"))) {
175 $gcontact['photo'] = "";
178 if (!isset($gcontact['network'])) {
180 "SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
181 dbesc(normalise_link($gcontact['url'])),
182 dbesc(NETWORK_STATUSNET)
184 if (DBM::is_result($r)) {
185 $gcontact['network'] = $r[0]["network"];
188 if (($gcontact['network'] == "") || ($gcontact['network'] == NETWORK_OSTATUS)) {
190 "SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
191 dbesc($gcontact['url']),
192 dbesc(normalise_link($gcontact['url'])),
193 dbesc(NETWORK_STATUSNET)
195 if (DBM::is_result($r)) {
196 $gcontact['network'] = $r[0]["network"];
201 $gcontact['server_url'] = '';
202 $gcontact['network'] = '';
205 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
206 dbesc(normalise_link($gcontact['url']))
209 if (DBM::is_result($x)) {
210 if (!isset($gcontact['network']) && ($x[0]["network"] != NETWORK_STATUSNET)) {
211 $gcontact['network'] = $x[0]["network"];
213 if ($gcontact['updated'] <= NULL_DATE) {
214 $gcontact['updated'] = $x[0]["updated"];
216 if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
217 $gcontact['server_url'] = $x[0]["server_url"];
219 if (!isset($gcontact['addr'])) {
220 $gcontact['addr'] = $x[0]["addr"];
224 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
225 && PortableContact::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
227 $data = Probe::uri($gcontact['url']);
229 if ($data["network"] == NETWORK_PHANTOM) {
230 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
233 $orig_profile = $gcontact['url'];
235 $gcontact["server_url"] = $data["baseurl"];
237 $gcontact = array_merge($gcontact, $data);
239 if ($alternate && ($gcontact['network'] == NETWORK_OSTATUS)) {
240 // Delete the old entry - if it exists
241 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
242 if (DBM::is_result($r)) {
243 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
244 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
249 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
250 throw new Exception('No name and photo for URL '.$gcontact['url']);
253 if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
254 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
257 if (!isset($gcontact['server_url'])) {
258 // We check the server url to be sure that it is a real one
259 $server_url = PortableContact::detectServer($gcontact['url']);
261 // We are now sure that it is a correct URL. So we use it in the future
262 if ($server_url != "") {
263 $gcontact['server_url'] = $server_url;
267 // The server URL doesn't seem to be valid, so we don't store it.
268 if (!PortableContact::checkServer($gcontact['server_url'], $gcontact['network'])) {
269 $gcontact['server_url'] = "";
275 public static function countCommonFriends($uid, $cid)
278 "SELECT count(*) as `total`
279 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
280 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
281 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
282 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
283 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
290 // logger("countCommonFriends: $uid $cid {$r[0]['total']}");
291 if (DBM::is_result($r)) {
292 return $r[0]['total'];
297 public static function countCommonFriendsZcid($uid, $zcid)
300 "SELECT count(*) as `total`
301 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
302 where `glink`.`zcid` = %d
303 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
308 if (DBM::is_result($r)) {
309 return $r[0]['total'];
315 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
318 $sql_extra = " order by rand() ";
320 $sql_extra = " order by `gcontact`.`name` asc ";
324 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
326 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
327 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
328 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
329 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
330 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
331 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
332 $sql_extra LIMIT %d, %d",
341 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
345 function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
348 $sql_extra = " order by rand() ";
350 $sql_extra = " order by `gcontact`.`name` asc ";
355 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
356 where `glink`.`zcid` = %d
357 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
358 $sql_extra limit %d, %d",
365 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
369 public static function countAllFriends($uid, $cid)
372 "SELECT count(*) as `total`
373 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
374 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
375 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
380 if (DBM::is_result($r)) {
381 return $r[0]['total'];
388 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
391 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
393 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
394 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
395 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
396 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
397 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
405 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
409 public static function suggestionQuery($uid, $start = 0, $limit = 80)
416 * Uncommented because the result of the queries are to big to store it in the cache.
417 * We need to decide if we want to change the db column type or if we want to delete it.
419 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
420 //if (!is_null($list)) {
424 $network = array(NETWORK_DFRN);
426 if (Config::get('system', 'diaspora_enabled')) {
427 $network[] = NETWORK_DIASPORA;
430 if (!Config::get('system', 'ostatus_disabled')) {
431 $network[] = NETWORK_OSTATUS;
434 $sql_network = implode("', '", $network);
435 $sql_network = "'".$sql_network."'";
437 /// @todo This query is really slow
438 // By now we cache the data for five minutes
440 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
441 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
442 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
443 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
444 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
445 AND `gcontact`.`updated` >= '%s'
446 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
447 AND `gcontact`.`network` IN (%s)
448 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
459 if (DBM::is_result($r) && count($r) >= ($limit -1)) {
461 * Uncommented because the result of the queries are to big to store it in the cache.
462 * We need to decide if we want to change the db column type or if we want to delete it.
464 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
470 "SELECT gcontact.* FROM gcontact
471 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
472 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
473 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
474 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
475 AND `gcontact`.`updated` >= '%s'
476 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
477 AND `gcontact`.`network` IN (%s)
478 ORDER BY rand() LIMIT %d, %d",
489 foreach ($r2 as $suggestion) {
490 $list[$suggestion["nurl"]] = $suggestion;
493 foreach ($r as $suggestion) {
494 $list[$suggestion["nurl"]] = $suggestion;
497 while (sizeof($list) > ($limit)) {
502 * Uncommented because the result of the queries are to big to store it in the cache.
503 * We need to decide if we want to change the db column type or if we want to delete it.
505 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
509 public static function updateSuggestions()
515 /// @TODO Check if it is really neccessary to poll the own server
516 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
518 $done[] = System::baseUrl() . '/poco';
520 if (strlen(Config::get('system', 'directory'))) {
521 $x = fetch_url(get_server()."/pubsites");
523 $j = json_decode($x);
525 foreach ($j->entries as $entry) {
526 PortableContact::checkServer($entry->url);
528 $url = $entry->url . '/poco';
529 if (! in_array($url, $done)) {
530 PortableContact::loadWorker(0, 0, 0, $entry->url . '/poco');
537 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
539 "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
541 dbesc(NETWORK_DIASPORA)
544 if (DBM::is_result($r)) {
545 foreach ($r as $rr) {
546 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
547 if (! in_array($base, $done)) {
548 PortableContact::loadWorker(0, 0, 0, $base);
555 * @brief Removes unwanted parts from a contact url
557 * @param string $url Contact url
559 * @return string Contact url with the wanted parts
561 public static function cleanContactUrl($url)
563 $parts = parse_url($url);
565 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
569 $new_url = $parts["scheme"]."://".$parts["host"];
571 if (isset($parts["port"])) {
572 $new_url .= ":".$parts["port"];
575 if (isset($parts["path"])) {
576 $new_url .= $parts["path"];
579 if ($new_url != $url) {
580 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), LOGGER_DEBUG);
587 * @brief Replace alternate OStatus user format with the primary one
589 * @param arr $contact contact array (called by reference)
591 public static function fixAlternateContactAddress(&$contact)
593 if (($contact["network"] == NETWORK_OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
594 $data = Probe::uri($contact["url"]);
595 if ($contact["network"] == NETWORK_OSTATUS) {
596 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
597 $contact["url"] = $data["url"];
598 $contact["addr"] = $data["addr"];
599 $contact["alias"] = $data["alias"];
600 $contact["server_url"] = $data["baseurl"];
606 * @brief Fetch the gcontact id, add an entry if not existed
608 * @param arr $contact contact array
610 * @return bool|int Returns false if not found, integer if contact was found
612 public static function getId($contact)
617 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
618 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
622 if ($contact["network"] == NETWORK_STATUSNET) {
623 $contact["network"] = NETWORK_OSTATUS;
626 // All new contacts are hidden by default
627 if (!isset($contact["hide"])) {
628 $contact["hide"] = true;
631 // Replace alternate OStatus user format with the primary one
632 self::fixAlternateContactAddress($contact);
634 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
635 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
636 $contact["url"] = self::cleanContactUrl($contact["url"]);
639 dba::lock('gcontact');
641 "SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
642 dbesc(normalise_link($contact["url"]))
645 if (DBM::is_result($r)) {
646 $gcontact_id = $r[0]["id"];
648 // Update every 90 days
649 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
650 $last_failure_str = $r[0]["last_failure"];
651 $last_failure = strtotime($r[0]["last_failure"]);
652 $last_contact_str = $r[0]["last_contact"];
653 $last_contact = strtotime($r[0]["last_contact"]);
654 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
658 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
659 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
660 dbesc($contact["name"]),
661 dbesc($contact["nick"]),
662 dbesc($contact["addr"]),
663 dbesc($contact["network"]),
664 dbesc($contact["url"]),
665 dbesc(normalise_link($contact["url"])),
666 dbesc($contact["photo"]),
667 dbesc(datetime_convert()),
668 dbesc(datetime_convert()),
669 dbesc($contact["location"]),
670 dbesc($contact["about"]),
671 intval($contact["hide"]),
672 intval($contact["generation"])
676 "SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
677 dbesc(normalise_link($contact["url"]))
680 if (DBM::is_result($r)) {
681 $gcontact_id = $r[0]["id"];
683 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
689 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
690 Worker::add(PRIORITY_LOW, 'gprobe', $contact["url"]);
697 * @brief Updates the gcontact table from a given array
699 * @param arr $contact contact array
701 * @return bool|int Returns false if not found, integer if contact was found
703 public static function update($contact)
705 // Check for invalid "contact-type" value
706 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
707 $contact['contact-type'] = 0;
710 /// @todo update contact table as well
712 $gcontact_id = self::getId($contact);
719 "SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
720 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
721 FROM `gcontact` WHERE `id` = %d LIMIT 1",
725 // Get all field names
727 foreach ($r[0] as $field => $data) {
728 $fields[$field] = $data;
731 unset($fields["url"]);
732 unset($fields["updated"]);
733 unset($fields["hide"]);
735 // Bugfix: We had an error in the storing of keywords which lead to the "0"
736 // This value is still transmitted via poco.
737 if ($contact["keywords"] == "0") {
738 unset($contact["keywords"]);
741 if ($r[0]["keywords"] == "0") {
742 $r[0]["keywords"] = "";
745 // assign all unassigned fields from the database entry
746 foreach ($fields as $field => $data) {
747 if (!isset($contact[$field]) || ($contact[$field] == "")) {
748 $contact[$field] = $r[0][$field];
752 if (!isset($contact["hide"])) {
753 $contact["hide"] = $r[0]["hide"];
756 $fields["hide"] = $r[0]["hide"];
758 if ($contact["network"] == NETWORK_STATUSNET) {
759 $contact["network"] = NETWORK_OSTATUS;
762 // Replace alternate OStatus user format with the primary one
763 self::fixAlternateContactAddress($contact);
765 if (!isset($contact["updated"])) {
766 $contact["updated"] = DBM::date();
769 if ($contact["network"] == NETWORK_TWITTER) {
770 $contact["server_url"] = 'http://twitter.com';
773 if ($contact["server_url"] == "") {
774 $data = Probe::uri($contact["url"]);
775 if ($data["network"] != NETWORK_PHANTOM) {
776 $contact["server_url"] = $data['baseurl'];
779 $contact["server_url"] = normalise_link($contact["server_url"]);
782 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
783 $hostname = str_replace("http://", "", $contact["server_url"]);
784 $contact["addr"] = $contact["nick"]."@".$hostname;
787 // Check if any field changed
789 unset($fields["generation"]);
791 if ((($contact["generation"] > 0) && ($contact["generation"] <= $r[0]["generation"])) || ($r[0]["generation"] == 0)) {
792 foreach ($fields as $field => $data) {
793 if ($contact[$field] != $r[0][$field]) {
794 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
799 if ($contact["generation"] < $r[0]["generation"]) {
800 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
806 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
807 $condition = array('`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
808 normalise_link($contact["url"]), $contact["generation"]);
809 $contact["updated"] = DBM::date($contact["updated"]);
811 $updated = array('photo' => $contact['photo'], 'name' => $contact['name'],
812 'nick' => $contact['nick'], 'addr' => $contact['addr'],
813 'network' => $contact['network'], 'birthday' => $contact['birthday'],
814 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
815 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
816 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
817 'notify' => $contact['notify'], 'url' => $contact['url'],
818 'location' => $contact['location'], 'about' => $contact['about'],
819 'generation' => $contact['generation'], 'updated' => $contact['updated'],
820 'server_url' => $contact['server_url'], 'connect' => $contact['connect']);
822 dba::update('gcontact', $updated, $condition, $fields);
824 // Now update the contact entry with the user id "0" as well.
825 // This is used for the shadow copies of public items.
827 "SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
828 dbesc(normalise_link($contact["url"]))
831 if (DBM::is_result($r)) {
832 logger("Update public contact ".$r[0]["id"], LOGGER_DEBUG);
834 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
836 $fields = array('name', 'nick', 'addr',
837 'network', 'bd', 'gender',
838 'keywords', 'alias', 'contact-type',
839 'url', 'location', 'about');
840 $old_contact = dba::select('contact', $fields, array('id' => $r[0]["id"]), array('limit' => 1));
842 // Update it with the current values
843 $fields = array('name' => $contact['name'], 'nick' => $contact['nick'],
844 'addr' => $contact['addr'], 'network' => $contact['network'],
845 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
846 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
847 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
848 'location' => $contact['location'], 'about' => $contact['about']);
850 dba::update('contact', $fields, array('id' => $r[0]["id"]), $old_contact);
858 * @brief Updates the gcontact entry from probe
860 * @param str $url profile link
862 public static function updateFromProbe($url)
864 $data = Probe::uri($url);
866 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
867 logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
871 $data["server_url"] = $data["baseurl"];
877 * @brief Update the gcontact entry for a given user id
879 * @param int $uid User ID
881 public static function updateForUser($uid)
884 "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
885 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
886 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
887 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
888 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
890 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
891 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
892 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
896 $location = formatted_location(
897 array("locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"])
900 // The "addr" field was added in 3.4.3 so it can be empty for older users
901 if ($r[0]["addr"] != "") {
902 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", System::baseUrl());
904 $addr = $r[0]["addr"];
907 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
908 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
909 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
910 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
911 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
912 "nick" => $r[0]["nickname"], "addr" => $addr,
913 "connect" => $addr, "server_url" => System::baseUrl(),
914 "generation" => 1, "network" => NETWORK_DFRN);
916 self::update($gcontact);
920 * @brief Fetches users of given GNU Social server
922 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
924 * @param str $server Server address
926 public static function gsFetchUsers($server)
928 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
930 $url = $server."/main/statistics";
932 $result = z_fetch_url($url);
933 if (!$result["success"]) {
937 $statistics = json_decode($result["body"]);
939 if (is_object($statistics->config)) {
940 if ($statistics->config->instance_with_ssl) {
941 $server = "https://";
946 $server .= $statistics->config->instance_address;
948 $hostname = $statistics->config->instance_address;
950 /// @TODO is_object() above means here no object, still $statistics is being used as object
951 if ($statistics->instance_with_ssl) {
952 $server = "https://";
957 $server .= $statistics->instance_address;
959 $hostname = $statistics->instance_address;
962 if (is_object($statistics->users)) {
963 foreach ($statistics->users as $nick => $user) {
964 $profile_url = $server."/".$user->nickname;
966 $contact = array("url" => $profile_url,
967 "name" => $user->fullname,
968 "addr" => $user->nickname."@".$hostname,
969 "nick" => $user->nickname,
970 "about" => $user->bio,
971 "network" => NETWORK_OSTATUS,
972 "photo" => System::baseUrl()."/images/person-175.jpg");
973 self::getId($contact);
979 * @brief Asking GNU Social server on a regular base for their user data
982 public static function gsDiscover()
984 $requery_days = intval(Config::get("system", "poco_requery_days"));
986 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
989 "SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
990 dbesc(NETWORK_OSTATUS),
994 if (!DBM::is_result($r)) {
998 foreach ($r as $server) {
999 self::gsFetchUsers($server["url"]);
1000 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));