3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Search;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Network\Probe;
35 use Friendica\Protocol\ActivityPub;
36 use Friendica\Protocol\PortableContact;
37 use Friendica\Util\DateTimeFormat;
38 use Friendica\Util\Network;
39 use Friendica\Util\Strings;
42 * This class handles GlobalContact related functions
47 * Search global contact table by nick or name
49 * @param string $search Name or nick
50 * @param string $mode Search mode (e.g. "community")
52 * @return array with search results
53 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
55 public static function searchByName($search, $mode = '')
61 // check supported networks
62 if (DI::config()->get('system', 'diaspora_enabled')) {
63 $diaspora = Protocol::DIASPORA;
65 $diaspora = Protocol::DFRN;
68 if (!DI::config()->get('system', 'ostatus_disabled')) {
69 $ostatus = Protocol::OSTATUS;
71 $ostatus = Protocol::DFRN;
74 // check if we search only communities or every contact
75 if ($mode === 'community') {
76 $extra_sql = ' AND `community`';
83 $results = DBA::p("SELECT `nurl` FROM `gcontact`
84 WHERE NOT `hide` AND `network` IN (?, ?, ?, ?) AND
86 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
87 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
88 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $search, $search, $search
92 while ($result = DBA::fetch($results)) {
93 $urlparts = parse_url($result['nurl']);
95 // Ignore results that look strange.
96 // For historic reasons the gcontact table does contain some garbage.
97 if (empty($result['nurl']) || !empty($urlparts['query']) || !empty($urlparts['fragment'])) {
101 $gcontacts[] = Contact::getByURLForUser($result['nurl'], local_user());
103 DBA::close($results);
108 * Link the gcontact entry with user, contact and global contact
110 * @param integer $gcid Global contact ID
111 * @param integer $uid User ID
112 * @param integer $cid Contact ID
113 * @param integer $zcid Global Contact ID
117 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
123 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
124 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
128 * Sanitize the given gcontact data
132 * 1: Profiles on this server
133 * 2: Contacts of profiles on this server
134 * 3: Contacts of contacts of profiles on this server
137 * @param array $gcontact array with gcontact data
138 * @return array $gcontact
141 public static function sanitize($gcontact)
143 if (empty($gcontact['url'])) {
144 throw new Exception('URL is empty');
147 $gcontact['server_url'] = $gcontact['server_url'] ?? '';
149 $urlparts = parse_url($gcontact['url']);
150 if (empty($urlparts['scheme'])) {
151 throw new Exception('This (' . $gcontact['url'] . ") doesn't seem to be an url.");
154 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
155 throw new Exception('Contact from a non federated network ignored. (' . $gcontact['url'] . ')');
158 // Don't store the statusnet connector as network
159 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
160 if ($gcontact['network'] == Protocol::STATUSNET) {
161 $gcontact['network'] = '';
164 // Assure that there are no parameter fragments in the profile url
165 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
166 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
169 // The global contacts should contain the original picture, not the cached one
170 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(DI::baseUrl() . '/photo/'))) {
171 $gcontact['photo'] = '';
174 if (empty($gcontact['network'])) {
175 $gcontact['network'] = '';
177 $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
178 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
179 $contact = DBA::selectFirst('contact', ['network'], $condition);
180 if (DBA::isResult($contact)) {
181 $gcontact['network'] = $contact['network'];
184 if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
185 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
186 $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
187 $contact = DBA::selectFirst('contact', ['network'], $condition);
188 if (DBA::isResult($contact)) {
189 $gcontact['network'] = $contact['network'];
194 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
195 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
196 if (DBA::isResult($gcnt)) {
197 if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
198 $gcontact['network'] = $gcnt['network'];
200 if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
201 $gcontact['updated'] = $gcnt['updated'];
203 if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
204 $gcontact['server_url'] = $gcnt['server_url'];
206 if (!isset($gcontact['addr'])) {
207 $gcontact['addr'] = $gcnt['addr'];
211 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']))
212 && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
214 $data = Probe::uri($gcontact['url']);
216 if ($data['network'] == Protocol::PHANTOM) {
217 throw new Exception('Probing for URL ' . $gcontact['url'] . ' failed');
220 $gcontact['server_url'] = $data['baseurl'];
221 $gcontact['failed'] = false;
223 $gcontact = array_merge($gcontact, $data);
226 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
227 throw new Exception('No name and photo for URL '.$gcontact['url']);
230 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
231 throw new Exception('No federated network (' . $gcontact['network'] . ') detected for URL ' . $gcontact['url']);
234 if (empty($gcontact['server_url'])) {
235 // We check the server url to be sure that it is a real one
236 $server_url = self::getBasepath($gcontact['url']);
238 // We are now sure that it is a correct URL. So we use it in the future
239 if ($server_url != '') {
240 $gcontact['server_url'] = $server_url;
244 // The server URL doesn't seem to be valid, so we don't store it.
245 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
246 $gcontact['server_url'] = '';
253 * @param integer $uid id
254 * @param integer $cid id
258 public static function countCommonFriends($uid, $cid)
261 "SELECT count(*) as `total`
262 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
263 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
264 NOT `gcontact`.`failed`
265 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d) ",
272 if (DBA::isResult($r)) {
273 return $r[0]['total'];
279 * @param integer $uid id
280 * @param integer $zcid zcid
284 public static function countCommonFriendsZcid($uid, $zcid)
287 "SELECT count(*) as `total`
288 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
289 where `glink`.`zcid` = %d
290 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0) ",
295 if (DBA::isResult($r)) {
296 return $r[0]['total'];
303 * @param integer $uid user
304 * @param integer $cid cid
305 * @param integer $start optional, default 0
306 * @param integer $limit optional, default 9999
307 * @param boolean $shuffle optional, default false
311 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
314 $sql_extra = " order by rand() ";
316 $sql_extra = " order by `gcontact`.`name` asc ";
320 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
322 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
323 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
324 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
325 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
326 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
327 AND NOT `gcontact`.`failed`
328 $sql_extra LIMIT %d, %d",
337 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
342 * @param integer $uid user
343 * @param integer $zcid zcid
344 * @param integer $start optional, default 0
345 * @param integer $limit optional, default 9999
346 * @param boolean $shuffle optional, default false
350 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
353 $sql_extra = " order by rand() ";
355 $sql_extra = " order by `gcontact`.`name` asc ";
360 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
361 where `glink`.`zcid` = %d
362 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0)
363 $sql_extra limit %d, %d",
370 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
375 * @param integer $uid user
376 * @param integer $cid cid
380 public static function countAllFriends($uid, $cid)
383 "SELECT count(*) as `total`
384 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
385 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
386 NOT `gcontact`.`failed`",
391 if (DBA::isResult($r)) {
392 return $r[0]['total'];
399 * @param integer $uid user
400 * @param integer $cid cid
401 * @param integer $start optional, default 0
402 * @param integer $limit optional, default 80
406 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
409 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
411 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
412 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
413 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
414 NOT `gcontact`.`failed`
415 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
423 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
428 * @param int $uid user
429 * @param integer $start optional, default 0
430 * @param integer $limit optional, default 80
432 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
434 public static function suggestionQuery($uid, $start = 0, $limit = 80)
440 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
442 if (DI::config()->get('system', 'diaspora_enabled')) {
443 $network[] = Protocol::DIASPORA;
446 if (!DI::config()->get('system', 'ostatus_disabled')) {
447 $network[] = Protocol::OSTATUS;
450 $sql_network = "'" . implode("', '", $network) . "'";
452 /// @todo This query is really slow
453 // By now we cache the data for five minutes
455 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
456 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
457 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
458 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
459 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
460 AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
461 AND NOT `gcontact`.`failed`
462 AND `gcontact`.`network` IN (%s)
463 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
474 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
479 "SELECT gcontact.* FROM gcontact
480 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
481 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
482 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
483 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
484 AND `gcontact`.`updated` >= '%s'
485 AND NOT `gcontact`.`failed`
486 AND `gcontact`.`network` IN (%s)
487 ORDER BY rand() LIMIT %d, %d",
498 foreach ($r2 as $suggestion) {
499 $list[$suggestion['nurl']] = $suggestion;
502 foreach ($r as $suggestion) {
503 $list[$suggestion['nurl']] = $suggestion;
506 while (sizeof($list) > ($limit)) {
515 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
517 public static function updateSuggestions()
521 /// @TODO Check if it is really neccessary to poll the own server
522 PortableContact::loadWorker(0, 0, 0, DI::baseUrl() . '/poco');
524 $done[] = DI::baseUrl() . '/poco';
526 if (strlen(DI::config()->get('system', 'directory'))) {
527 $x = DI::httpRequest()->fetch(Search::getGlobalDirectory() . '/pubsites');
529 $j = json_decode($x);
530 if (!empty($j->entries)) {
531 foreach ($j->entries as $entry) {
532 GServer::check($entry->url);
534 $url = $entry->url . '/poco';
535 if (!in_array($url, $done)) {
536 PortableContact::loadWorker(0, 0, 0, $url);
544 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
545 $contacts = DBA::p("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN (?, ?)", Protocol::DFRN, Protocol::DIASPORA);
546 while ($contact = DBA::fetch($contacts)) {
547 $base = substr($contact['poco'], 0, strrpos($contact['poco'], '/'));
548 if (!in_array($base, $done)) {
549 PortableContact::loadWorker(0, 0, 0, $base);
552 DBA::close($contacts);
556 * Removes unwanted parts from a contact url
558 * @param string $url Contact url
560 * @return string Contact url with the wanted parts
563 public static function cleanContactUrl($url)
565 $parts = parse_url($url);
567 if (empty($parts['scheme']) || empty($parts['host'])) {
571 $new_url = $parts['scheme'] . '://' . $parts['host'];
573 if (!empty($parts['port'])) {
574 $new_url .= ':' . $parts['port'];
577 if (!empty($parts['path'])) {
578 $new_url .= $parts['path'];
581 if ($new_url != $url) {
582 Logger::info('Cleaned contact url', ['url' => $url, 'new_url' => $new_url, 'callstack' => System::callstack()]);
589 * Fetch the gcontact id, add an entry if not existed
591 * @param array $contact contact array
593 * @return bool|int Returns false if not found, integer if contact was found
594 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
595 * @throws \ImagickException
597 public static function getId($contact)
599 if (empty($contact['network'])) {
600 Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
604 if (in_array($contact['network'], [Protocol::PHANTOM])) {
605 Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
609 if ($contact['network'] == Protocol::STATUSNET) {
610 $contact['network'] = Protocol::OSTATUS;
613 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
614 if (in_array($contact['network'], Protocol::FEDERATED)) {
615 $contact['url'] = self::cleanContactUrl($contact['url']);
618 $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
619 $gcontact = DBA::selectFirst('gcontact', ['id'], $condition, ['order' => ['id']]);
620 if (DBA::isResult($gcontact)) {
621 return $gcontact['id'];
624 $contact['location'] = $contact['location'] ?? '';
625 $contact['about'] = $contact['about'] ?? '';
626 $contact['generation'] = $contact['generation'] ?? 0;
627 $contact['hide'] = $contact['hide'] ?? true;
629 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'] ?? '', 'addr' => $contact['addr'] ?? '', 'network' => $contact['network'],
630 'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
631 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
632 'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation'], 'failed' => false];
634 DBA::insert('gcontact', $fields);
636 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
637 $gcontact = DBA::selectFirst('gcontact', ['id'], $condition, ['order' => ['id']]);
638 if (!DBA::isResult($gcontact)) {
639 Logger::info('GContact creation failed', $fields);
643 return $gcontact['id'];
647 * Updates the gcontact table from a given array
649 * @param array $contact contact array
651 * @return bool|int Returns false if not found, integer if contact was found
652 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
653 * @throws \ImagickException
655 public static function update($contact)
657 // Check for invalid "contact-type" value
658 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
659 $contact['contact-type'] = 0;
662 /// @todo update contact table as well
664 $gcontact_id = self::getId($contact);
670 $public_contact = DBA::selectFirst('gcontact', [
671 'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'keywords', 'gsid', 'failed',
672 'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
673 ], ['id' => $gcontact_id]);
675 if (!DBA::isResult($public_contact)) {
679 // Get all field names
681 foreach ($public_contact as $field => $data) {
682 $fields[$field] = $data;
685 unset($fields['url']);
686 unset($fields['updated']);
687 unset($fields['hide']);
689 // Bugfix: We had an error in the storing of keywords which lead to the "0"
690 // This value is still transmitted via poco.
691 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
692 unset($contact['keywords']);
695 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
696 $public_contact['keywords'] = '';
699 // assign all unassigned fields from the database entry
700 foreach ($fields as $field => $data) {
701 if (empty($contact[$field])) {
702 $contact[$field] = $public_contact[$field];
706 if (!isset($contact['hide'])) {
707 $contact['hide'] = $public_contact['hide'];
710 $fields['hide'] = $public_contact['hide'];
712 if ($contact['network'] == Protocol::STATUSNET) {
713 $contact['network'] = Protocol::OSTATUS;
716 if (!isset($contact['updated'])) {
717 $contact['updated'] = DateTimeFormat::utcNow();
720 if ($contact['network'] == Protocol::TWITTER) {
721 $contact['server_url'] = 'http://twitter.com';
724 if (empty($contact['server_url'])) {
725 $data = Probe::uri($contact['url']);
726 if ($data['network'] != Protocol::PHANTOM) {
727 $contact['server_url'] = $data['baseurl'];
730 $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
733 if (!empty($contact['server_url']) && empty($contact['gsid'])) {
734 $contact['gsid'] = GServer::getID($contact['server_url']);
737 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
738 $hostname = str_replace('http://', '', $contact['server_url']);
739 $contact['addr'] = $contact['nick'] . '@' . $hostname;
742 // Check if any field changed
744 unset($fields['generation']);
746 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
747 foreach ($fields as $field => $data) {
748 if ($contact[$field] != $public_contact[$field]) {
749 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
754 if ($contact['generation'] < $public_contact['generation']) {
755 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
761 Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
762 $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
763 Strings::normaliseLink($contact['url']), $contact['generation']];
764 $contact['updated'] = DateTimeFormat::utc($contact['updated']);
767 'photo' => $contact['photo'], 'name' => $contact['name'],
768 'nick' => $contact['nick'], 'addr' => $contact['addr'],
769 'network' => $contact['network'], 'birthday' => $contact['birthday'],
770 'keywords' => $contact['keywords'],
771 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
772 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
773 'notify' => $contact['notify'], 'url' => $contact['url'],
774 'location' => $contact['location'], 'about' => $contact['about'],
775 'generation' => $contact['generation'], 'updated' => $contact['updated'],
776 'server_url' => $contact['server_url'], 'connect' => $contact['connect'],
777 'failed' => $contact['failed'], 'gsid' => $contact['gsid']
780 DBA::update('gcontact', $updated, $condition, $fields);
787 * Set the last date that the contact had posted something
789 * @param string $data Probing result
790 * @param bool $force force updating
792 public static function setLastUpdate(array $data, bool $force = false)
794 // Fetch the global contact
795 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
796 ['nurl' => Strings::normaliseLink($data['url'])]);
797 if (!DBA::isResult($gcontact)) {
801 if (!$force && !GServer::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
802 Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
806 if (self::updateFromNoScrape($data)) {
810 if (!empty($data['outbox'])) {
811 self::updateFromOutbox($data['outbox'], $data);
812 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
813 self::updateFromOutbox($data['poll'], $data);
814 } elseif (!empty($data['poll'])) {
815 self::updateFromFeed($data);
820 * Update a global contact via the "noscrape" endpoint
822 * @param string $data Probing result
824 * @return bool 'true' if update was successful or the server was unreachable
826 private static function updateFromNoScrape(array $data)
828 // Check the 'noscrape' endpoint when it is a Friendica server
829 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
830 Strings::normaliseLink($data['baseurl'])]);
831 if (!DBA::isResult($gserver)) {
835 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
837 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
838 $noscrape = json_decode($curlResult->getBody(), true);
839 if (!empty($noscrape) && !empty($noscrape['updated'])) {
840 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
841 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
842 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
845 } elseif ($curlResult->isTimeout()) {
846 // On a timeout return the existing value, but mark the contact as failure
847 $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
848 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
855 * Update a global contact via an ActivityPub Outbox
857 * @param string $feed
858 * @param array $data Probing result
859 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
861 private static function updateFromOutbox(string $feed, array $data)
863 $outbox = ActivityPub::fetchContent($feed);
864 if (empty($outbox)) {
868 if (!empty($outbox['orderedItems'])) {
869 $items = $outbox['orderedItems'];
870 } elseif (!empty($outbox['first']['orderedItems'])) {
871 $items = $outbox['first']['orderedItems'];
872 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
873 self::updateFromOutbox($outbox['first']['href'], $data);
875 } elseif (!empty($outbox['first'])) {
876 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
877 self::updateFromOutbox($outbox['first'], $data);
879 Logger::warning('Unexpected data', ['outbox' => $outbox]);
887 foreach ($items as $activity) {
888 if (!empty($activity['published'])) {
889 $published = DateTimeFormat::utc($activity['published']);
890 } elseif (!empty($activity['object']['published'])) {
891 $published = DateTimeFormat::utc($activity['object']['published']);
896 if ($last_updated < $published) {
897 $last_updated = $published;
901 if (empty($last_updated)) {
905 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
906 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
910 * Update a global contact via an XML feed
912 * @param string $data Probing result
914 private static function updateFromFeed(array $data)
916 // Search for the newest entry in the feed
917 $curlResult = DI::httpRequest()->get($data['poll']);
918 if (!$curlResult->isSuccess()) {
919 $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
920 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
922 Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
926 $doc = new DOMDocument();
927 @$doc->loadXML($curlResult->getBody());
929 $xpath = new DOMXPath($doc);
930 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
932 $entries = $xpath->query('/atom:feed/atom:entry');
936 foreach ($entries as $entry) {
937 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
938 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
939 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
940 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
942 if (empty($published) || empty($updated)) {
943 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
947 if ($last_updated < $published) {
948 $last_updated = $published;
951 if ($last_updated < $updated) {
952 $last_updated = $updated;
956 if (empty($last_updated)) {
960 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
961 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
964 * Updates the gcontact entry from a given public contact id
966 * @param integer $cid contact id
968 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
969 * @throws \ImagickException
971 public static function updateFromPublicContactID($cid)
973 self::updateFromPublicContact(['id' => $cid]);
977 * Updates the gcontact entry from a given public contact url
979 * @param string $url contact url
980 * @return integer gcontact id
981 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
982 * @throws \ImagickException
984 public static function updateFromPublicContactURL($url)
986 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
990 * Helper function for updateFromPublicContactID and updateFromPublicContactURL
992 * @param array $condition contact condition
993 * @return integer gcontact id
994 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
995 * @throws \ImagickException
997 private static function updateFromPublicContact($condition)
999 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords',
1000 'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
1001 'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
1002 'baseurl', 'gsid', 'sensitive', 'unsearchable', 'failed'];
1004 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
1005 if (!DBA::isResult($contact)) {
1009 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'generation',
1010 'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
1011 'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
1012 'server_url', 'gsid', 'nsfw', 'hide', 'id', 'failed'];
1014 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
1015 $do_insert = !DBA::isResult($old_gcontact);
1022 // These fields are identical in both contact and gcontact
1023 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gsid',
1024 'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated', 'failed'];
1026 foreach ($fields as $field) {
1027 $gcontact[$field] = $contact[$field];
1030 // These fields are having different names but the same content
1031 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
1032 $gcontact['nsfw'] = $contact['sensitive'];
1033 $gcontact['hide'] = $contact['unsearchable'];
1034 $gcontact['archived'] = $contact['archive'];
1035 $gcontact['archive_date'] = $contact['term-date'];
1036 $gcontact['birthday'] = $contact['bd'];
1037 $gcontact['photo'] = $contact['avatar'];
1038 $gcontact['last_contact'] = $contact['success_update'];
1039 $gcontact['last_failure'] = $contact['failure_update'];
1040 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
1042 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
1043 if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
1044 unset($gcontact[$field]);
1048 if (!$gcontact['archived']) {
1049 $gcontact['archive_date'] = DBA::NULL_DATETIME;
1052 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
1053 && ($old_gcontact['created'] <= $gcontact['created'])) {
1054 unset($gcontact['created']);
1057 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
1058 unset($gcontact['birthday']);
1061 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
1062 $gcontact['generation'] = 2; // We fetched the data directly from the other server
1066 DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
1067 return $old_gcontact['id'];
1068 } elseif (!$gcontact['archived']) {
1069 DBA::insert('gcontact', $gcontact);
1070 return DBA::lastInsertId();
1075 * Updates the gcontact entry from probe
1077 * @param string $url profile link
1078 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1080 * @return boolean 'true' when contact had been updated
1082 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1083 * @throws \ImagickException
1085 public static function updateFromProbe($url, $force = false)
1087 $data = Probe::uri($url, $force);
1089 if (in_array($data['network'], [Protocol::PHANTOM])) {
1090 $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
1091 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1092 Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
1096 $data['server_url'] = $data['baseurl'];
1097 $data['failed'] = false;
1099 self::update($data);
1101 // Set the date of the latest post
1102 self::setLastUpdate($data, $force);
1108 * Update the gcontact entry for a given user id
1110 * @param int $uid User ID
1112 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1113 * @throws \ImagickException
1115 public static function updateForUser($uid)
1117 $profile = Profile::getByUID($uid);
1118 if (empty($profile)) {
1119 Logger::error('Cannot find profile', ['uid' => $uid]);
1123 $user = User::getOwnerDataById($uid);
1125 Logger::error('Cannot find user', ['uid' => $uid]);
1129 $userdata = array_merge($profile, $user);
1131 $location = Profile::formatLocation(
1132 ['locality' => $userdata['locality'], 'region' => $userdata['region'], 'country-name' => $userdata['country-name']]
1135 $gcontact = ['name' => $userdata['name'], 'location' => $location, 'about' => $userdata['about'],
1136 'keywords' => $userdata['pub_keywords'],
1137 'birthday' => $userdata['dob'], 'photo' => $userdata['photo'],
1138 "notify" => $userdata['notify'], 'url' => $userdata['url'],
1139 "hide" => !$userdata['net-publish'],
1140 'nick' => $userdata['nickname'], 'addr' => $userdata['addr'],
1141 "connect" => $userdata['addr'], "server_url" => DI::baseUrl(),
1142 "generation" => 1, 'network' => Protocol::DFRN];
1144 self::update($gcontact);
1148 * Get the basepath for a given contact link
1150 * @param string $url The gcontact link
1151 * @param boolean $dont_update Don't update the contact
1153 * @return string basepath
1154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1155 * @throws \ImagickException
1157 public static function getBasepath($url, $dont_update = false)
1159 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1160 if (!empty($gcontact['server_url'])) {
1161 return $gcontact['server_url'];
1162 } elseif ($dont_update) {
1166 self::updateFromProbe($url, true);
1169 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1170 if (empty($gcontact['server_url'])) {
1171 Logger::info('No baseurl for gcontact', ['url' => $url]);
1175 Logger::info('Found baseurl for gcontact', ['url' => $url, 'baseurl' => $gcontact['server_url']]);
1176 return $gcontact['server_url'];
1180 * Fetches users of given GNU Social server
1182 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1184 * @param string $server Server address
1186 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1187 * @throws \ImagickException
1189 public static function fetchGsUsers($server)
1191 Logger::info('Fetching users from GNU Social server', ['server' => $server]);
1193 $url = $server . '/main/statistics';
1195 $curlResult = DI::httpRequest()->get($url);
1196 if (!$curlResult->isSuccess()) {
1200 $statistics = json_decode($curlResult->getBody());
1202 if (!empty($statistics->config->instance_address)) {
1203 if (!empty($statistics->config->instance_with_ssl)) {
1204 $server = 'https://';
1206 $server = 'http://';
1209 $server .= $statistics->config->instance_address;
1211 $hostname = $statistics->config->instance_address;
1212 } elseif (!empty($statistics->instance_address)) {
1213 if (!empty($statistics->instance_with_ssl)) {
1214 $server = 'https://';
1216 $server = 'http://';
1219 $server .= $statistics->instance_address;
1221 $hostname = $statistics->instance_address;
1224 if (!empty($statistics->users)) {
1225 foreach ($statistics->users as $nick => $user) {
1226 $profile_url = $server . '/' . $user->nickname;
1228 $contact = ['url' => $profile_url,
1229 'name' => $user->fullname,
1230 'addr' => $user->nickname . '@' . $hostname,
1231 'nick' => $user->nickname,
1232 "network" => Protocol::OSTATUS,
1233 'photo' => DI::baseUrl() . '/images/person-300.jpg'];
1235 if (isset($user->bio)) {
1236 $contact['about'] = $user->bio;
1239 self::getId($contact);
1245 * Asking GNU Social server on a regular base for their user data
1248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1249 * @throws \ImagickException
1251 public static function discoverGsUsers()
1253 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1255 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1257 $r = DBA::select('gserver', ['nurl', 'url'], [
1260 AND `last_poco_query` < ?',
1265 'order' => ['RAND()']
1268 if (!DBA::isResult($r)) {
1272 foreach ($r as $server) {
1273 self::fetchGsUsers($server['url']);
1274 DBA::update('gserver', ['last_poco_query' => DateTimeFormat::utcNow()], ['nurl' => $server['nurl']]);
1279 * Returns a random, global contact of the current node
1281 * @return string The profile URL
1284 public static function getRandomUrl()
1286 $r = DBA::selectFirst('gcontact', ['url'], [
1291 DateTimeFormat::utc('now - 1 month'),
1292 ], ['order' => ['RAND()']]);
1294 if (DBA::isResult($r)) {