4 * @file src/Model/GlobalContact.php
5 * @brief This file includes the GlobalContact class with directory related functions
7 namespace Friendica\Model;
10 use Friendica\Core\Config;
11 use Friendica\Core\Logger;
12 use Friendica\Core\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBA;
16 use Friendica\Network\Probe;
17 use Friendica\Protocol\PortableContact;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Network;
20 use Friendica\Util\Strings;
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
34 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
36 public static function searchByName($search, $mode = '')
42 // check supported networks
43 if (Config::get('system', 'diaspora_enabled')) {
44 $diaspora = Protocol::DIASPORA;
46 $diaspora = Protocol::DFRN;
49 if (!Config::get('system', 'ostatus_disabled')) {
50 $ostatus = Protocol::OSTATUS;
52 $ostatus = Protocol::DFRN;
55 // check if we search only communities or every contact
56 if ($mode === "community") {
57 $extra_sql = " AND `community`";
64 $results = DBA::p("SELECT `nurl` FROM `gcontact`
65 WHERE NOT `hide` AND `network` IN (?, ?, ?, ?) AND
66 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
67 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
68 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
69 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $search, $search, $search
73 while ($result = DBA::fetch($results)) {
74 $urlparts = parse_url($result["nurl"]);
76 // Ignore results that look strange.
77 // For historic reasons the gcontact table does contain some garbage.
78 if (!empty($urlparts['query']) || !empty($urlparts['fragment'])) {
82 $gcontacts[] = Contact::getDetailsByURL($result["nurl"], local_user());
88 * @brief Link the gcontact entry with user, contact and global contact
90 * @param integer $gcid Global contact ID
91 * @param integer $uid User ID
92 * @param integer $cid Contact ID
93 * @param integer $zcid Global Contact ID
97 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
103 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
104 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
108 * @brief Sanitize the given gcontact data
112 * 1: Profiles on this server
113 * 2: Contacts of profiles on this server
114 * 3: Contacts of contacts of profiles on this server
117 * @param array $gcontact array with gcontact data
118 * @return array $gcontact
121 public static function sanitize($gcontact)
123 if ($gcontact['url'] == "") {
124 throw new Exception('URL is empty');
127 $urlparts = parse_url($gcontact['url']);
128 if (!isset($urlparts["scheme"])) {
129 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
132 if (in_array($urlparts["host"], ["twitter.com", "identi.ca"])) {
133 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
136 // Don't store the statusnet connector as network
137 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
138 if ($gcontact['network'] == Protocol::STATUSNET) {
139 $gcontact['network'] = "";
142 // Assure that there are no parameter fragments in the profile url
143 if (empty($gcontact["network"]) || in_array($gcontact["network"], Protocol::FEDERATED)) {
144 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
147 $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
149 // The global contacts should contain the original picture, not the cached one
150 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(System::baseUrl()."/photo/"))) {
151 $gcontact['photo'] = "";
154 if (!isset($gcontact['network'])) {
155 $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
156 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
157 $contact = DBA::selectFirst('contact', ['network'], $condition);
158 if (DBA::isResult($contact)) {
159 $gcontact['network'] = $contact["network"];
162 if (($gcontact['network'] == "") || ($gcontact['network'] == Protocol::OSTATUS)) {
163 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
164 $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
165 $contact = DBA::selectFirst('contact', ['network'], $condition);
166 if (DBA::isResult($contact)) {
167 $gcontact['network'] = $contact["network"];
172 $gcontact['server_url'] = '';
173 $gcontact['network'] = '';
175 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
176 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
177 if (DBA::isResult($gcnt)) {
178 if (!isset($gcontact['network']) && ($gcnt["network"] != Protocol::STATUSNET)) {
179 $gcontact['network'] = $gcnt["network"];
181 if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
182 $gcontact['updated'] = $gcnt["updated"];
184 if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt["server_url"]) != Strings::normaliseLink($gcnt["url"]))) {
185 $gcontact['server_url'] = $gcnt["server_url"];
187 if (!isset($gcontact['addr'])) {
188 $gcontact['addr'] = $gcnt["addr"];
192 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
193 && PortableContact::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
195 $data = Probe::uri($gcontact['url']);
197 if ($data["network"] == Protocol::PHANTOM) {
198 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
201 $orig_profile = $gcontact['url'];
203 $gcontact["server_url"] = $data["baseurl"];
205 $gcontact = array_merge($gcontact, $data);
207 if ($alternate && ($gcontact['network'] == Protocol::OSTATUS)) {
208 // Delete the old entry - if it exists
209 if (DBA::exists('gcontact', ['nurl' => Strings::normaliseLink($orig_profile)])) {
210 DBA::delete('gcontact', ['nurl' => Strings::normaliseLink($orig_profile)]);
215 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
216 throw new Exception('No name and photo for URL '.$gcontact['url']);
219 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
220 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
223 if (!isset($gcontact['server_url'])) {
224 // We check the server url to be sure that it is a real one
225 $server_url = Contact::getBasepath($gcontact['url']);
227 // We are now sure that it is a correct URL. So we use it in the future
228 if ($server_url != "") {
229 $gcontact['server_url'] = $server_url;
233 // The server URL doesn't seem to be valid, so we don't store it.
234 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
235 $gcontact['server_url'] = "";
242 * @param integer $uid id
243 * @param integer $cid id
247 public static function countCommonFriends($uid, $cid)
250 "SELECT count(*) as `total`
251 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
252 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
253 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
254 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
255 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
262 // Logger::log("countCommonFriends: $uid $cid {$r[0]['total']}");
263 if (DBA::isResult($r)) {
264 return $r[0]['total'];
270 * @param integer $uid id
271 * @param integer $zcid zcid
275 public static function countCommonFriendsZcid($uid, $zcid)
278 "SELECT count(*) as `total`
279 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
280 where `glink`.`zcid` = %d
281 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
286 if (DBA::isResult($r)) {
287 return $r[0]['total'];
294 * @param integer $uid user
295 * @param integer $cid cid
296 * @param integer $start optional, default 0
297 * @param integer $limit optional, default 9999
298 * @param boolean $shuffle optional, default false
302 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
305 $sql_extra = " order by rand() ";
307 $sql_extra = " order by `gcontact`.`name` asc ";
311 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
313 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
314 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
315 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
316 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
317 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
318 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
319 $sql_extra LIMIT %d, %d",
328 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
333 * @param integer $uid user
334 * @param integer $zcid zcid
335 * @param integer $start optional, default 0
336 * @param integer $limit optional, default 9999
337 * @param boolean $shuffle optional, default false
341 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
344 $sql_extra = " order by rand() ";
346 $sql_extra = " order by `gcontact`.`name` asc ";
351 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
352 where `glink`.`zcid` = %d
353 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
354 $sql_extra limit %d, %d",
361 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
366 * @param integer $uid user
367 * @param integer $cid cid
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 (DBA::isResult($r)) {
383 return $r[0]['total'];
390 * @param integer $uid user
391 * @param integer $cid cid
392 * @param integer $start optional, default 0
393 * @param integer $limit optional, default 80
397 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
400 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
402 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
403 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
404 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
405 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
406 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
414 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
419 * @param int $uid user
420 * @param integer $start optional, default 0
421 * @param integer $limit optional, default 80
423 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
425 public static function suggestionQuery($uid, $start = 0, $limit = 80)
432 * Uncommented because the result of the queries are to big to store it in the cache.
433 * We need to decide if we want to change the db column type or if we want to delete it.
435 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
436 //if (!is_null($list)) {
440 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
442 if (Config::get('system', 'diaspora_enabled')) {
443 $network[] = Protocol::DIASPORA;
446 if (!Config::get('system', 'ostatus_disabled')) {
447 $network[] = Protocol::OSTATUS;
450 $sql_network = implode("', '", $network);
451 $sql_network = "'".$sql_network."'";
453 /// @todo This query is really slow
454 // By now we cache the data for five minutes
456 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
457 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
458 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
459 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
460 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
461 AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
462 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
463 AND `gcontact`.`network` IN (%s)
464 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
475 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
477 * Uncommented because the result of the queries are to big to store it in the cache.
478 * We need to decide if we want to change the db column type or if we want to delete it.
480 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, Cache::FIVE_MINUTES);
486 "SELECT gcontact.* FROM gcontact
487 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
488 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 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 ORDER BY rand() LIMIT %d, %d",
505 foreach ($r2 as $suggestion) {
506 $list[$suggestion["nurl"]] = $suggestion;
509 foreach ($r as $suggestion) {
510 $list[$suggestion["nurl"]] = $suggestion;
513 while (sizeof($list) > ($limit)) {
518 * Uncommented because the result of the queries are to big to store it in the cache.
519 * We need to decide if we want to change the db column type or if we want to delete it.
521 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, Cache::FIVE_MINUTES);
527 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
529 public static function updateSuggestions()
533 /// @TODO Check if it is really neccessary to poll the own server
534 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
536 $done[] = System::baseUrl() . '/poco';
538 if (strlen(Config::get('system', 'directory'))) {
539 $x = Network::fetchUrl(get_server()."/pubsites");
541 $j = json_decode($x);
542 if (!empty($j->entries)) {
543 foreach ($j->entries as $entry) {
544 GServer::check($entry->url);
546 $url = $entry->url . '/poco';
547 if (!in_array($url, $done)) {
548 PortableContact::loadWorker(0, 0, 0, $url);
556 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
558 "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
559 DBA::escape(Protocol::DFRN),
560 DBA::escape(Protocol::DIASPORA)
563 if (DBA::isResult($r)) {
564 foreach ($r as $rr) {
565 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
566 if (! in_array($base, $done)) {
567 PortableContact::loadWorker(0, 0, 0, $base);
574 * @brief Removes unwanted parts from a contact url
576 * @param string $url Contact url
578 * @return string Contact url with the wanted parts
581 public static function cleanContactUrl($url)
583 $parts = parse_url($url);
585 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
589 $new_url = $parts["scheme"]."://".$parts["host"];
591 if (isset($parts["port"])) {
592 $new_url .= ":".$parts["port"];
595 if (isset($parts["path"])) {
596 $new_url .= $parts["path"];
599 if ($new_url != $url) {
600 Logger::log("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), Logger::DEBUG);
607 * @brief Replace alternate OStatus user format with the primary one
609 * @param array $contact contact array (called by reference)
611 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
612 * @throws \ImagickException
614 public static function fixAlternateContactAddress(&$contact)
616 if (($contact["network"] == Protocol::OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
617 $data = Probe::uri($contact["url"]);
618 if ($contact["network"] == Protocol::OSTATUS) {
619 Logger::log("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
620 $contact["url"] = $data["url"];
621 $contact["addr"] = $data["addr"];
622 $contact["alias"] = $data["alias"];
623 $contact["server_url"] = $data["baseurl"];
629 * @brief Fetch the gcontact id, add an entry if not existed
631 * @param array $contact contact array
633 * @return bool|int Returns false if not found, integer if contact was found
634 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
635 * @throws \ImagickException
637 public static function getId($contact)
641 $last_failure_str = '';
642 $last_contact_str = '';
644 if (empty($contact["network"])) {
645 Logger::log("Empty network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
649 if (in_array($contact["network"], [Protocol::PHANTOM])) {
650 Logger::log("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
654 if ($contact["network"] == Protocol::STATUSNET) {
655 $contact["network"] = Protocol::OSTATUS;
658 // All new contacts are hidden by default
659 if (!isset($contact["hide"])) {
660 $contact["hide"] = true;
663 // Replace alternate OStatus user format with the primary one
664 self::fixAlternateContactAddress($contact);
666 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
667 if (in_array($contact["network"], Protocol::FEDERATED)) {
668 $contact["url"] = self::cleanContactUrl($contact["url"]);
671 DBA::lock('gcontact');
672 $fields = ['id', 'last_contact', 'last_failure', 'network'];
673 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact["url"])]);
674 if (DBA::isResult($gcnt)) {
675 $gcontact_id = $gcnt["id"];
677 // Update every 90 days
678 if (in_array($gcnt["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
679 $last_failure_str = $gcnt["last_failure"];
680 $last_failure = strtotime($gcnt["last_failure"]);
681 $last_contact_str = $gcnt["last_contact"];
682 $last_contact = strtotime($gcnt["last_contact"]);
683 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
686 $contact['location'] = defaults($contact, 'location', '');
687 $contact['about'] = defaults($contact, 'about', '');
688 $contact['generation'] = defaults($contact, 'generation', 0);
691 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
692 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
693 DBA::escape($contact["name"]),
694 DBA::escape($contact["nick"]),
695 DBA::escape($contact["addr"]),
696 DBA::escape($contact["network"]),
697 DBA::escape($contact["url"]),
698 DBA::escape(Strings::normaliseLink($contact["url"])),
699 DBA::escape($contact["photo"]),
700 DBA::escape(DateTimeFormat::utcNow()),
701 DBA::escape(DateTimeFormat::utcNow()),
702 DBA::escape($contact["location"]),
703 DBA::escape($contact["about"]),
704 intval($contact["hide"]),
705 intval($contact["generation"])
708 $condition = ['nurl' => Strings::normaliseLink($contact["url"])];
709 $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
710 if (DBA::isResult($cnt)) {
711 $gcontact_id = $cnt["id"];
712 $doprobing = in_array($cnt["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""]);
718 Logger::log("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], Logger::DEBUG);
719 Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]);
726 * @brief Updates the gcontact table from a given array
728 * @param array $contact contact array
730 * @return bool|int Returns false if not found, integer if contact was found
731 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
732 * @throws \ImagickException
734 public static function update($contact)
736 // Check for invalid "contact-type" value
737 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
738 $contact['contact-type'] = 0;
741 /// @todo update contact table as well
743 $gcontact_id = self::getId($contact);
749 $public_contact = DBA::selectFirst('gcontact', [
750 'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'gender', 'keywords',
751 'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
752 ], ['id' => $gcontact_id]);
754 if (!DBA::isResult($public_contact)) {
758 // Get all field names
760 foreach ($public_contact as $field => $data) {
761 $fields[$field] = $data;
764 unset($fields['url']);
765 unset($fields['updated']);
766 unset($fields['hide']);
768 // Bugfix: We had an error in the storing of keywords which lead to the "0"
769 // This value is still transmitted via poco.
770 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
771 unset($contact['keywords']);
774 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
775 $public_contact['keywords'] = '';
778 // assign all unassigned fields from the database entry
779 foreach ($fields as $field => $data) {
780 if (empty($contact[$field])) {
781 $contact[$field] = $public_contact[$field];
785 if (!isset($contact['hide'])) {
786 $contact['hide'] = $public_contact['hide'];
789 $fields['hide'] = $public_contact['hide'];
791 if ($contact['network'] == Protocol::STATUSNET) {
792 $contact['network'] = Protocol::OSTATUS;
795 // Replace alternate OStatus user format with the primary one
796 self::fixAlternateContactAddress($contact);
798 if (!isset($contact['updated'])) {
799 $contact['updated'] = DateTimeFormat::utcNow();
802 if ($contact['network'] == Protocol::TWITTER) {
803 $contact['server_url'] = 'http://twitter.com';
806 if (empty($contact['server_url'])) {
807 $data = Probe::uri($contact['url']);
808 if ($data['network'] != Protocol::PHANTOM) {
809 $contact['server_url'] = $data['baseurl'];
812 $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
815 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
816 $hostname = str_replace('http://', '', $contact['server_url']);
817 $contact['addr'] = $contact['nick'] . '@' . $hostname;
820 // Check if any field changed
822 unset($fields['generation']);
824 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
825 foreach ($fields as $field => $data) {
826 if ($contact[$field] != $public_contact[$field]) {
827 Logger::debug('Difference found.', ['contact' => $contact["url"], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
832 if ($contact['generation'] < $public_contact['generation']) {
833 Logger::debug('Difference found.', ['contact' => $contact["url"], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
839 Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
840 $condition = ['`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
841 Strings::normaliseLink($contact["url"]), $contact["generation"]];
842 $contact["updated"] = DateTimeFormat::utc($contact["updated"]);
845 'photo' => $contact['photo'], 'name' => $contact['name'],
846 'nick' => $contact['nick'], 'addr' => $contact['addr'],
847 'network' => $contact['network'], 'birthday' => $contact['birthday'],
848 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
849 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
850 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
851 'notify' => $contact['notify'], 'url' => $contact['url'],
852 'location' => $contact['location'], 'about' => $contact['about'],
853 'generation' => $contact['generation'], 'updated' => $contact['updated'],
854 'server_url' => $contact['server_url'], 'connect' => $contact['connect']
857 DBA::update('gcontact', $updated, $condition, $fields);
864 * @brief Updates the gcontact entry from a given public contact id
866 * @param integer $cid contact id
868 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
869 * @throws \ImagickException
871 public static function updateFromPublicContactID($cid)
873 self::updateFromPublicContact(['id' => $cid]);
877 * @brief Updates the gcontact entry from a given public contact url
879 * @param string $url contact url
880 * @return integer gcontact id
881 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
882 * @throws \ImagickException
884 public static function updateFromPublicContactURL($url)
886 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
890 * @brief Helper function for updateFromPublicContactID and updateFromPublicContactURL
892 * @param array $condition contact condition
893 * @return integer gcontact id
894 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
895 * @throws \ImagickException
897 private static function updateFromPublicContact($condition)
899 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
900 'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
901 'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
902 'baseurl', 'sensitive', 'unsearchable'];
904 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
905 if (!DBA::isResult($contact)) {
909 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender', 'generation',
910 'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
911 'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
912 'server_url', 'nsfw', 'hide', 'id'];
914 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
915 $do_insert = !DBA::isResult($old_gcontact);
922 // These fields are identical in both contact and gcontact
923 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
924 'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated'];
926 foreach ($fields as $field) {
927 $gcontact[$field] = $contact[$field];
930 // These fields are having different names but the same content
931 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
932 $gcontact['nsfw'] = $contact['sensitive'];
933 $gcontact['hide'] = $contact['unsearchable'];
934 $gcontact['archived'] = $contact['archive'];
935 $gcontact['archive_date'] = $contact['term-date'];
936 $gcontact['birthday'] = $contact['bd'];
937 $gcontact['photo'] = $contact['avatar'];
938 $gcontact['last_contact'] = $contact['success_update'];
939 $gcontact['last_failure'] = $contact['failure_update'];
940 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
942 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
943 if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
944 unset($gcontact[$field]);
948 if (!$gcontact['archived']) {
949 $gcontact['archive_date'] = DBA::NULL_DATETIME;
952 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
953 && ($old_gcontact['created'] <= $gcontact['created'])) {
954 unset($gcontact['created']);
957 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
958 unset($gcontact['birthday']);
961 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
962 $gcontact['generation'] = 2; // We fetched the data directly from the other server
966 DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
967 return $old_gcontact['id'];
968 } elseif (!$gcontact['archived']) {
969 DBA::insert('gcontact', $gcontact);
970 return DBA::lastInsertId();
975 * @brief Updates the gcontact entry from probe
977 * @param string $url profile link
978 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
980 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
981 * @throws \ImagickException
983 public static function updateFromProbe($url, $force = false)
985 $data = Probe::uri($url, $force);
987 if (in_array($data["network"], [Protocol::PHANTOM])) {
988 Logger::log("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
992 $data["server_url"] = $data["baseurl"];
998 * @brief Update the gcontact entry for a given user id
1000 * @param int $uid User ID
1002 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1003 * @throws \ImagickException
1005 public static function updateForUser($uid)
1008 "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
1009 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
1010 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
1011 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
1012 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
1014 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
1015 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
1016 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
1020 if (!DBA::isResult($r)) {
1021 Logger::log('Cannot find user with uid=' . $uid, Logger::INFO);
1025 $location = Profile::formatLocation(
1026 ["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
1029 // The "addr" field was added in 3.4.3 so it can be empty for older users
1030 if ($r[0]["addr"] != "") {
1031 $addr = $r[0]["nickname"].'@'.str_replace(["http://", "https://"], "", System::baseUrl());
1033 $addr = $r[0]["addr"];
1036 $gcontact = ["name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
1037 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
1038 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
1039 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
1040 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
1041 "nick" => $r[0]["nickname"], "addr" => $addr,
1042 "connect" => $addr, "server_url" => System::baseUrl(),
1043 "generation" => 1, "network" => Protocol::DFRN];
1045 self::update($gcontact);
1049 * @brief Fetches users of given GNU Social server
1051 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1053 * @param string $server Server address
1055 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1056 * @throws \ImagickException
1058 public static function fetchGsUsers($server)
1060 Logger::log("Fetching users from GNU Social server ".$server, Logger::DEBUG);
1062 $url = $server."/main/statistics";
1064 $curlResult = Network::curl($url);
1065 if (!$curlResult->isSuccess()) {
1069 $statistics = json_decode($curlResult->getBody());
1071 if (!empty($statistics->config->instance_address)) {
1072 if (!empty($statistics->config->instance_with_ssl)) {
1073 $server = "https://";
1075 $server = "http://";
1078 $server .= $statistics->config->instance_address;
1080 $hostname = $statistics->config->instance_address;
1081 } elseif (!empty($statistics->instance_address)) {
1082 if (!empty($statistics->instance_with_ssl)) {
1083 $server = "https://";
1085 $server = "http://";
1088 $server .= $statistics->instance_address;
1090 $hostname = $statistics->instance_address;
1093 if (!empty($statistics->users)) {
1094 foreach ($statistics->users as $nick => $user) {
1095 $profile_url = $server."/".$user->nickname;
1097 $contact = ["url" => $profile_url,
1098 "name" => $user->fullname,
1099 "addr" => $user->nickname."@".$hostname,
1100 "nick" => $user->nickname,
1101 "network" => Protocol::OSTATUS,
1102 "photo" => System::baseUrl()."/images/person-300.jpg"];
1104 if (isset($user->bio)) {
1105 $contact["about"] = $user->bio;
1108 self::getId($contact);
1114 * @brief Asking GNU Social server on a regular base for their user data
1116 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1117 * @throws \ImagickException
1119 public static function discoverGsUsers()
1121 $requery_days = intval(Config::get("system", "poco_requery_days"));
1123 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1125 $r = DBA::select('gserver', ['nurl', 'url'], [
1127 AND `last_contact` >= `last_failure`
1128 AND `last_poco_query` < ?',
1133 'order' => ['RAND()']
1136 if (!DBA::isResult($r)) {
1140 foreach ($r as $server) {
1141 self::fetchGsUsers($server["url"]);
1142 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", DBA::escape(DateTimeFormat::utcNow()), DBA::escape($server["nurl"]));
1147 * Returns a random, global contact of the current node
1149 * @return string The profile URL
1152 public static function getRandomUrl()
1154 $r = DBA::selectFirst('gcontact', ['url'], [
1156 AND `last_contact` >= `last_failure`
1159 DateTimeFormat::utc('now - 1 month'),
1160 ], ['order' => ['RAND()']]);
1162 if (DBA::isResult($r)) {