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\Core\Worker;
11 use Friendica\Database\DBM;
12 use Friendica\Network\Probe;
13 use Friendica\Object\Profile;
14 use Friendica\Protocol\PortableContact;
18 require_once 'include/datetime.php';
19 require_once 'include/network.php';
20 require_once 'include/html2bbcode.php';
21 require_once 'include/Contact.php';
22 require_once 'include/Photo.php';
25 * @brief This class handles GlobalContact related functions
30 * @brief Search global contact table by nick or name
32 * @param string $search Name or nick
33 * @param string $mode Search mode (e.g. "community")
35 * @return array with search results
37 public static function searchByName($search, $mode = '')
40 // check supported networks
41 if (Config::get('system', 'diaspora_enabled')) {
42 $diaspora = NETWORK_DIASPORA;
44 $diaspora = NETWORK_DFRN;
47 if (!Config::get('system', 'ostatus_disabled')) {
48 $ostatus = NETWORK_OSTATUS;
50 $ostatus = NETWORK_DFRN;
53 // check if we search only communities or every contact
54 if ($mode === "community") {
55 $extra_sql = " AND `community`";
63 "SELECT `contact`.`id` AS `cid`, `gcontact`.`url`, `gcontact`.`name`, `gcontact`.`nick`, `gcontact`.`photo`,
64 `gcontact`.`network`, `gcontact`.`keywords`, `gcontact`.`addr`, `gcontact`.`community`
66 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl`
67 AND `contact`.`uid` = %d AND NOT `contact`.`blocked`
68 AND NOT `contact`.`pending` AND `contact`.`rel` IN ('%s', '%s')
69 WHERE (`contact`.`id` > 0 OR (NOT `gcontact`.`hide` AND `gcontact`.`network` IN ('%s', '%s', '%s') AND
70 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
71 (`gcontact`.`updated` >= `gcontact`.`last_failure`)))) AND
72 (`gcontact`.`addr` LIKE '%s' OR `gcontact`.`name` LIKE '%s' OR `gcontact`.`nick` LIKE '%s') $extra_sql
73 GROUP BY `gcontact`.`nurl`
74 ORDER BY `gcontact`.`nurl` DESC
77 dbesc(CONTACT_IS_SHARING),
78 dbesc(CONTACT_IS_FRIEND),
82 dbesc(escape_tags($search)),
83 dbesc(escape_tags($search)),
84 dbesc(escape_tags($search))
92 * @brief Link the gcontact entry with user, contact and global contact
94 * @param integer $gcid Global contact ID
95 * @param integer $uid User ID
96 * @param integer $cid Contact ID
97 * @param integer $zcid Global Contact ID
99 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
106 "SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
113 if (!DBM::is_result($r)) {
115 "INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
120 dbesc(datetime_convert())
124 "UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
125 dbesc(datetime_convert()),
135 * @brief Sanitize the given gcontact data
137 * @param array $gcontact array with gcontact data
142 * 1: Profiles on this server
143 * 2: Contacts of profiles on this server
144 * 3: Contacts of contacts of profiles on this server
147 public static function sanitize($gcontact)
149 if ($gcontact['url'] == "") {
150 throw new Exception('URL is empty');
153 $urlparts = parse_url($gcontact['url']);
154 if (!isset($urlparts["scheme"])) {
155 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
158 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com", "identi.ca", "alpha.app.net"))) {
159 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
162 // Don't store the statusnet connector as network
163 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
164 if ($gcontact['network'] == NETWORK_STATUSNET) {
165 $gcontact['network'] = "";
168 // Assure that there are no parameter fragments in the profile url
169 if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
170 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
173 $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
175 // The global contacts should contain the original picture, not the cached one
176 if (($gcontact['generation'] != 1) && stristr(normalise_link($gcontact['photo']), normalise_link(System::baseUrl()."/photo/"))) {
177 $gcontact['photo'] = "";
180 if (!isset($gcontact['network'])) {
182 "SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
183 dbesc(normalise_link($gcontact['url'])),
184 dbesc(NETWORK_STATUSNET)
186 if (DBM::is_result($r)) {
187 $gcontact['network'] = $r[0]["network"];
190 if (($gcontact['network'] == "") || ($gcontact['network'] == NETWORK_OSTATUS)) {
192 "SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
193 dbesc($gcontact['url']),
194 dbesc(normalise_link($gcontact['url'])),
195 dbesc(NETWORK_STATUSNET)
197 if (DBM::is_result($r)) {
198 $gcontact['network'] = $r[0]["network"];
203 $gcontact['server_url'] = '';
204 $gcontact['network'] = '';
207 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
208 dbesc(normalise_link($gcontact['url']))
211 if (DBM::is_result($x)) {
212 if (!isset($gcontact['network']) && ($x[0]["network"] != NETWORK_STATUSNET)) {
213 $gcontact['network'] = $x[0]["network"];
215 if ($gcontact['updated'] <= NULL_DATE) {
216 $gcontact['updated'] = $x[0]["updated"];
218 if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
219 $gcontact['server_url'] = $x[0]["server_url"];
221 if (!isset($gcontact['addr'])) {
222 $gcontact['addr'] = $x[0]["addr"];
226 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
227 && PortableContact::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
229 $data = Probe::uri($gcontact['url']);
231 if ($data["network"] == NETWORK_PHANTOM) {
232 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
235 $orig_profile = $gcontact['url'];
237 $gcontact["server_url"] = $data["baseurl"];
239 $gcontact = array_merge($gcontact, $data);
241 if ($alternate && ($gcontact['network'] == NETWORK_OSTATUS)) {
242 // Delete the old entry - if it exists
243 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
244 if (DBM::is_result($r)) {
245 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
246 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
251 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
252 throw new Exception('No name and photo for URL '.$gcontact['url']);
255 if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
256 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
259 if (!isset($gcontact['server_url'])) {
260 // We check the server url to be sure that it is a real one
261 $server_url = PortableContact::detectServer($gcontact['url']);
263 // We are now sure that it is a correct URL. So we use it in the future
264 if ($server_url != "") {
265 $gcontact['server_url'] = $server_url;
269 // The server URL doesn't seem to be valid, so we don't store it.
270 if (!PortableContact::checkServer($gcontact['server_url'], $gcontact['network'])) {
271 $gcontact['server_url'] = "";
277 public static function countCommonFriends($uid, $cid)
280 "SELECT count(*) as `total`
281 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
282 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
283 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
284 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
285 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
292 // logger("countCommonFriends: $uid $cid {$r[0]['total']}");
293 if (DBM::is_result($r)) {
294 return $r[0]['total'];
299 public static function countCommonFriendsZcid($uid, $zcid)
302 "SELECT count(*) as `total`
303 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
304 where `glink`.`zcid` = %d
305 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
310 if (DBM::is_result($r)) {
311 return $r[0]['total'];
317 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
320 $sql_extra = " order by rand() ";
322 $sql_extra = " order by `gcontact`.`name` asc ";
326 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
328 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
329 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
330 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
331 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
332 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
333 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
334 $sql_extra LIMIT %d, %d",
343 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
347 function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
350 $sql_extra = " order by rand() ";
352 $sql_extra = " order by `gcontact`.`name` asc ";
357 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
358 where `glink`.`zcid` = %d
359 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
360 $sql_extra limit %d, %d",
367 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
371 public static function countAllFriends($uid, $cid)
374 "SELECT count(*) as `total`
375 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
376 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
377 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
382 if (DBM::is_result($r)) {
383 return $r[0]['total'];
390 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
393 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
395 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
396 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
397 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
398 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
399 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
407 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
411 public static function suggestionQuery($uid, $start = 0, $limit = 80)
418 * Uncommented because the result of the queries are to big to store it in the cache.
419 * We need to decide if we want to change the db column type or if we want to delete it.
421 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
422 //if (!is_null($list)) {
426 $network = array(NETWORK_DFRN);
428 if (Config::get('system', 'diaspora_enabled')) {
429 $network[] = NETWORK_DIASPORA;
432 if (!Config::get('system', 'ostatus_disabled')) {
433 $network[] = NETWORK_OSTATUS;
436 $sql_network = implode("', '", $network);
437 $sql_network = "'".$sql_network."'";
439 /// @todo This query is really slow
440 // By now we cache the data for five minutes
442 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
443 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
444 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
445 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
446 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
447 AND `gcontact`.`updated` >= '%s'
448 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
449 AND `gcontact`.`network` IN (%s)
450 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
461 if (DBM::is_result($r) && count($r) >= ($limit -1)) {
463 * Uncommented because the result of the queries are to big to store it in the cache.
464 * We need to decide if we want to change the db column type or if we want to delete it.
466 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
472 "SELECT gcontact.* FROM gcontact
473 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
474 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
475 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
476 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
477 AND `gcontact`.`updated` >= '%s'
478 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
479 AND `gcontact`.`network` IN (%s)
480 ORDER BY rand() LIMIT %d, %d",
491 foreach ($r2 as $suggestion) {
492 $list[$suggestion["nurl"]] = $suggestion;
495 foreach ($r as $suggestion) {
496 $list[$suggestion["nurl"]] = $suggestion;
499 while (sizeof($list) > ($limit)) {
504 * Uncommented because the result of the queries are to big to store it in the cache.
505 * We need to decide if we want to change the db column type or if we want to delete it.
507 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
511 public static function updateSuggestions()
517 /// @TODO Check if it is really neccessary to poll the own server
518 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
520 $done[] = System::baseUrl() . '/poco';
522 if (strlen(Config::get('system', 'directory'))) {
523 $x = fetch_url(get_server()."/pubsites");
525 $j = json_decode($x);
527 foreach ($j->entries as $entry) {
528 PortableContact::checkServer($entry->url);
530 $url = $entry->url . '/poco';
531 if (! in_array($url, $done)) {
532 PortableContact::loadWorker(0, 0, 0, $entry->url . '/poco');
539 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
541 "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
543 dbesc(NETWORK_DIASPORA)
546 if (DBM::is_result($r)) {
547 foreach ($r as $rr) {
548 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
549 if (! in_array($base, $done)) {
550 PortableContact::loadWorker(0, 0, 0, $base);
557 * @brief Removes unwanted parts from a contact url
559 * @param string $url Contact url
561 * @return string Contact url with the wanted parts
563 public static function cleanContactUrl($url)
565 $parts = parse_url($url);
567 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
571 $new_url = $parts["scheme"]."://".$parts["host"];
573 if (isset($parts["port"])) {
574 $new_url .= ":".$parts["port"];
577 if (isset($parts["path"])) {
578 $new_url .= $parts["path"];
581 if ($new_url != $url) {
582 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), LOGGER_DEBUG);
589 * @brief Replace alternate OStatus user format with the primary one
591 * @param arr $contact contact array (called by reference)
593 public static function fixAlternateContactAddress(&$contact)
595 if (($contact["network"] == NETWORK_OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
596 $data = Probe::uri($contact["url"]);
597 if ($contact["network"] == NETWORK_OSTATUS) {
598 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
599 $contact["url"] = $data["url"];
600 $contact["addr"] = $data["addr"];
601 $contact["alias"] = $data["alias"];
602 $contact["server_url"] = $data["baseurl"];
608 * @brief Fetch the gcontact id, add an entry if not existed
610 * @param arr $contact contact array
612 * @return bool|int Returns false if not found, integer if contact was found
614 public static function getId($contact)
619 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
620 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
624 if ($contact["network"] == NETWORK_STATUSNET) {
625 $contact["network"] = NETWORK_OSTATUS;
628 // All new contacts are hidden by default
629 if (!isset($contact["hide"])) {
630 $contact["hide"] = true;
633 // Replace alternate OStatus user format with the primary one
634 self::fixAlternateContactAddress($contact);
636 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
637 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
638 $contact["url"] = self::cleanContactUrl($contact["url"]);
641 dba::lock('gcontact');
643 "SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
644 dbesc(normalise_link($contact["url"]))
647 if (DBM::is_result($r)) {
648 $gcontact_id = $r[0]["id"];
650 // Update every 90 days
651 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
652 $last_failure_str = $r[0]["last_failure"];
653 $last_failure = strtotime($r[0]["last_failure"]);
654 $last_contact_str = $r[0]["last_contact"];
655 $last_contact = strtotime($r[0]["last_contact"]);
656 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
660 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
661 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
662 dbesc($contact["name"]),
663 dbesc($contact["nick"]),
664 dbesc($contact["addr"]),
665 dbesc($contact["network"]),
666 dbesc($contact["url"]),
667 dbesc(normalise_link($contact["url"])),
668 dbesc($contact["photo"]),
669 dbesc(datetime_convert()),
670 dbesc(datetime_convert()),
671 dbesc($contact["location"]),
672 dbesc($contact["about"]),
673 intval($contact["hide"]),
674 intval($contact["generation"])
678 "SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
679 dbesc(normalise_link($contact["url"]))
682 if (DBM::is_result($r)) {
683 $gcontact_id = $r[0]["id"];
685 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
691 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
692 Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]);
699 * @brief Updates the gcontact table from a given array
701 * @param arr $contact contact array
703 * @return bool|int Returns false if not found, integer if contact was found
705 public static function update($contact)
707 // Check for invalid "contact-type" value
708 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
709 $contact['contact-type'] = 0;
712 /// @todo update contact table as well
714 $gcontact_id = self::getId($contact);
721 "SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
722 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
723 FROM `gcontact` WHERE `id` = %d LIMIT 1",
727 // Get all field names
729 foreach ($r[0] as $field => $data) {
730 $fields[$field] = $data;
733 unset($fields["url"]);
734 unset($fields["updated"]);
735 unset($fields["hide"]);
737 // Bugfix: We had an error in the storing of keywords which lead to the "0"
738 // This value is still transmitted via poco.
739 if ($contact["keywords"] == "0") {
740 unset($contact["keywords"]);
743 if ($r[0]["keywords"] == "0") {
744 $r[0]["keywords"] = "";
747 // assign all unassigned fields from the database entry
748 foreach ($fields as $field => $data) {
749 if (!isset($contact[$field]) || ($contact[$field] == "")) {
750 $contact[$field] = $r[0][$field];
754 if (!isset($contact["hide"])) {
755 $contact["hide"] = $r[0]["hide"];
758 $fields["hide"] = $r[0]["hide"];
760 if ($contact["network"] == NETWORK_STATUSNET) {
761 $contact["network"] = NETWORK_OSTATUS;
764 // Replace alternate OStatus user format with the primary one
765 self::fixAlternateContactAddress($contact);
767 if (!isset($contact["updated"])) {
768 $contact["updated"] = DBM::date();
771 if ($contact["network"] == NETWORK_TWITTER) {
772 $contact["server_url"] = 'http://twitter.com';
775 if ($contact["server_url"] == "") {
776 $data = Probe::uri($contact["url"]);
777 if ($data["network"] != NETWORK_PHANTOM) {
778 $contact["server_url"] = $data['baseurl'];
781 $contact["server_url"] = normalise_link($contact["server_url"]);
784 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
785 $hostname = str_replace("http://", "", $contact["server_url"]);
786 $contact["addr"] = $contact["nick"]."@".$hostname;
789 // Check if any field changed
791 unset($fields["generation"]);
793 if ((($contact["generation"] > 0) && ($contact["generation"] <= $r[0]["generation"])) || ($r[0]["generation"] == 0)) {
794 foreach ($fields as $field => $data) {
795 if ($contact[$field] != $r[0][$field]) {
796 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
801 if ($contact["generation"] < $r[0]["generation"]) {
802 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
808 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
809 $condition = array('`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
810 normalise_link($contact["url"]), $contact["generation"]);
811 $contact["updated"] = DBM::date($contact["updated"]);
813 $updated = array('photo' => $contact['photo'], 'name' => $contact['name'],
814 'nick' => $contact['nick'], 'addr' => $contact['addr'],
815 'network' => $contact['network'], 'birthday' => $contact['birthday'],
816 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
817 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
818 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
819 'notify' => $contact['notify'], 'url' => $contact['url'],
820 'location' => $contact['location'], 'about' => $contact['about'],
821 'generation' => $contact['generation'], 'updated' => $contact['updated'],
822 'server_url' => $contact['server_url'], 'connect' => $contact['connect']);
824 dba::update('gcontact', $updated, $condition, $fields);
826 // Now update the contact entry with the user id "0" as well.
827 // This is used for the shadow copies of public items.
829 "SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
830 dbesc(normalise_link($contact["url"]))
833 if (DBM::is_result($r)) {
834 logger("Update public contact ".$r[0]["id"], LOGGER_DEBUG);
836 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
838 $fields = array('name', 'nick', 'addr',
839 'network', 'bd', 'gender',
840 'keywords', 'alias', 'contact-type',
841 'url', 'location', 'about');
842 $old_contact = dba::select('contact', $fields, array('id' => $r[0]["id"]), array('limit' => 1));
844 // Update it with the current values
845 $fields = array('name' => $contact['name'], 'nick' => $contact['nick'],
846 'addr' => $contact['addr'], 'network' => $contact['network'],
847 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
848 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
849 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
850 'location' => $contact['location'], 'about' => $contact['about']);
852 dba::update('contact', $fields, array('id' => $r[0]["id"]), $old_contact);
860 * @brief Updates the gcontact entry from probe
862 * @param str $url profile link
864 public static function updateFromProbe($url)
866 $data = Probe::uri($url);
868 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
869 logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
873 $data["server_url"] = $data["baseurl"];
879 * @brief Update the gcontact entry for a given user id
881 * @param int $uid User ID
883 public static function updateForUser($uid)
886 "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
887 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
888 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
889 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
890 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
892 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
893 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
894 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
898 $location = formatted_location(
899 array("locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"])
902 // The "addr" field was added in 3.4.3 so it can be empty for older users
903 if ($r[0]["addr"] != "") {
904 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", System::baseUrl());
906 $addr = $r[0]["addr"];
909 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
910 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
911 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
912 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
913 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
914 "nick" => $r[0]["nickname"], "addr" => $addr,
915 "connect" => $addr, "server_url" => System::baseUrl(),
916 "generation" => 1, "network" => NETWORK_DFRN);
918 self::update($gcontact);
922 * @brief Fetches users of given GNU Social server
924 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
926 * @param str $server Server address
928 public static function fetchGsUsers($server)
930 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
932 $url = $server."/main/statistics";
934 $result = z_fetch_url($url);
935 if (!$result["success"]) {
939 $statistics = json_decode($result["body"]);
941 if (is_object($statistics->config)) {
942 if ($statistics->config->instance_with_ssl) {
943 $server = "https://";
948 $server .= $statistics->config->instance_address;
950 $hostname = $statistics->config->instance_address;
952 /// @TODO is_object() above means here no object, still $statistics is being used as object
953 if ($statistics->instance_with_ssl) {
954 $server = "https://";
959 $server .= $statistics->instance_address;
961 $hostname = $statistics->instance_address;
964 if (is_object($statistics->users)) {
965 foreach ($statistics->users as $nick => $user) {
966 $profile_url = $server."/".$user->nickname;
968 $contact = array("url" => $profile_url,
969 "name" => $user->fullname,
970 "addr" => $user->nickname."@".$hostname,
971 "nick" => $user->nickname,
972 "about" => $user->bio,
973 "network" => NETWORK_OSTATUS,
974 "photo" => System::baseUrl()."/images/person-175.jpg");
975 self::getId($contact);
981 * @brief Asking GNU Social server on a regular base for their user data
984 public static function discoverGsUsers()
986 $requery_days = intval(Config::get("system", "poco_requery_days"));
988 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
991 "SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
992 dbesc(NETWORK_OSTATUS),
996 if (!DBM::is_result($r)) {
1000 foreach ($r as $server) {
1001 self::fetchGsUsers($server["url"]);
1002 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));