4 * @file src/Model/GlobalContact.php
5 * @brief This file includes the GlobalContact class with directory related functions
7 namespace Friendica\Model;
9 use Friendica\Core\Config;
10 use Friendica\Core\System;
11 use Friendica\Core\Worker;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Profile;
15 use Friendica\Network\Probe;
16 use Friendica\Protocol\PortableContact;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Network;
22 require_once 'include/dba.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 = '')
43 // check supported networks
44 if (Config::get('system', 'diaspora_enabled')) {
45 $diaspora = NETWORK_DIASPORA;
47 $diaspora = NETWORK_DFRN;
50 if (!Config::get('system', 'ostatus_disabled')) {
51 $ostatus = NETWORK_OSTATUS;
53 $ostatus = NETWORK_DFRN;
56 // check if we search only communities or every contact
57 if ($mode === "community") {
58 $extra_sql = " AND `community`";
65 $results = dba::p("SELECT `nurl` FROM `gcontact`
66 WHERE NOT `hide` AND `network` IN (?, ?, ?) AND
67 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
68 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
69 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
70 NETWORK_DFRN, $ostatus, $diaspora, $search, $search, $search
74 while ($result = dba::fetch($results)) {
75 $urlparts = parse_url($result["nurl"]);
77 // Ignore results that look strange.
78 // For historic reasons the gcontact table does contain some garbage.
79 if (!empty($urlparts['query']) || !empty($urlparts['fragment'])) {
83 $gcontacts[] = Contact::getDetailsByURL($result["nurl"], local_user());
89 * @brief Link the gcontact entry with user, contact and global contact
91 * @param integer $gcid Global contact ID
92 * @param integer $uid User ID
93 * @param integer $cid Contact ID
94 * @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(DateTimeFormat::utcNow())
122 "UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
123 dbesc(DateTimeFormat::utcNow()),
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
144 * @return array $gcontact
146 public static function sanitize($gcontact)
148 if ($gcontact['url'] == "") {
149 throw new Exception('URL is empty');
152 $urlparts = parse_url($gcontact['url']);
153 if (!isset($urlparts["scheme"])) {
154 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
157 if (in_array($urlparts["host"], ["www.facebook.com", "facebook.com", "twitter.com", "identi.ca", "alpha.app.net"])) {
158 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
161 // Don't store the statusnet connector as network
162 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
163 if ($gcontact['network'] == NETWORK_STATUSNET) {
164 $gcontact['network'] = "";
167 // Assure that there are no parameter fragments in the profile url
168 if (in_array($gcontact['network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
169 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
172 $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
174 // The global contacts should contain the original picture, not the cached one
175 if (($gcontact['generation'] != 1) && stristr(normalise_link($gcontact['photo']), normalise_link(System::baseUrl()."/photo/"))) {
176 $gcontact['photo'] = "";
179 if (!isset($gcontact['network'])) {
181 "SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
182 dbesc(normalise_link($gcontact['url'])),
183 dbesc(NETWORK_STATUSNET)
185 if (DBM::is_result($r)) {
186 $gcontact['network'] = $r[0]["network"];
189 if (($gcontact['network'] == "") || ($gcontact['network'] == NETWORK_OSTATUS)) {
191 "SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
192 dbesc($gcontact['url']),
193 dbesc(normalise_link($gcontact['url'])),
194 dbesc(NETWORK_STATUSNET)
196 if (DBM::is_result($r)) {
197 $gcontact['network'] = $r[0]["network"];
202 $gcontact['server_url'] = '';
203 $gcontact['network'] = '';
206 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
207 dbesc(normalise_link($gcontact['url']))
210 if (DBM::is_result($x)) {
211 if (!isset($gcontact['network']) && ($x[0]["network"] != NETWORK_STATUSNET)) {
212 $gcontact['network'] = $x[0]["network"];
214 if ($gcontact['updated'] <= NULL_DATE) {
215 $gcontact['updated'] = $x[0]["updated"];
217 if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
218 $gcontact['server_url'] = $x[0]["server_url"];
220 if (!isset($gcontact['addr'])) {
221 $gcontact['addr'] = $x[0]["addr"];
225 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
226 && PortableContact::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
228 $data = Probe::uri($gcontact['url']);
230 if ($data["network"] == NETWORK_PHANTOM) {
231 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
234 $orig_profile = $gcontact['url'];
236 $gcontact["server_url"] = $data["baseurl"];
238 $gcontact = array_merge($gcontact, $data);
240 if ($alternate && ($gcontact['network'] == NETWORK_OSTATUS)) {
241 // Delete the old entry - if it exists
242 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
243 if (DBM::is_result($r)) {
244 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
245 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
250 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
251 throw new Exception('No name and photo for URL '.$gcontact['url']);
254 if (!in_array($gcontact['network'], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA])) {
255 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
258 if (!isset($gcontact['server_url'])) {
259 // We check the server url to be sure that it is a real one
260 $server_url = PortableContact::detectServer($gcontact['url']);
262 // We are now sure that it is a correct URL. So we use it in the future
263 if ($server_url != "") {
264 $gcontact['server_url'] = $server_url;
268 // The server URL doesn't seem to be valid, so we don't store it.
269 if (!PortableContact::checkServer($gcontact['server_url'], $gcontact['network'])) {
270 $gcontact['server_url'] = "";
277 * @param integer $uid id
278 * @param integer $cid id
281 public static function countCommonFriends($uid, $cid)
284 "SELECT count(*) as `total`
285 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
286 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
287 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
288 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
289 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
296 // logger("countCommonFriends: $uid $cid {$r[0]['total']}");
297 if (DBM::is_result($r)) {
298 return $r[0]['total'];
304 * @param integer $uid id
305 * @param integer $zcid zcid
308 public static function countCommonFriendsZcid($uid, $zcid)
311 "SELECT count(*) as `total`
312 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
313 where `glink`.`zcid` = %d
314 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
319 if (DBM::is_result($r)) {
320 return $r[0]['total'];
327 * @param integer $uid user
328 * @param integer $cid cid
329 * @param integer $start optional, default 0
330 * @param integer $limit optional, default 9999
331 * @param boolean $shuffle optional, default false
334 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
337 $sql_extra = " order by rand() ";
339 $sql_extra = " order by `gcontact`.`name` asc ";
343 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
345 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
346 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
347 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
348 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
349 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
350 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
351 $sql_extra LIMIT %d, %d",
360 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
365 * @param integer $uid user
366 * @param integer $zcid zcid
367 * @param integer $start optional, default 0
368 * @param integer $limit optional, default 9999
369 * @param boolean $shuffle optional, default false
372 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
375 $sql_extra = " order by rand() ";
377 $sql_extra = " order by `gcontact`.`name` asc ";
382 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
383 where `glink`.`zcid` = %d
384 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
385 $sql_extra limit %d, %d",
392 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
397 * @param integer $uid user
398 * @param integer $cid cid
401 public static function countAllFriends($uid, $cid)
404 "SELECT count(*) as `total`
405 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
406 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
407 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
412 if (DBM::is_result($r)) {
413 return $r[0]['total'];
420 * @param integer $uid user
421 * @param integer $cid cid
422 * @param integer $start optional, default 0
423 * @param integer $limit optional, default 80
426 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
429 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
431 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
432 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
433 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
434 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
435 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
443 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
448 * @param object $uid user
449 * @param integer $start optional, default 0
450 * @param integer $limit optional, default 80
453 public static function suggestionQuery($uid, $start = 0, $limit = 80)
460 * Uncommented because the result of the queries are to big to store it in the cache.
461 * We need to decide if we want to change the db column type or if we want to delete it.
463 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
464 //if (!is_null($list)) {
468 $network = [NETWORK_DFRN];
470 if (Config::get('system', 'diaspora_enabled')) {
471 $network[] = NETWORK_DIASPORA;
474 if (!Config::get('system', 'ostatus_disabled')) {
475 $network[] = NETWORK_OSTATUS;
478 $sql_network = implode("', '", $network);
479 $sql_network = "'".$sql_network."'";
481 /// @todo This query is really slow
482 // By now we cache the data for five minutes
484 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
485 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
486 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
487 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
488 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
489 AND `gcontact`.`updated` >= '%s'
490 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
491 AND `gcontact`.`network` IN (%s)
492 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
503 if (DBM::is_result($r) && count($r) >= ($limit -1)) {
505 * Uncommented because the result of the queries are to big to store it in the cache.
506 * We need to decide if we want to change the db column type or if we want to delete it.
508 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
514 "SELECT gcontact.* FROM gcontact
515 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
516 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
517 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
518 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
519 AND `gcontact`.`updated` >= '%s'
520 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
521 AND `gcontact`.`network` IN (%s)
522 ORDER BY rand() LIMIT %d, %d",
533 foreach ($r2 as $suggestion) {
534 $list[$suggestion["nurl"]] = $suggestion;
537 foreach ($r as $suggestion) {
538 $list[$suggestion["nurl"]] = $suggestion;
541 while (sizeof($list) > ($limit)) {
546 * Uncommented because the result of the queries are to big to store it in the cache.
547 * We need to decide if we want to change the db column type or if we want to delete it.
549 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
556 public static function updateSuggestions()
562 /// @TODO Check if it is really neccessary to poll the own server
563 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
565 $done[] = System::baseUrl() . '/poco';
567 if (strlen(Config::get('system', 'directory'))) {
568 $x = Network::fetchUrl(get_server()."/pubsites");
570 $j = json_decode($x);
572 foreach ($j->entries as $entry) {
573 PortableContact::checkServer($entry->url);
575 $url = $entry->url . '/poco';
576 if (! in_array($url, $done)) {
577 PortableContact::loadWorker(0, 0, 0, $entry->url . '/poco');
584 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
586 "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
588 dbesc(NETWORK_DIASPORA)
591 if (DBM::is_result($r)) {
592 foreach ($r as $rr) {
593 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
594 if (! in_array($base, $done)) {
595 PortableContact::loadWorker(0, 0, 0, $base);
602 * @brief Removes unwanted parts from a contact url
604 * @param string $url Contact url
606 * @return string Contact url with the wanted parts
608 public static function cleanContactUrl($url)
610 $parts = parse_url($url);
612 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
616 $new_url = $parts["scheme"]."://".$parts["host"];
618 if (isset($parts["port"])) {
619 $new_url .= ":".$parts["port"];
622 if (isset($parts["path"])) {
623 $new_url .= $parts["path"];
626 if ($new_url != $url) {
627 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), LOGGER_DEBUG);
634 * @brief Replace alternate OStatus user format with the primary one
636 * @param array $contact contact array (called by reference)
639 public static function fixAlternateContactAddress(&$contact)
641 if (($contact["network"] == NETWORK_OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
642 $data = Probe::uri($contact["url"]);
643 if ($contact["network"] == NETWORK_OSTATUS) {
644 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
645 $contact["url"] = $data["url"];
646 $contact["addr"] = $data["addr"];
647 $contact["alias"] = $data["alias"];
648 $contact["server_url"] = $data["baseurl"];
654 * @brief Fetch the gcontact id, add an entry if not existed
656 * @param array $contact contact array
658 * @return bool|int Returns false if not found, integer if contact was found
660 public static function getId($contact)
664 $last_failure_str = '';
665 $last_contact_str = '';
667 if (in_array($contact["network"], [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"], [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"], [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(DateTimeFormat::utcNow()),
718 dbesc(DateTimeFormat::utcNow()),
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"], [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 array $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 ($public_contact[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 ($public_contact[0]["keywords"] == "0") {
792 $public_contact[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] = $public_contact[0][$field];
802 if (!isset($contact["hide"])) {
803 $contact["hide"] = $public_contact[0]["hide"];
806 $fields["hide"] = $public_contact[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"] <= $public_contact[0]["generation"])) || ($public_contact[0]["generation"] == 0)) {
842 foreach ($fields as $field => $data) {
843 if ($contact[$field] != $public_contact[0][$field]) {
844 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$public_contact[0][$field]."'", LOGGER_DEBUG);
849 if ($contact["generation"] < $public_contact[0]["generation"]) {
850 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$public_contact[0]["generation"]."'", LOGGER_DEBUG);
856 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
857 $condition = ['`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
858 normalise_link($contact["url"]), $contact["generation"]];
859 $contact["updated"] = DBM::date($contact["updated"]);
861 $updated = ['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.
876 /// @todo Check if we really should do this.
877 // The quality of the gcontact table is mostly lower than the public contact
878 $public_contact = dba::selectFirst('contact', ['id'], ['nurl' => normalise_link($contact["url"]), 'uid' => 0]);
879 if (DBM::is_result($public_contact)) {
880 logger("Update public contact ".$public_contact["id"], LOGGER_DEBUG);
882 Contact::updateAvatar($contact["photo"], 0, $public_contact["id"]);
884 $fields = ['name', 'nick', 'addr',
885 'network', 'bd', 'gender',
886 'keywords', 'alias', 'contact-type',
887 'url', 'location', 'about'];
888 $old_contact = dba::selectFirst('contact', $fields, ['id' => $public_contact["id"]]);
890 // Update it with the current values
891 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'],
892 'addr' => $contact['addr'], 'network' => $contact['network'],
893 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
894 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
895 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
896 'location' => $contact['location'], 'about' => $contact['about']];
898 // Don't update the birthday field if not set or invalid
899 if (empty($contact['birthday']) || ($contact['birthday'] < '0001-01-01')) {
900 unset($fields['bd']);
904 dba::update('contact', $fields, ['id' => $public_contact["id"]], $old_contact);
912 * @brief Updates the gcontact entry from probe
914 * @param string $url profile link
917 public static function updateFromProbe($url)
919 $data = Probe::uri($url);
921 if (in_array($data["network"], [NETWORK_PHANTOM])) {
922 logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
926 $data["server_url"] = $data["baseurl"];
932 * @brief Update the gcontact entry for a given user id
934 * @param int $uid User ID
937 public static function updateForUser($uid)
940 "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
941 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
942 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
943 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
944 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
946 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
947 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
948 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
952 $location = Profile::formatLocation(
953 ["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
956 // The "addr" field was added in 3.4.3 so it can be empty for older users
957 if ($r[0]["addr"] != "") {
958 $addr = $r[0]["nickname"].'@'.str_replace(["http://", "https://"], "", System::baseUrl());
960 $addr = $r[0]["addr"];
963 $gcontact = ["name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
964 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
965 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
966 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
967 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
968 "nick" => $r[0]["nickname"], "addr" => $addr,
969 "connect" => $addr, "server_url" => System::baseUrl(),
970 "generation" => 1, "network" => NETWORK_DFRN];
972 self::update($gcontact);
976 * @brief Fetches users of given GNU Social server
978 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
980 * @param string $server Server address
983 public static function fetchGsUsers($server)
985 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
987 $url = $server."/main/statistics";
989 $result = Network::curl($url);
990 if (!$result["success"]) {
994 $statistics = json_decode($result["body"]);
996 if (is_object($statistics->config)) {
997 if ($statistics->config->instance_with_ssl) {
998 $server = "https://";
1000 $server = "http://";
1003 $server .= $statistics->config->instance_address;
1005 $hostname = $statistics->config->instance_address;
1007 /// @TODO is_object() above means here no object, still $statistics is being used as object
1008 if ($statistics->instance_with_ssl) {
1009 $server = "https://";
1011 $server = "http://";
1014 $server .= $statistics->instance_address;
1016 $hostname = $statistics->instance_address;
1019 if (is_object($statistics->users)) {
1020 foreach ($statistics->users as $nick => $user) {
1021 $profile_url = $server."/".$user->nickname;
1023 $contact = ["url" => $profile_url,
1024 "name" => $user->fullname,
1025 "addr" => $user->nickname."@".$hostname,
1026 "nick" => $user->nickname,
1027 "about" => $user->bio,
1028 "network" => NETWORK_OSTATUS,
1029 "photo" => System::baseUrl()."/images/person-175.jpg"];
1030 self::getId($contact);
1036 * @brief Asking GNU Social server on a regular base for their user data
1039 public static function discoverGsUsers()
1041 $requery_days = intval(Config::get("system", "poco_requery_days"));
1043 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1046 "SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
1047 dbesc(NETWORK_OSTATUS),
1051 if (!DBM::is_result($r)) {
1055 foreach ($r as $server) {
1056 self::fetchGsUsers($server["url"]);
1057 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(DateTimeFormat::utcNow()), dbesc($server["nurl"]));
1064 public static function getRandomUrl()
1067 "SELECT `url` FROM `gcontact` WHERE `network` = '%s'
1068 AND `last_contact` >= `last_failure`
1069 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
1070 ORDER BY rand() LIMIT 1",
1074 if (DBM::is_result($r)) {
1075 return dirname($r[0]['url']);