4 * @file src/Model/GlobalContact.php
5 * @brief This file includes the GlobalContact class with directory related functions
7 namespace Friendica\Model;
12 use Friendica\Core\Config;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
18 use Friendica\Network\Probe;
19 use Friendica\Protocol\ActivityPub;
20 use Friendica\Protocol\PortableContact;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Strings;
26 * @brief This class handles GlobalContact related functions
31 * @brief Search global contact table by nick or name
33 * @param string $search Name or nick
34 * @param string $mode Search mode (e.g. 'community')
36 * @return array with search results
37 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
39 public static function searchByName($search, $mode = '')
45 // check supported networks
46 if (Config::get('system', 'diaspora_enabled')) {
47 $diaspora = Protocol::DIASPORA;
49 $diaspora = Protocol::DFRN;
52 if (!Config::get('system', 'ostatus_disabled')) {
53 $ostatus = Protocol::OSTATUS;
55 $ostatus = Protocol::DFRN;
58 // check if we search only communities or every contact
59 if ($mode === 'community') {
60 $extra_sql = ' AND `community`';
67 $results = DBA::p("SELECT `nurl` FROM `gcontact`
68 WHERE NOT `hide` AND `network` IN (?, ?, ?, ?) AND
69 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
70 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
71 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
72 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $search, $search, $search
76 while ($result = DBA::fetch($results)) {
77 $urlparts = parse_url($result['nurl']);
79 // Ignore results that look strange.
80 // For historic reasons the gcontact table does contain some garbage.
81 if (!empty($urlparts['query']) || !empty($urlparts['fragment'])) {
85 $gcontacts[] = Contact::getDetailsByURL($result['nurl'], local_user());
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
100 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
106 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
107 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
111 * @brief Sanitize the given gcontact data
115 * 1: Profiles on this server
116 * 2: Contacts of profiles on this server
117 * 3: Contacts of contacts of profiles on this server
120 * @param array $gcontact array with gcontact data
121 * @return array $gcontact
124 public static function sanitize($gcontact)
126 if ($gcontact['url'] == '') {
127 throw new Exception('URL is empty');
130 $gcontact['server_url'] = defaults($gcontact, 'server_url', '');
132 $urlparts = parse_url($gcontact['url']);
133 if (!isset($urlparts['scheme'])) {
134 throw new Exception('This ('.$gcontact['url'].") doesn't seem to be an url.");
137 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
138 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
141 // Don't store the statusnet connector as network
142 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
143 if ($gcontact['network'] == Protocol::STATUSNET) {
144 $gcontact['network'] = '';
147 // Assure that there are no parameter fragments in the profile url
148 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
149 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
152 $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
154 // The global contacts should contain the original picture, not the cached one
155 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(System::baseUrl() . '/photo/'))) {
156 $gcontact['photo'] = '';
159 if (empty($gcontact['network'])) {
160 $gcontact['network'] = '';
162 $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
163 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
164 $contact = DBA::selectFirst('contact', ['network'], $condition);
165 if (DBA::isResult($contact)) {
166 $gcontact['network'] = $contact['network'];
169 if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
170 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
171 $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
172 $contact = DBA::selectFirst('contact', ['network'], $condition);
173 if (DBA::isResult($contact)) {
174 $gcontact['network'] = $contact['network'];
179 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
180 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
181 if (DBA::isResult($gcnt)) {
182 if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
183 $gcontact['network'] = $gcnt['network'];
185 if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
186 $gcontact['updated'] = $gcnt['updated'];
188 if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
189 $gcontact['server_url'] = $gcnt['server_url'];
191 if (!isset($gcontact['addr'])) {
192 $gcontact['addr'] = $gcnt['addr'];
196 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
197 && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
199 $data = Probe::uri($gcontact['url']);
201 if ($data['network'] == Protocol::PHANTOM) {
202 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
205 $orig_profile = $gcontact['url'];
207 $gcontact['server_url'] = $data['baseurl'];
209 $gcontact = array_merge($gcontact, $data);
211 if ($alternate && ($gcontact['network'] == Protocol::OSTATUS)) {
212 // Delete the old entry - if it exists
213 if (DBA::exists('gcontact', ['nurl' => Strings::normaliseLink($orig_profile)])) {
214 DBA::delete('gcontact', ['nurl' => Strings::normaliseLink($orig_profile)]);
219 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
220 throw new Exception('No name and photo for URL '.$gcontact['url']);
223 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
224 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
227 if (empty($gcontact['server_url'])) {
228 // We check the server url to be sure that it is a real one
229 $server_url = Contact::getBasepath($gcontact['url']);
231 // We are now sure that it is a correct URL. So we use it in the future
232 if ($server_url != '') {
233 $gcontact['server_url'] = $server_url;
237 // The server URL doesn't seem to be valid, so we don't store it.
238 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
239 $gcontact['server_url'] = '';
246 * @param integer $uid id
247 * @param integer $cid id
251 public static function countCommonFriends($uid, $cid)
254 "SELECT count(*) as `total`
255 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
256 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
257 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
258 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
259 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d) ",
266 // Logger::log("countCommonFriends: $uid $cid {$r[0]['total']}");
267 if (DBA::isResult($r)) {
268 return $r[0]['total'];
274 * @param integer $uid id
275 * @param integer $zcid zcid
279 public static function countCommonFriendsZcid($uid, $zcid)
282 "SELECT count(*) as `total`
283 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
284 where `glink`.`zcid` = %d
285 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0) ",
290 if (DBA::isResult($r)) {
291 return $r[0]['total'];
298 * @param integer $uid user
299 * @param integer $cid cid
300 * @param integer $start optional, default 0
301 * @param integer $limit optional, default 9999
302 * @param boolean $shuffle optional, default false
306 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
309 $sql_extra = " order by rand() ";
311 $sql_extra = " order by `gcontact`.`name` asc ";
315 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
317 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
318 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
319 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
320 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
321 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
322 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
323 $sql_extra LIMIT %d, %d",
332 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
337 * @param integer $uid user
338 * @param integer $zcid zcid
339 * @param integer $start optional, default 0
340 * @param integer $limit optional, default 9999
341 * @param boolean $shuffle optional, default false
345 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
348 $sql_extra = " order by rand() ";
350 $sql_extra = " order by `gcontact`.`name` asc ";
355 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
356 where `glink`.`zcid` = %d
357 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0)
358 $sql_extra limit %d, %d",
365 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
370 * @param integer $uid user
371 * @param integer $cid cid
375 public static function countAllFriends($uid, $cid)
378 "SELECT count(*) as `total`
379 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
380 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
381 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
386 if (DBA::isResult($r)) {
387 return $r[0]['total'];
394 * @param integer $uid user
395 * @param integer $cid cid
396 * @param integer $start optional, default 0
397 * @param integer $limit optional, default 80
401 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
404 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
406 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
407 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
408 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
409 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
410 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
418 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
423 * @param int $uid user
424 * @param integer $start optional, default 0
425 * @param integer $limit optional, default 80
427 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
429 public static function suggestionQuery($uid, $start = 0, $limit = 80)
436 * Uncommented because the result of the queries are to big to store it in the cache.
437 * We need to decide if we want to change the db column type or if we want to delete it.
439 //$list = Cache::get('suggestion_query:'.$uid.':'.$start.':'.$limit);
440 //if (!is_null($list)) {
444 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
446 if (Config::get('system', 'diaspora_enabled')) {
447 $network[] = Protocol::DIASPORA;
450 if (!Config::get('system', 'ostatus_disabled')) {
451 $network[] = Protocol::OSTATUS;
454 $sql_network = implode("', '", $network);
455 $sql_network = "'".$sql_network."'";
457 /// @todo This query is really slow
458 // By now we cache the data for five minutes
460 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
461 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
462 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
463 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
464 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
465 AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
466 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
467 AND `gcontact`.`network` IN (%s)
468 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
479 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
481 * Uncommented because the result of the queries are to big to store it in the cache.
482 * We need to decide if we want to change the db column type or if we want to delete it.
484 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, Cache::FIVE_MINUTES);
490 "SELECT gcontact.* FROM gcontact
491 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
492 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
493 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
494 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
495 AND `gcontact`.`updated` >= '%s'
496 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
497 AND `gcontact`.`network` IN (%s)
498 ORDER BY rand() LIMIT %d, %d",
509 foreach ($r2 as $suggestion) {
510 $list[$suggestion['nurl']] = $suggestion;
513 foreach ($r as $suggestion) {
514 $list[$suggestion['nurl']] = $suggestion;
517 while (sizeof($list) > ($limit)) {
522 * Uncommented because the result of the queries are to big to store it in the cache.
523 * We need to decide if we want to change the db column type or if we want to delete it.
525 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, Cache::FIVE_MINUTES);
531 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
533 public static function updateSuggestions()
537 /// @TODO Check if it is really neccessary to poll the own server
538 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
540 $done[] = System::baseUrl() . '/poco';
542 if (strlen(Config::get('system', 'directory'))) {
543 $x = Network::fetchUrl(get_server().'/pubsites');
545 $j = json_decode($x);
546 if (!empty($j->entries)) {
547 foreach ($j->entries as $entry) {
548 GServer::check($entry->url);
550 $url = $entry->url . '/poco';
551 if (!in_array($url, $done)) {
552 PortableContact::loadWorker(0, 0, 0, $url);
560 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
562 "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
563 DBA::escape(Protocol::DFRN),
564 DBA::escape(Protocol::DIASPORA)
567 if (DBA::isResult($r)) {
568 foreach ($r as $rr) {
569 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
570 if (! in_array($base, $done)) {
571 PortableContact::loadWorker(0, 0, 0, $base);
578 * @brief Removes unwanted parts from a contact url
580 * @param string $url Contact url
582 * @return string Contact url with the wanted parts
585 public static function cleanContactUrl($url)
587 $parts = parse_url($url);
589 if (!isset($parts['scheme']) || !isset($parts['host'])) {
593 $new_url = $parts['scheme'].'://'.$parts['host'];
595 if (isset($parts['port'])) {
596 $new_url .= ':'.$parts['port'];
599 if (isset($parts['path'])) {
600 $new_url .= $parts['path'];
603 if ($new_url != $url) {
604 Logger::log('Cleaned contact url '.$url.' to '.$new_url.' - Called by: '.System::callstack(), Logger::DEBUG);
611 * @brief Replace alternate OStatus user format with the primary one
613 * @param array $contact contact array (called by reference)
615 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
616 * @throws \ImagickException
618 public static function fixAlternateContactAddress(&$contact)
620 if (($contact['network'] == Protocol::OSTATUS) && PortableContact::alternateOStatusUrl($contact['url'])) {
621 $data = Probe::uri($contact['url']);
622 if ($contact['network'] == Protocol::OSTATUS) {
623 Logger::log('Fix primary url from '.$contact['url'].' to '.$data['url'].' - Called by: '.System::callstack(), Logger::DEBUG);
624 $contact['url'] = $data['url'];
625 $contact['addr'] = $data['addr'];
626 $contact['alias'] = $data['alias'];
627 $contact['server_url'] = $data['baseurl'];
633 * @brief Fetch the gcontact id, add an entry if not existed
635 * @param array $contact contact array
637 * @return bool|int Returns false if not found, integer if contact was found
638 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
639 * @throws \ImagickException
641 public static function getId($contact)
645 $last_failure_str = '';
646 $last_contact_str = '';
648 if (empty($contact['network'])) {
649 Logger::log('Empty network for contact url '.$contact['url'].' - Called by: '.System::callstack(), Logger::DEBUG);
653 if (in_array($contact['network'], [Protocol::PHANTOM])) {
654 Logger::log('Invalid network for contact url '.$contact['url'].' - Called by: '.System::callstack(), Logger::DEBUG);
658 if ($contact['network'] == Protocol::STATUSNET) {
659 $contact['network'] = Protocol::OSTATUS;
662 // All new contacts are hidden by default
663 if (!isset($contact['hide'])) {
664 $contact['hide'] = true;
667 // Replace alternate OStatus user format with the primary one
668 self::fixAlternateContactAddress($contact);
670 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
671 if (in_array($contact['network'], Protocol::FEDERATED)) {
672 $contact['url'] = self::cleanContactUrl($contact['url']);
675 DBA::lock('gcontact');
676 $fields = ['id', 'last_contact', 'last_failure', 'network'];
677 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
678 if (DBA::isResult($gcnt)) {
679 $gcontact_id = $gcnt['id'];
681 // Update every 90 days
682 if (in_array($gcnt['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ''])) {
683 $last_failure_str = $gcnt['last_failure'];
684 $last_failure = strtotime($gcnt['last_failure']);
685 $last_contact_str = $gcnt['last_contact'];
686 $last_contact = strtotime($gcnt['last_contact']);
687 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
690 $contact['location'] = $contact['location'] ?? '';
691 $contact['about'] = $contact['about'] ?? '';
692 $contact['generation'] = $contact['generation'] ?? 0;
695 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
696 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
697 DBA::escape($contact['name']),
698 DBA::escape($contact['nick']),
699 DBA::escape($contact['addr']),
700 DBA::escape($contact['network']),
701 DBA::escape($contact['url']),
702 DBA::escape(Strings::normaliseLink($contact['url'])),
703 DBA::escape($contact['photo']),
704 DBA::escape(DateTimeFormat::utcNow()),
705 DBA::escape(DateTimeFormat::utcNow()),
706 DBA::escape($contact['location']),
707 DBA::escape($contact['about']),
708 intval($contact['hide']),
709 intval($contact['generation'])
712 $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
713 $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
714 if (DBA::isResult($cnt)) {
715 $gcontact_id = $cnt['id'];
716 $doprobing = in_array($cnt['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, '']);
722 Logger::log("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact['url'], Logger::DEBUG);
723 Worker::add(PRIORITY_LOW, 'GProbe', $contact['url']);
730 * @brief Updates the gcontact table from a given array
732 * @param array $contact contact array
734 * @return bool|int Returns false if not found, integer if contact was found
735 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
736 * @throws \ImagickException
738 public static function update($contact)
740 // Check for invalid "contact-type" value
741 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
742 $contact['contact-type'] = 0;
745 /// @todo update contact table as well
747 $gcontact_id = self::getId($contact);
753 $public_contact = DBA::selectFirst('gcontact', [
754 'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'gender', 'keywords',
755 'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
756 ], ['id' => $gcontact_id]);
758 if (!DBA::isResult($public_contact)) {
762 // Get all field names
764 foreach ($public_contact as $field => $data) {
765 $fields[$field] = $data;
768 unset($fields['url']);
769 unset($fields['updated']);
770 unset($fields['hide']);
772 // Bugfix: We had an error in the storing of keywords which lead to the "0"
773 // This value is still transmitted via poco.
774 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
775 unset($contact['keywords']);
778 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
779 $public_contact['keywords'] = '';
782 // assign all unassigned fields from the database entry
783 foreach ($fields as $field => $data) {
784 if (empty($contact[$field])) {
785 $contact[$field] = $public_contact[$field];
789 if (!isset($contact['hide'])) {
790 $contact['hide'] = $public_contact['hide'];
793 $fields['hide'] = $public_contact['hide'];
795 if ($contact['network'] == Protocol::STATUSNET) {
796 $contact['network'] = Protocol::OSTATUS;
799 // Replace alternate OStatus user format with the primary one
800 self::fixAlternateContactAddress($contact);
802 if (!isset($contact['updated'])) {
803 $contact['updated'] = DateTimeFormat::utcNow();
806 if ($contact['network'] == Protocol::TWITTER) {
807 $contact['server_url'] = 'http://twitter.com';
810 if (empty($contact['server_url'])) {
811 $data = Probe::uri($contact['url']);
812 if ($data['network'] != Protocol::PHANTOM) {
813 $contact['server_url'] = $data['baseurl'];
816 $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
819 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
820 $hostname = str_replace('http://', '', $contact['server_url']);
821 $contact['addr'] = $contact['nick'] . '@' . $hostname;
824 // Check if any field changed
826 unset($fields['generation']);
828 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
829 foreach ($fields as $field => $data) {
830 if ($contact[$field] != $public_contact[$field]) {
831 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
836 if ($contact['generation'] < $public_contact['generation']) {
837 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
843 Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
844 $condition = ['`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
845 Strings::normaliseLink($contact['url']), $contact["generation"]];
846 $contact["updated"] = DateTimeFormat::utc($contact["updated"]);
849 'photo' => $contact['photo'], 'name' => $contact['name'],
850 'nick' => $contact['nick'], 'addr' => $contact['addr'],
851 'network' => $contact['network'], 'birthday' => $contact['birthday'],
852 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
853 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
854 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
855 'notify' => $contact['notify'], 'url' => $contact['url'],
856 'location' => $contact['location'], 'about' => $contact['about'],
857 'generation' => $contact['generation'], 'updated' => $contact['updated'],
858 'server_url' => $contact['server_url'], 'connect' => $contact['connect']
861 DBA::update('gcontact', $updated, $condition, $fields);
868 * Set the last date that the contact had posted something
870 * @param string $data Probing result
871 * @param bool $force force updating
873 public static function setLastUpdate(array $data, bool $force = false)
875 // Fetch the global contact
876 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
877 ['nurl' => Strings::normaliseLink($data['url'])]);
878 if (!DBA::isResult($gcontact)) {
882 if (!$force && !PortableContact::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
883 Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
887 if (self::updateFromNoScrape($data)) {
891 // When the profile doesn't have got a feed, then we exit here
892 if (empty($data['poll'])) {
896 if ($data['network'] == Protocol::ACTIVITYPUB) {
897 self::updateFromOutbox($data['poll'], $data);
899 self::updateFromFeed($data);
904 * Update a global contact via the "noscrape" endpoint
906 * @param string $data Probing result
908 * @return bool 'true' if update was successful or the server was unreachable
910 private static function updateFromNoScrape(array $data)
912 // Check the 'noscrape' endpoint when it is a Friendica server
913 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
914 Strings::normaliseLink($data['baseurl'])]);
915 if (!DBA::isResult($gserver)) {
919 $curlResult = Network::curl($gserver['noscrape'] . '/' . $data['nick']);
921 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
922 $noscrape = json_decode($curlResult->getBody(), true);
923 if (!empty($noscrape)) {
924 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
925 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
926 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
929 } elseif ($curlResult->isTimeout()) {
930 // On a timeout return the existing value, but mark the contact as failure
931 $fields = ['last_failure' => DateTimeFormat::utcNow()];
932 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
939 * Update a global contact via an ActivityPub Outbox
941 * @param string $data Probing result
943 private static function updateFromOutbox(string $feed, array $data)
945 $outbox = ActivityPub::fetchContent($feed);
946 if (empty($outbox)) {
950 if (!empty($outbox['orderedItems'])) {
951 $items = $outbox['orderedItems'];
952 } elseif (!empty($outbox['first']['orderedItems'])) {
953 $items = $outbox['first']['orderedItems'];
954 } elseif (!empty($outbox['first'])) {
955 self::updateFromOutbox($outbox['first'], $data);
963 foreach ($items as $activity) {
964 if ($last_updated < $activity['published']) {
965 $last_updated = $activity['published'];
969 if (empty($last_updated)) {
973 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
974 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
978 * Update a global contact via an XML feed
980 * @param string $data Probing result
982 private static function updateFromFeed(array $data)
984 // Search for the newest entry in the feed
985 $curlResult = Network::curl($data['poll']);
986 if (!$curlResult->isSuccess()) {
987 $fields = ['last_failure' => DateTimeFormat::utcNow()];
988 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
990 Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
994 $doc = new DOMDocument();
995 @$doc->loadXML($curlResult->getBody());
997 $xpath = new DOMXPath($doc);
998 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
1000 $entries = $xpath->query('/atom:feed/atom:entry');
1004 foreach ($entries as $entry) {
1005 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
1006 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
1007 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
1008 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
1010 if (empty($published) || empty($updated)) {
1011 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
1015 if ($last_updated < $published) {
1016 $last_updated = $published;
1019 if ($last_updated < $updated) {
1020 $last_updated = $updated;
1024 if (empty($last_updated)) {
1028 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
1029 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
1032 * @brief Updates the gcontact entry from a given public contact id
1034 * @param integer $cid contact id
1036 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1037 * @throws \ImagickException
1039 public static function updateFromPublicContactID($cid)
1041 self::updateFromPublicContact(['id' => $cid]);
1045 * @brief Updates the gcontact entry from a given public contact url
1047 * @param string $url contact url
1048 * @return integer gcontact id
1049 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1050 * @throws \ImagickException
1052 public static function updateFromPublicContactURL($url)
1054 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
1058 * @brief Helper function for updateFromPublicContactID and updateFromPublicContactURL
1060 * @param array $condition contact condition
1061 * @return integer gcontact id
1062 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1063 * @throws \ImagickException
1065 private static function updateFromPublicContact($condition)
1067 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
1068 'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
1069 'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
1070 'baseurl', 'sensitive', 'unsearchable'];
1072 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
1073 if (!DBA::isResult($contact)) {
1077 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender', 'generation',
1078 'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
1079 'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
1080 'server_url', 'nsfw', 'hide', 'id'];
1082 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
1083 $do_insert = !DBA::isResult($old_gcontact);
1090 // These fields are identical in both contact and gcontact
1091 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
1092 'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated'];
1094 foreach ($fields as $field) {
1095 $gcontact[$field] = $contact[$field];
1098 // These fields are having different names but the same content
1099 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
1100 $gcontact['nsfw'] = $contact['sensitive'];
1101 $gcontact['hide'] = $contact['unsearchable'];
1102 $gcontact['archived'] = $contact['archive'];
1103 $gcontact['archive_date'] = $contact['term-date'];
1104 $gcontact['birthday'] = $contact['bd'];
1105 $gcontact['photo'] = $contact['avatar'];
1106 $gcontact['last_contact'] = $contact['success_update'];
1107 $gcontact['last_failure'] = $contact['failure_update'];
1108 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
1110 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
1111 if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
1112 unset($gcontact[$field]);
1116 if (!$gcontact['archived']) {
1117 $gcontact['archive_date'] = DBA::NULL_DATETIME;
1120 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
1121 && ($old_gcontact['created'] <= $gcontact['created'])) {
1122 unset($gcontact['created']);
1125 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
1126 unset($gcontact['birthday']);
1129 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
1130 $gcontact['generation'] = 2; // We fetched the data directly from the other server
1134 DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
1135 return $old_gcontact['id'];
1136 } elseif (!$gcontact['archived']) {
1137 DBA::insert('gcontact', $gcontact);
1138 return DBA::lastInsertId();
1143 * @brief Updates the gcontact entry from probe
1145 * @param string $url profile link
1146 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1148 * @return boolean 'true' when contact had been updated
1150 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1151 * @throws \ImagickException
1153 public static function updateFromProbe($url, $force = false)
1155 $data = Probe::uri($url, $force);
1157 if (in_array($data['network'], [Protocol::PHANTOM])) {
1158 $fields = ['last_failure' => DateTimeFormat::utcNow()];
1159 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1160 Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
1164 $data["server_url"] = $data["baseurl"];
1166 self::update($data);
1168 // Set the date of the latest post
1169 self::setLastUpdate($data, $force);
1175 * @brief Update the gcontact entry for a given user id
1177 * @param int $uid User ID
1179 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1180 * @throws \ImagickException
1182 public static function updateForUser($uid)
1185 "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
1186 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
1187 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
1188 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
1189 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
1191 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
1192 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
1193 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
1197 if (!DBA::isResult($r)) {
1198 Logger::log('Cannot find user with uid=' . $uid, Logger::INFO);
1202 $location = Profile::formatLocation(
1203 ["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
1206 // The 'addr' field was added in 3.4.3 so it can be empty for older users
1207 if ($r[0]['addr'] != '') {
1208 $addr = $r[0]["nickname"].'@'.str_replace(["http://", "https://"], '', System::baseUrl());
1210 $addr = $r[0]['addr'];
1213 $gcontact = ['name' => $r[0]['name'], "location" => $location, 'about' => $r[0]['about'],
1214 "gender" => $r[0]["gender"], 'keywords' => $r[0]["pub_keywords"],
1215 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
1216 "notify" => $r[0]["notify"], "url" => $r[0]['url'],
1217 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
1218 "nick" => $r[0]["nickname"], 'addr' => $addr,
1219 "connect" => $addr, "server_url" => System::baseUrl(),
1220 "generation" => 1, "network" => Protocol::DFRN];
1222 self::update($gcontact);
1226 * @brief Fetches users of given GNU Social server
1228 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1230 * @param string $server Server address
1232 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1233 * @throws \ImagickException
1235 public static function fetchGsUsers($server)
1237 Logger::log("Fetching users from GNU Social server ".$server, Logger::DEBUG);
1239 $url = $server."/main/statistics";
1241 $curlResult = Network::curl($url);
1242 if (!$curlResult->isSuccess()) {
1246 $statistics = json_decode($curlResult->getBody());
1248 if (!empty($statistics->config->instance_address)) {
1249 if (!empty($statistics->config->instance_with_ssl)) {
1250 $server = "https://";
1252 $server = "http://";
1255 $server .= $statistics->config->instance_address;
1257 $hostname = $statistics->config->instance_address;
1258 } elseif (!empty($statistics->instance_address)) {
1259 if (!empty($statistics->instance_with_ssl)) {
1260 $server = "https://";
1262 $server = "http://";
1265 $server .= $statistics->instance_address;
1267 $hostname = $statistics->instance_address;
1270 if (!empty($statistics->users)) {
1271 foreach ($statistics->users as $nick => $user) {
1272 $profile_url = $server."/".$user->nickname;
1274 $contact = ["url" => $profile_url,
1275 'name' => $user->fullname,
1276 'addr' => $user->nickname."@".$hostname,
1277 "nick" => $user->nickname,
1278 "network" => Protocol::OSTATUS,
1279 "photo" => System::baseUrl()."/images/person-300.jpg"];
1281 if (isset($user->bio)) {
1282 $contact['about'] = $user->bio;
1285 self::getId($contact);
1291 * @brief Asking GNU Social server on a regular base for their user data
1293 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1294 * @throws \ImagickException
1296 public static function discoverGsUsers()
1298 $requery_days = intval(Config::get("system", "poco_requery_days"));
1300 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1302 $r = DBA::select('gserver', ['nurl', 'url'], [
1304 AND `last_contact` >= `last_failure`
1305 AND `last_poco_query` < ?',
1310 'order' => ['RAND()']
1313 if (!DBA::isResult($r)) {
1317 foreach ($r as $server) {
1318 self::fetchGsUsers($server['url']);
1319 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", DBA::escape(DateTimeFormat::utcNow()), DBA::escape($server["nurl"]));
1324 * Returns a random, global contact of the current node
1326 * @return string The profile URL
1329 public static function getRandomUrl()
1331 $r = DBA::selectFirst('gcontact', ['url'], [
1333 AND `last_contact` >= `last_failure`
1336 DateTimeFormat::utc('now - 1 month'),
1337 ], ['order' => ['RAND()']]);
1339 if (DBA::isResult($r)) {