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/Photo.php';
24 * @brief This class handles GlobalContact related functions
29 * @brief Search global contact table by nick or name
31 * @param string $search Name or nick
32 * @param string $mode Search mode (e.g. "community")
34 * @return array with search results
36 public static function searchByName($search, $mode = '')
39 // check supported networks
40 if (Config::get('system', 'diaspora_enabled')) {
41 $diaspora = NETWORK_DIASPORA;
43 $diaspora = NETWORK_DFRN;
46 if (!Config::get('system', 'ostatus_disabled')) {
47 $ostatus = NETWORK_OSTATUS;
49 $ostatus = NETWORK_DFRN;
52 // check if we search only communities or every contact
53 if ($mode === "community") {
54 $extra_sql = " AND `community`";
62 "SELECT `contact`.`id` AS `cid`, `gcontact`.`url`, `gcontact`.`name`, `gcontact`.`nick`, `gcontact`.`photo`,
63 `gcontact`.`network`, `gcontact`.`keywords`, `gcontact`.`addr`, `gcontact`.`community`
65 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl`
66 AND `contact`.`uid` = %d AND NOT `contact`.`blocked`
67 AND NOT `contact`.`pending` AND `contact`.`rel` IN ('%s', '%s')
68 WHERE (`contact`.`id` > 0 OR (NOT `gcontact`.`hide` AND `gcontact`.`network` IN ('%s', '%s', '%s') AND
69 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
70 (`gcontact`.`updated` >= `gcontact`.`last_failure`)))) AND
71 (`gcontact`.`addr` LIKE '%s' OR `gcontact`.`name` LIKE '%s' OR `gcontact`.`nick` LIKE '%s') $extra_sql
72 GROUP BY `gcontact`.`nurl`
73 ORDER BY `gcontact`.`nurl` DESC
76 dbesc(CONTACT_IS_SHARING),
77 dbesc(CONTACT_IS_FRIEND),
81 dbesc(escape_tags($search)),
82 dbesc(escape_tags($search)),
83 dbesc(escape_tags($search))
91 * @brief Link the gcontact entry with user, contact and global contact
93 * @param integer $gcid Global contact ID
94 * @param integer $uid User ID
95 * @param integer $cid Contact ID
96 * @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
146 * @return array $gcontact
148 public static function sanitize($gcontact)
150 if ($gcontact['url'] == "") {
151 throw new Exception('URL is empty');
154 $urlparts = parse_url($gcontact['url']);
155 if (!isset($urlparts["scheme"])) {
156 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
159 if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com", "identi.ca", "alpha.app.net"))) {
160 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
163 // Don't store the statusnet connector as network
164 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
165 if ($gcontact['network'] == NETWORK_STATUSNET) {
166 $gcontact['network'] = "";
169 // Assure that there are no parameter fragments in the profile url
170 if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
171 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
174 $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
176 // The global contacts should contain the original picture, not the cached one
177 if (($gcontact['generation'] != 1) && stristr(normalise_link($gcontact['photo']), normalise_link(System::baseUrl()."/photo/"))) {
178 $gcontact['photo'] = "";
181 if (!isset($gcontact['network'])) {
183 "SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
184 dbesc(normalise_link($gcontact['url'])),
185 dbesc(NETWORK_STATUSNET)
187 if (DBM::is_result($r)) {
188 $gcontact['network'] = $r[0]["network"];
191 if (($gcontact['network'] == "") || ($gcontact['network'] == NETWORK_OSTATUS)) {
193 "SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
194 dbesc($gcontact['url']),
195 dbesc(normalise_link($gcontact['url'])),
196 dbesc(NETWORK_STATUSNET)
198 if (DBM::is_result($r)) {
199 $gcontact['network'] = $r[0]["network"];
204 $gcontact['server_url'] = '';
205 $gcontact['network'] = '';
208 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
209 dbesc(normalise_link($gcontact['url']))
212 if (DBM::is_result($x)) {
213 if (!isset($gcontact['network']) && ($x[0]["network"] != NETWORK_STATUSNET)) {
214 $gcontact['network'] = $x[0]["network"];
216 if ($gcontact['updated'] <= NULL_DATE) {
217 $gcontact['updated'] = $x[0]["updated"];
219 if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
220 $gcontact['server_url'] = $x[0]["server_url"];
222 if (!isset($gcontact['addr'])) {
223 $gcontact['addr'] = $x[0]["addr"];
227 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
228 && PortableContact::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
230 $data = Probe::uri($gcontact['url']);
232 if ($data["network"] == NETWORK_PHANTOM) {
233 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
236 $orig_profile = $gcontact['url'];
238 $gcontact["server_url"] = $data["baseurl"];
240 $gcontact = array_merge($gcontact, $data);
242 if ($alternate && ($gcontact['network'] == NETWORK_OSTATUS)) {
243 // Delete the old entry - if it exists
244 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
245 if (DBM::is_result($r)) {
246 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
247 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
252 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
253 throw new Exception('No name and photo for URL '.$gcontact['url']);
256 if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
257 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
260 if (!isset($gcontact['server_url'])) {
261 // We check the server url to be sure that it is a real one
262 $server_url = PortableContact::detectServer($gcontact['url']);
264 // We are now sure that it is a correct URL. So we use it in the future
265 if ($server_url != "") {
266 $gcontact['server_url'] = $server_url;
270 // The server URL doesn't seem to be valid, so we don't store it.
271 if (!PortableContact::checkServer($gcontact['server_url'], $gcontact['network'])) {
272 $gcontact['server_url'] = "";
279 * @param integer $uid id
280 * @param integer $cid id
283 public static function countCommonFriends($uid, $cid)
286 "SELECT count(*) as `total`
287 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
288 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
289 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
290 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
291 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
298 // logger("countCommonFriends: $uid $cid {$r[0]['total']}");
299 if (DBM::is_result($r)) {
300 return $r[0]['total'];
306 * @param integer $uid id
307 * @param integer $zcid zcid
310 public static function countCommonFriendsZcid($uid, $zcid)
313 "SELECT count(*) as `total`
314 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
315 where `glink`.`zcid` = %d
316 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
321 if (DBM::is_result($r)) {
322 return $r[0]['total'];
329 * @param object $uid user
330 * @param object $cid cid
331 * @param integer $start optional, default 0
332 * @param integer $limit optional, default 9999
333 * @param boolean $shuffle optional, default false
336 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
339 $sql_extra = " order by rand() ";
341 $sql_extra = " order by `gcontact`.`name` asc ";
345 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
347 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
348 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
349 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
350 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
351 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
352 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
353 $sql_extra LIMIT %d, %d",
362 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
367 * @param object $uid user
368 * @param object $zcid zcid
369 * @param integer $start optional, default 0
370 * @param integer $limit optional, default 9999
371 * @param boolean $shuffle optional, default false
374 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
377 $sql_extra = " order by rand() ";
379 $sql_extra = " order by `gcontact`.`name` asc ";
384 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
385 where `glink`.`zcid` = %d
386 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
387 $sql_extra limit %d, %d",
394 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
399 * @param object $uid user
400 * @param object $cid cid
403 public static function countAllFriends($uid, $cid)
406 "SELECT count(*) as `total`
407 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
408 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
409 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
414 if (DBM::is_result($r)) {
415 return $r[0]['total'];
422 * @param object $uid user
423 * @param object $cid cid
424 * @param integer $start optional, default 0
425 * @param integer $limit optional, default 80
428 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
431 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
433 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
434 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
435 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
436 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
437 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
445 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
450 * @param object $uid user
451 * @param integer $start optional, default 0
452 * @param integer $limit optional, default 80
455 public static function suggestionQuery($uid, $start = 0, $limit = 80)
462 * Uncommented because the result of the queries are to big to store it in the cache.
463 * We need to decide if we want to change the db column type or if we want to delete it.
465 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
466 //if (!is_null($list)) {
470 $network = array(NETWORK_DFRN);
472 if (Config::get('system', 'diaspora_enabled')) {
473 $network[] = NETWORK_DIASPORA;
476 if (!Config::get('system', 'ostatus_disabled')) {
477 $network[] = NETWORK_OSTATUS;
480 $sql_network = implode("', '", $network);
481 $sql_network = "'".$sql_network."'";
483 /// @todo This query is really slow
484 // By now we cache the data for five minutes
486 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
487 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
488 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
489 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
490 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
491 AND `gcontact`.`updated` >= '%s'
492 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
493 AND `gcontact`.`network` IN (%s)
494 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
505 if (DBM::is_result($r) && count($r) >= ($limit -1)) {
507 * Uncommented because the result of the queries are to big to store it in the cache.
508 * We need to decide if we want to change the db column type or if we want to delete it.
510 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
516 "SELECT gcontact.* FROM gcontact
517 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
518 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
519 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
520 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
521 AND `gcontact`.`updated` >= '%s'
522 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
523 AND `gcontact`.`network` IN (%s)
524 ORDER BY rand() LIMIT %d, %d",
535 foreach ($r2 as $suggestion) {
536 $list[$suggestion["nurl"]] = $suggestion;
539 foreach ($r as $suggestion) {
540 $list[$suggestion["nurl"]] = $suggestion;
543 while (sizeof($list) > ($limit)) {
548 * Uncommented because the result of the queries are to big to store it in the cache.
549 * We need to decide if we want to change the db column type or if we want to delete it.
551 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
558 public static function updateSuggestions()
564 /// @TODO Check if it is really neccessary to poll the own server
565 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
567 $done[] = System::baseUrl() . '/poco';
569 if (strlen(Config::get('system', 'directory'))) {
570 $x = fetch_url(get_server()."/pubsites");
572 $j = json_decode($x);
574 foreach ($j->entries as $entry) {
575 PortableContact::checkServer($entry->url);
577 $url = $entry->url . '/poco';
578 if (! in_array($url, $done)) {
579 PortableContact::loadWorker(0, 0, 0, $entry->url . '/poco');
586 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
588 "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
590 dbesc(NETWORK_DIASPORA)
593 if (DBM::is_result($r)) {
594 foreach ($r as $rr) {
595 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
596 if (! in_array($base, $done)) {
597 PortableContact::loadWorker(0, 0, 0, $base);
604 * @brief Removes unwanted parts from a contact url
606 * @param string $url Contact url
608 * @return string Contact url with the wanted parts
610 public static function cleanContactUrl($url)
612 $parts = parse_url($url);
614 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
618 $new_url = $parts["scheme"]."://".$parts["host"];
620 if (isset($parts["port"])) {
621 $new_url .= ":".$parts["port"];
624 if (isset($parts["path"])) {
625 $new_url .= $parts["path"];
628 if ($new_url != $url) {
629 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), LOGGER_DEBUG);
636 * @brief Replace alternate OStatus user format with the primary one
638 * @param arr $contact contact array (called by reference)
641 public static function fixAlternateContactAddress(&$contact)
643 if (($contact["network"] == NETWORK_OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
644 $data = Probe::uri($contact["url"]);
645 if ($contact["network"] == NETWORK_OSTATUS) {
646 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
647 $contact["url"] = $data["url"];
648 $contact["addr"] = $data["addr"];
649 $contact["alias"] = $data["alias"];
650 $contact["server_url"] = $data["baseurl"];
656 * @brief Fetch the gcontact id, add an entry if not existed
658 * @param arr $contact contact array
660 * @return bool|int Returns false if not found, integer if contact was found
662 public static function getId($contact)
667 if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
668 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
672 if ($contact["network"] == NETWORK_STATUSNET) {
673 $contact["network"] = NETWORK_OSTATUS;
676 // All new contacts are hidden by default
677 if (!isset($contact["hide"])) {
678 $contact["hide"] = true;
681 // Replace alternate OStatus user format with the primary one
682 self::fixAlternateContactAddress($contact);
684 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
685 if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
686 $contact["url"] = self::cleanContactUrl($contact["url"]);
689 dba::lock('gcontact');
691 "SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
692 dbesc(normalise_link($contact["url"]))
695 if (DBM::is_result($r)) {
696 $gcontact_id = $r[0]["id"];
698 // Update every 90 days
699 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
700 $last_failure_str = $r[0]["last_failure"];
701 $last_failure = strtotime($r[0]["last_failure"]);
702 $last_contact_str = $r[0]["last_contact"];
703 $last_contact = strtotime($r[0]["last_contact"]);
704 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
708 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
709 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
710 dbesc($contact["name"]),
711 dbesc($contact["nick"]),
712 dbesc($contact["addr"]),
713 dbesc($contact["network"]),
714 dbesc($contact["url"]),
715 dbesc(normalise_link($contact["url"])),
716 dbesc($contact["photo"]),
717 dbesc(datetime_convert()),
718 dbesc(datetime_convert()),
719 dbesc($contact["location"]),
720 dbesc($contact["about"]),
721 intval($contact["hide"]),
722 intval($contact["generation"])
726 "SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
727 dbesc(normalise_link($contact["url"]))
730 if (DBM::is_result($r)) {
731 $gcontact_id = $r[0]["id"];
733 $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
739 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
740 Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]);
747 * @brief Updates the gcontact table from a given array
749 * @param arr $contact contact array
751 * @return bool|int Returns false if not found, integer if contact was found
753 public static function update($contact)
755 // Check for invalid "contact-type" value
756 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
757 $contact['contact-type'] = 0;
760 /// @todo update contact table as well
762 $gcontact_id = self::getId($contact);
769 "SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
770 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
771 FROM `gcontact` WHERE `id` = %d LIMIT 1",
775 // Get all field names
777 foreach ($r[0] as $field => $data) {
778 $fields[$field] = $data;
781 unset($fields["url"]);
782 unset($fields["updated"]);
783 unset($fields["hide"]);
785 // Bugfix: We had an error in the storing of keywords which lead to the "0"
786 // This value is still transmitted via poco.
787 if ($contact["keywords"] == "0") {
788 unset($contact["keywords"]);
791 if ($r[0]["keywords"] == "0") {
792 $r[0]["keywords"] = "";
795 // assign all unassigned fields from the database entry
796 foreach ($fields as $field => $data) {
797 if (!isset($contact[$field]) || ($contact[$field] == "")) {
798 $contact[$field] = $r[0][$field];
802 if (!isset($contact["hide"])) {
803 $contact["hide"] = $r[0]["hide"];
806 $fields["hide"] = $r[0]["hide"];
808 if ($contact["network"] == NETWORK_STATUSNET) {
809 $contact["network"] = NETWORK_OSTATUS;
812 // Replace alternate OStatus user format with the primary one
813 self::fixAlternateContactAddress($contact);
815 if (!isset($contact["updated"])) {
816 $contact["updated"] = DBM::date();
819 if ($contact["network"] == NETWORK_TWITTER) {
820 $contact["server_url"] = 'http://twitter.com';
823 if ($contact["server_url"] == "") {
824 $data = Probe::uri($contact["url"]);
825 if ($data["network"] != NETWORK_PHANTOM) {
826 $contact["server_url"] = $data['baseurl'];
829 $contact["server_url"] = normalise_link($contact["server_url"]);
832 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
833 $hostname = str_replace("http://", "", $contact["server_url"]);
834 $contact["addr"] = $contact["nick"]."@".$hostname;
837 // Check if any field changed
839 unset($fields["generation"]);
841 if ((($contact["generation"] > 0) && ($contact["generation"] <= $r[0]["generation"])) || ($r[0]["generation"] == 0)) {
842 foreach ($fields as $field => $data) {
843 if ($contact[$field] != $r[0][$field]) {
844 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
849 if ($contact["generation"] < $r[0]["generation"]) {
850 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
856 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
857 $condition = array('`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
858 normalise_link($contact["url"]), $contact["generation"]);
859 $contact["updated"] = DBM::date($contact["updated"]);
861 $updated = array('photo' => $contact['photo'], 'name' => $contact['name'],
862 'nick' => $contact['nick'], 'addr' => $contact['addr'],
863 'network' => $contact['network'], 'birthday' => $contact['birthday'],
864 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
865 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
866 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
867 'notify' => $contact['notify'], 'url' => $contact['url'],
868 'location' => $contact['location'], 'about' => $contact['about'],
869 'generation' => $contact['generation'], 'updated' => $contact['updated'],
870 'server_url' => $contact['server_url'], 'connect' => $contact['connect']);
872 dba::update('gcontact', $updated, $condition, $fields);
874 // Now update the contact entry with the user id "0" as well.
875 // This is used for the shadow copies of public items.
877 "SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
878 dbesc(normalise_link($contact["url"]))
881 if (DBM::is_result($r)) {
882 logger("Update public contact ".$r[0]["id"], LOGGER_DEBUG);
884 update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
886 $fields = array('name', 'nick', 'addr',
887 'network', 'bd', 'gender',
888 'keywords', 'alias', 'contact-type',
889 'url', 'location', 'about');
890 $old_contact = dba::select('contact', $fields, array('id' => $r[0]["id"]), array('limit' => 1));
892 // Update it with the current values
893 $fields = array('name' => $contact['name'], 'nick' => $contact['nick'],
894 'addr' => $contact['addr'], 'network' => $contact['network'],
895 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
896 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
897 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
898 'location' => $contact['location'], 'about' => $contact['about']);
900 dba::update('contact', $fields, array('id' => $r[0]["id"]), $old_contact);
908 * @brief Updates the gcontact entry from probe
910 * @param str $url profile link
913 public static function updateFromProbe($url)
915 $data = Probe::uri($url);
917 if (in_array($data["network"], array(NETWORK_PHANTOM))) {
918 logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
922 $data["server_url"] = $data["baseurl"];
928 * @brief Update the gcontact entry for a given user id
930 * @param int $uid User ID
933 public static function updateForUser($uid)
936 "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
937 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
938 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
939 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
940 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
942 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
943 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
944 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
948 $location = Profile::formatLocation(
949 array("locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"])
952 // The "addr" field was added in 3.4.3 so it can be empty for older users
953 if ($r[0]["addr"] != "") {
954 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", System::baseUrl());
956 $addr = $r[0]["addr"];
959 $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
960 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
961 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
962 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
963 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
964 "nick" => $r[0]["nickname"], "addr" => $addr,
965 "connect" => $addr, "server_url" => System::baseUrl(),
966 "generation" => 1, "network" => NETWORK_DFRN);
968 self::update($gcontact);
972 * @brief Fetches users of given GNU Social server
974 * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
976 * @param str $server Server address
979 public static function fetchGsUsers($server)
981 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
983 $url = $server."/main/statistics";
985 $result = z_fetch_url($url);
986 if (!$result["success"]) {
990 $statistics = json_decode($result["body"]);
992 if (is_object($statistics->config)) {
993 if ($statistics->config->instance_with_ssl) {
994 $server = "https://";
999 $server .= $statistics->config->instance_address;
1001 $hostname = $statistics->config->instance_address;
1003 /// @TODO is_object() above means here no object, still $statistics is being used as object
1004 if ($statistics->instance_with_ssl) {
1005 $server = "https://";
1007 $server = "http://";
1010 $server .= $statistics->instance_address;
1012 $hostname = $statistics->instance_address;
1015 if (is_object($statistics->users)) {
1016 foreach ($statistics->users as $nick => $user) {
1017 $profile_url = $server."/".$user->nickname;
1019 $contact = array("url" => $profile_url,
1020 "name" => $user->fullname,
1021 "addr" => $user->nickname."@".$hostname,
1022 "nick" => $user->nickname,
1023 "about" => $user->bio,
1024 "network" => NETWORK_OSTATUS,
1025 "photo" => System::baseUrl()."/images/person-175.jpg");
1026 self::getId($contact);
1032 * @brief Asking GNU Social server on a regular base for their user data
1035 public static function discoverGsUsers()
1037 $requery_days = intval(Config::get("system", "poco_requery_days"));
1039 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1042 "SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
1043 dbesc(NETWORK_OSTATUS),
1047 if (!DBM::is_result($r)) {
1051 foreach ($r as $server) {
1052 self::fetchGsUsers($server["url"]);
1053 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1060 public static function getRandomUrl()
1063 "SELECT `url` FROM `gcontact` WHERE `network` = '%s'
1064 AND `last_contact` >= `last_failure`
1065 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
1066 ORDER BY rand() LIMIT 1",
1070 if (DBM::is_result($r)) {
1071 return dirname($r[0]['url']);