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\System;
30 use Friendica\Core\Search;
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 * No discovery of followers/followings
49 const DISCOVERY_NONE = 0;
51 * Only discover followers/followings from direct contacts
53 const DISCOVERY_DIRECT = 1;
55 * Recursive discovery of followers/followings
57 const DISCOVERY_RECURSIVE = 2;
60 * Search global contact table by nick or name
62 * @param string $search Name or nick
63 * @param string $mode Search mode (e.g. "community")
65 * @return array with search results
66 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
68 public static function searchByName($search, $mode = '')
74 // check supported networks
75 if (DI::config()->get('system', 'diaspora_enabled')) {
76 $diaspora = Protocol::DIASPORA;
78 $diaspora = Protocol::DFRN;
81 if (!DI::config()->get('system', 'ostatus_disabled')) {
82 $ostatus = Protocol::OSTATUS;
84 $ostatus = Protocol::DFRN;
87 // check if we search only communities or every contact
88 if ($mode === 'community') {
89 $extra_sql = ' AND `community`';
96 $results = DBA::p("SELECT `nurl` FROM `gcontact`
97 WHERE NOT `hide` AND `network` IN (?, ?, ?, ?) AND
98 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
99 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
100 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
101 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $search, $search, $search
105 while ($result = DBA::fetch($results)) {
106 $urlparts = parse_url($result['nurl']);
108 // Ignore results that look strange.
109 // For historic reasons the gcontact table does contain some garbage.
110 if (empty($result['nurl']) || !empty($urlparts['query']) || !empty($urlparts['fragment'])) {
114 $gcontacts[] = Contact::getByURLForUser($result['nurl'], local_user());
116 DBA::close($results);
121 * Link the gcontact entry with user, contact and global contact
123 * @param integer $gcid Global contact ID
124 * @param integer $uid User ID
125 * @param integer $cid Contact ID
126 * @param integer $zcid Global Contact ID
130 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
136 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
137 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
141 * Sanitize the given gcontact data
145 * 1: Profiles on this server
146 * 2: Contacts of profiles on this server
147 * 3: Contacts of contacts of profiles on this server
150 * @param array $gcontact array with gcontact data
151 * @return array $gcontact
154 public static function sanitize($gcontact)
156 if (empty($gcontact['url'])) {
157 throw new Exception('URL is empty');
160 $gcontact['server_url'] = $gcontact['server_url'] ?? '';
162 $urlparts = parse_url($gcontact['url']);
163 if (empty($urlparts['scheme'])) {
164 throw new Exception('This (' . $gcontact['url'] . ") doesn't seem to be an url.");
167 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
168 throw new Exception('Contact from a non federated network ignored. (' . $gcontact['url'] . ')');
171 // Don't store the statusnet connector as network
172 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
173 if ($gcontact['network'] == Protocol::STATUSNET) {
174 $gcontact['network'] = '';
177 // Assure that there are no parameter fragments in the profile url
178 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
179 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
182 // The global contacts should contain the original picture, not the cached one
183 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(DI::baseUrl() . '/photo/'))) {
184 $gcontact['photo'] = '';
187 if (empty($gcontact['network'])) {
188 $gcontact['network'] = '';
190 $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
191 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
192 $contact = DBA::selectFirst('contact', ['network'], $condition);
193 if (DBA::isResult($contact)) {
194 $gcontact['network'] = $contact['network'];
197 if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
198 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
199 $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
200 $contact = DBA::selectFirst('contact', ['network'], $condition);
201 if (DBA::isResult($contact)) {
202 $gcontact['network'] = $contact['network'];
207 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
208 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
209 if (DBA::isResult($gcnt)) {
210 if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
211 $gcontact['network'] = $gcnt['network'];
213 if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
214 $gcontact['updated'] = $gcnt['updated'];
216 if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
217 $gcontact['server_url'] = $gcnt['server_url'];
219 if (!isset($gcontact['addr'])) {
220 $gcontact['addr'] = $gcnt['addr'];
224 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']))
225 && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
227 $data = Probe::uri($gcontact['url']);
229 if ($data['network'] == Protocol::PHANTOM) {
230 throw new Exception('Probing for URL ' . $gcontact['url'] . ' failed');
233 $gcontact['server_url'] = $data['baseurl'];
235 $gcontact = array_merge($gcontact, $data);
238 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
239 throw new Exception('No name and photo for URL '.$gcontact['url']);
242 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
243 throw new Exception('No federated network (' . $gcontact['network'] . ') detected for URL ' . $gcontact['url']);
246 if (empty($gcontact['server_url'])) {
247 // We check the server url to be sure that it is a real one
248 $server_url = self::getBasepath($gcontact['url']);
250 // We are now sure that it is a correct URL. So we use it in the future
251 if ($server_url != '') {
252 $gcontact['server_url'] = $server_url;
256 // The server URL doesn't seem to be valid, so we don't store it.
257 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
258 $gcontact['server_url'] = '';
265 * @param integer $uid id
266 * @param integer $cid id
270 public static function countCommonFriends($uid, $cid)
273 "SELECT count(*) as `total`
274 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
275 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
276 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
277 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
278 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d) ",
285 if (DBA::isResult($r)) {
286 return $r[0]['total'];
292 * @param integer $uid id
293 * @param integer $zcid zcid
297 public static function countCommonFriendsZcid($uid, $zcid)
300 "SELECT count(*) as `total`
301 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
302 where `glink`.`zcid` = %d
303 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0) ",
308 if (DBA::isResult($r)) {
309 return $r[0]['total'];
316 * @param integer $uid user
317 * @param integer $cid cid
318 * @param integer $start optional, default 0
319 * @param integer $limit optional, default 9999
320 * @param boolean $shuffle optional, default false
324 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
327 $sql_extra = " order by rand() ";
329 $sql_extra = " order by `gcontact`.`name` asc ";
333 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
335 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
336 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
337 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
338 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
339 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
340 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
341 $sql_extra LIMIT %d, %d",
350 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
355 * @param integer $uid user
356 * @param integer $zcid zcid
357 * @param integer $start optional, default 0
358 * @param integer $limit optional, default 9999
359 * @param boolean $shuffle optional, default false
363 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
366 $sql_extra = " order by rand() ";
368 $sql_extra = " order by `gcontact`.`name` asc ";
373 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
374 where `glink`.`zcid` = %d
375 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0)
376 $sql_extra limit %d, %d",
383 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
388 * @param integer $uid user
389 * @param integer $cid cid
393 public static function countAllFriends($uid, $cid)
396 "SELECT count(*) as `total`
397 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
398 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
399 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
404 if (DBA::isResult($r)) {
405 return $r[0]['total'];
412 * @param integer $uid user
413 * @param integer $cid cid
414 * @param integer $start optional, default 0
415 * @param integer $limit optional, default 80
419 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
422 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
424 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
425 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
426 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
427 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
428 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
436 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
441 * @param int $uid user
442 * @param integer $start optional, default 0
443 * @param integer $limit optional, default 80
445 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
447 public static function suggestionQuery($uid, $start = 0, $limit = 80)
453 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
455 if (DI::config()->get('system', 'diaspora_enabled')) {
456 $network[] = Protocol::DIASPORA;
459 if (!DI::config()->get('system', 'ostatus_disabled')) {
460 $network[] = Protocol::OSTATUS;
463 $sql_network = "'" . implode("', '", $network) . "'";
465 /// @todo This query is really slow
466 // By now we cache the data for five minutes
468 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
469 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
470 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
471 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
472 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
473 AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
474 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
475 AND `gcontact`.`network` IN (%s)
476 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
487 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
492 "SELECT gcontact.* FROM gcontact
493 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
494 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
495 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
496 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
497 AND `gcontact`.`updated` >= '%s'
498 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
499 AND `gcontact`.`network` IN (%s)
500 ORDER BY rand() LIMIT %d, %d",
511 foreach ($r2 as $suggestion) {
512 $list[$suggestion['nurl']] = $suggestion;
515 foreach ($r as $suggestion) {
516 $list[$suggestion['nurl']] = $suggestion;
519 while (sizeof($list) > ($limit)) {
528 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
530 public static function updateSuggestions()
534 /// @TODO Check if it is really neccessary to poll the own server
535 PortableContact::loadWorker(0, 0, 0, DI::baseUrl() . '/poco');
537 $done[] = DI::baseUrl() . '/poco';
539 if (strlen(DI::config()->get('system', 'directory'))) {
540 $x = Network::fetchUrl(Search::getGlobalDirectory() . '/pubsites');
542 $j = json_decode($x);
543 if (!empty($j->entries)) {
544 foreach ($j->entries as $entry) {
545 GServer::check($entry->url);
547 $url = $entry->url . '/poco';
548 if (!in_array($url, $done)) {
549 PortableContact::loadWorker(0, 0, 0, $url);
557 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
558 $contacts = DBA::p("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN (?, ?)", Protocol::DFRN, Protocol::DIASPORA);
559 while ($contact = DBA::fetch($contacts)) {
560 $base = substr($contact['poco'], 0, strrpos($contact['poco'], '/'));
561 if (!in_array($base, $done)) {
562 PortableContact::loadWorker(0, 0, 0, $base);
565 DBA::close($contacts);
569 * Removes unwanted parts from a contact url
571 * @param string $url Contact url
573 * @return string Contact url with the wanted parts
576 public static function cleanContactUrl($url)
578 $parts = parse_url($url);
580 if (empty($parts['scheme']) || empty($parts['host'])) {
584 $new_url = $parts['scheme'] . '://' . $parts['host'];
586 if (!empty($parts['port'])) {
587 $new_url .= ':' . $parts['port'];
590 if (!empty($parts['path'])) {
591 $new_url .= $parts['path'];
594 if ($new_url != $url) {
595 Logger::info('Cleaned contact url', ['url' => $url, 'new_url' => $new_url, 'callstack' => System::callstack()]);
602 * Fetch the gcontact id, add an entry if not existed
604 * @param array $contact contact array
606 * @return bool|int Returns false if not found, integer if contact was found
607 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
608 * @throws \ImagickException
610 public static function getId($contact)
612 if (empty($contact['network'])) {
613 Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
617 if (in_array($contact['network'], [Protocol::PHANTOM])) {
618 Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
622 if ($contact['network'] == Protocol::STATUSNET) {
623 $contact['network'] = Protocol::OSTATUS;
626 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
627 if (in_array($contact['network'], Protocol::FEDERATED)) {
628 $contact['url'] = self::cleanContactUrl($contact['url']);
631 $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
632 $gcontact = DBA::selectFirst('gcontact', ['id'], $condition, ['order' => ['id']]);
633 if (DBA::isResult($gcontact)) {
634 return $gcontact['id'];
637 $contact['location'] = $contact['location'] ?? '';
638 $contact['about'] = $contact['about'] ?? '';
639 $contact['generation'] = $contact['generation'] ?? 0;
640 $contact['hide'] = $contact['hide'] ?? true;
642 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'] ?? '', 'addr' => $contact['addr'] ?? '', 'network' => $contact['network'],
643 'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
644 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
645 'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation']];
647 DBA::insert('gcontact', $fields);
649 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
650 $gcontact = DBA::selectFirst('gcontact', ['id'], $condition, ['order' => ['id']]);
651 if (!DBA::isResult($gcontact)) {
652 Logger::info('GContact creation failed', $fields);
656 return $gcontact['id'];
660 * Updates the gcontact table from a given array
662 * @param array $contact contact array
664 * @return bool|int Returns false if not found, integer if contact was found
665 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
666 * @throws \ImagickException
668 public static function update($contact)
670 // Check for invalid "contact-type" value
671 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
672 $contact['contact-type'] = 0;
675 /// @todo update contact table as well
677 $gcontact_id = self::getId($contact);
683 $public_contact = DBA::selectFirst('gcontact', [
684 'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'keywords', 'gsid',
685 'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
686 ], ['id' => $gcontact_id]);
688 if (!DBA::isResult($public_contact)) {
692 // Get all field names
694 foreach ($public_contact as $field => $data) {
695 $fields[$field] = $data;
698 unset($fields['url']);
699 unset($fields['updated']);
700 unset($fields['hide']);
702 // Bugfix: We had an error in the storing of keywords which lead to the "0"
703 // This value is still transmitted via poco.
704 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
705 unset($contact['keywords']);
708 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
709 $public_contact['keywords'] = '';
712 // assign all unassigned fields from the database entry
713 foreach ($fields as $field => $data) {
714 if (empty($contact[$field])) {
715 $contact[$field] = $public_contact[$field];
719 if (!isset($contact['hide'])) {
720 $contact['hide'] = $public_contact['hide'];
723 $fields['hide'] = $public_contact['hide'];
725 if ($contact['network'] == Protocol::STATUSNET) {
726 $contact['network'] = Protocol::OSTATUS;
729 if (!isset($contact['updated'])) {
730 $contact['updated'] = DateTimeFormat::utcNow();
733 if ($contact['network'] == Protocol::TWITTER) {
734 $contact['server_url'] = 'http://twitter.com';
737 if (empty($contact['server_url'])) {
738 $data = Probe::uri($contact['url']);
739 if ($data['network'] != Protocol::PHANTOM) {
740 $contact['server_url'] = $data['baseurl'];
743 $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
746 if (!empty($contact['server_url']) && empty($contact['gsid'])) {
747 $contact['gsid'] = GServer::getID($contact['server_url']);
750 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
751 $hostname = str_replace('http://', '', $contact['server_url']);
752 $contact['addr'] = $contact['nick'] . '@' . $hostname;
755 // Check if any field changed
757 unset($fields['generation']);
759 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
760 foreach ($fields as $field => $data) {
761 if ($contact[$field] != $public_contact[$field]) {
762 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
767 if ($contact['generation'] < $public_contact['generation']) {
768 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
774 Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
775 $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
776 Strings::normaliseLink($contact['url']), $contact['generation']];
777 $contact['updated'] = DateTimeFormat::utc($contact['updated']);
780 'photo' => $contact['photo'], 'name' => $contact['name'],
781 'nick' => $contact['nick'], 'addr' => $contact['addr'],
782 'network' => $contact['network'], 'birthday' => $contact['birthday'],
783 'keywords' => $contact['keywords'],
784 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
785 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
786 'notify' => $contact['notify'], 'url' => $contact['url'],
787 'location' => $contact['location'], 'about' => $contact['about'],
788 'generation' => $contact['generation'], 'updated' => $contact['updated'],
789 'server_url' => $contact['server_url'], 'connect' => $contact['connect'],
790 'gsid' => $contact['gsid']
793 DBA::update('gcontact', $updated, $condition, $fields);
800 * Set the last date that the contact had posted something
802 * @param string $data Probing result
803 * @param bool $force force updating
805 public static function setLastUpdate(array $data, bool $force = false)
807 // Fetch the global contact
808 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
809 ['nurl' => Strings::normaliseLink($data['url'])]);
810 if (!DBA::isResult($gcontact)) {
814 if (!$force && !GServer::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
815 Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
819 if (self::updateFromNoScrape($data)) {
823 if (!empty($data['outbox'])) {
824 self::updateFromOutbox($data['outbox'], $data);
825 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
826 self::updateFromOutbox($data['poll'], $data);
827 } elseif (!empty($data['poll'])) {
828 self::updateFromFeed($data);
833 * Update a global contact via the "noscrape" endpoint
835 * @param string $data Probing result
837 * @return bool 'true' if update was successful or the server was unreachable
839 private static function updateFromNoScrape(array $data)
841 // Check the 'noscrape' endpoint when it is a Friendica server
842 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
843 Strings::normaliseLink($data['baseurl'])]);
844 if (!DBA::isResult($gserver)) {
848 $curlResult = Network::curl($gserver['noscrape'] . '/' . $data['nick']);
850 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
851 $noscrape = json_decode($curlResult->getBody(), true);
852 if (!empty($noscrape) && !empty($noscrape['updated'])) {
853 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
854 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
855 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
858 } elseif ($curlResult->isTimeout()) {
859 // On a timeout return the existing value, but mark the contact as failure
860 $fields = ['last_failure' => DateTimeFormat::utcNow()];
861 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
868 * Update a global contact via an ActivityPub Outbox
870 * @param string $feed
871 * @param array $data Probing result
872 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
874 private static function updateFromOutbox(string $feed, array $data)
876 $outbox = ActivityPub::fetchContent($feed);
877 if (empty($outbox)) {
881 if (!empty($outbox['orderedItems'])) {
882 $items = $outbox['orderedItems'];
883 } elseif (!empty($outbox['first']['orderedItems'])) {
884 $items = $outbox['first']['orderedItems'];
885 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
886 self::updateFromOutbox($outbox['first']['href'], $data);
888 } elseif (!empty($outbox['first'])) {
889 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
890 self::updateFromOutbox($outbox['first'], $data);
892 Logger::warning('Unexpected data', ['outbox' => $outbox]);
900 foreach ($items as $activity) {
901 if (!empty($activity['published'])) {
902 $published = DateTimeFormat::utc($activity['published']);
903 } elseif (!empty($activity['object']['published'])) {
904 $published = DateTimeFormat::utc($activity['object']['published']);
909 if ($last_updated < $published) {
910 $last_updated = $published;
914 if (empty($last_updated)) {
918 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
919 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
923 * Update a global contact via an XML feed
925 * @param string $data Probing result
927 private static function updateFromFeed(array $data)
929 // Search for the newest entry in the feed
930 $curlResult = Network::curl($data['poll']);
931 if (!$curlResult->isSuccess()) {
932 $fields = ['last_failure' => DateTimeFormat::utcNow()];
933 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
935 Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
939 $doc = new DOMDocument();
940 @$doc->loadXML($curlResult->getBody());
942 $xpath = new DOMXPath($doc);
943 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
945 $entries = $xpath->query('/atom:feed/atom:entry');
949 foreach ($entries as $entry) {
950 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
951 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
952 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
953 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
955 if (empty($published) || empty($updated)) {
956 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
960 if ($last_updated < $published) {
961 $last_updated = $published;
964 if ($last_updated < $updated) {
965 $last_updated = $updated;
969 if (empty($last_updated)) {
973 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
974 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
977 * Updates the gcontact entry from a given public contact id
979 * @param integer $cid contact id
981 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
982 * @throws \ImagickException
984 public static function updateFromPublicContactID($cid)
986 self::updateFromPublicContact(['id' => $cid]);
990 * Updates the gcontact entry from a given public contact url
992 * @param string $url contact url
993 * @return integer gcontact id
994 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
995 * @throws \ImagickException
997 public static function updateFromPublicContactURL($url)
999 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
1003 * Helper function for updateFromPublicContactID and updateFromPublicContactURL
1005 * @param array $condition contact condition
1006 * @return integer gcontact id
1007 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1008 * @throws \ImagickException
1010 private static function updateFromPublicContact($condition)
1012 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords',
1013 'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
1014 'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
1015 'baseurl', 'gsid', 'sensitive', 'unsearchable'];
1017 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
1018 if (!DBA::isResult($contact)) {
1022 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'generation',
1023 'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
1024 'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
1025 'server_url', 'gsid', 'nsfw', 'hide', 'id'];
1027 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
1028 $do_insert = !DBA::isResult($old_gcontact);
1035 // These fields are identical in both contact and gcontact
1036 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gsid',
1037 'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated'];
1039 foreach ($fields as $field) {
1040 $gcontact[$field] = $contact[$field];
1043 // These fields are having different names but the same content
1044 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
1045 $gcontact['nsfw'] = $contact['sensitive'];
1046 $gcontact['hide'] = $contact['unsearchable'];
1047 $gcontact['archived'] = $contact['archive'];
1048 $gcontact['archive_date'] = $contact['term-date'];
1049 $gcontact['birthday'] = $contact['bd'];
1050 $gcontact['photo'] = $contact['avatar'];
1051 $gcontact['last_contact'] = $contact['success_update'];
1052 $gcontact['last_failure'] = $contact['failure_update'];
1053 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
1055 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
1056 if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
1057 unset($gcontact[$field]);
1061 if (!$gcontact['archived']) {
1062 $gcontact['archive_date'] = DBA::NULL_DATETIME;
1065 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
1066 && ($old_gcontact['created'] <= $gcontact['created'])) {
1067 unset($gcontact['created']);
1070 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
1071 unset($gcontact['birthday']);
1074 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
1075 $gcontact['generation'] = 2; // We fetched the data directly from the other server
1079 DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
1080 return $old_gcontact['id'];
1081 } elseif (!$gcontact['archived']) {
1082 DBA::insert('gcontact', $gcontact);
1083 return DBA::lastInsertId();
1088 * Updates the gcontact entry from probe
1090 * @param string $url profile link
1091 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1093 * @return boolean 'true' when contact had been updated
1095 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1096 * @throws \ImagickException
1098 public static function updateFromProbe($url, $force = false)
1100 $data = Probe::uri($url, $force);
1102 if (in_array($data['network'], [Protocol::PHANTOM])) {
1103 $fields = ['last_failure' => DateTimeFormat::utcNow()];
1104 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1105 Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
1109 $data['server_url'] = $data['baseurl'];
1111 self::update($data);
1113 // Set the date of the latest post
1114 self::setLastUpdate($data, $force);
1120 * Update the gcontact entry for a given user id
1122 * @param int $uid User ID
1124 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1125 * @throws \ImagickException
1127 public static function updateForUser($uid)
1129 $profile = Profile::getByUID($uid);
1130 if (empty($profile)) {
1131 Logger::error('Cannot find profile', ['uid' => $uid]);
1135 $user = User::getOwnerDataById($uid);
1137 Logger::error('Cannot find user', ['uid' => $uid]);
1141 $userdata = array_merge($profile, $user);
1143 $location = Profile::formatLocation(
1144 ['locality' => $userdata['locality'], 'region' => $userdata['region'], 'country-name' => $userdata['country-name']]
1147 $gcontact = ['name' => $userdata['name'], 'location' => $location, 'about' => $userdata['about'],
1148 'keywords' => $userdata['pub_keywords'],
1149 'birthday' => $userdata['dob'], 'photo' => $userdata['photo'],
1150 "notify" => $userdata['notify'], 'url' => $userdata['url'],
1151 "hide" => !$userdata['net-publish'],
1152 'nick' => $userdata['nickname'], 'addr' => $userdata['addr'],
1153 "connect" => $userdata['addr'], "server_url" => DI::baseUrl(),
1154 "generation" => 1, 'network' => Protocol::DFRN];
1156 self::update($gcontact);
1160 * Get the basepath for a given contact link
1162 * @param string $url The gcontact link
1163 * @param boolean $dont_update Don't update the contact
1165 * @return string basepath
1166 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1167 * @throws \ImagickException
1169 public static function getBasepath($url, $dont_update = false)
1171 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1172 if (!empty($gcontact['server_url'])) {
1173 return $gcontact['server_url'];
1174 } elseif ($dont_update) {
1178 self::updateFromProbe($url, true);
1181 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1182 if (empty($gcontact['server_url'])) {
1183 Logger::info('No baseurl for gcontact', ['url' => $url]);
1187 Logger::info('Found baseurl for gcontact', ['url' => $url, 'baseurl' => $gcontact['server_url']]);
1188 return $gcontact['server_url'];
1192 * Fetches users of given GNU Social server
1194 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1196 * @param string $server Server address
1198 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1199 * @throws \ImagickException
1201 public static function fetchGsUsers($server)
1203 Logger::info('Fetching users from GNU Social server', ['server' => $server]);
1205 $url = $server . '/main/statistics';
1207 $curlResult = Network::curl($url);
1208 if (!$curlResult->isSuccess()) {
1212 $statistics = json_decode($curlResult->getBody());
1214 if (!empty($statistics->config->instance_address)) {
1215 if (!empty($statistics->config->instance_with_ssl)) {
1216 $server = 'https://';
1218 $server = 'http://';
1221 $server .= $statistics->config->instance_address;
1223 $hostname = $statistics->config->instance_address;
1224 } elseif (!empty($statistics->instance_address)) {
1225 if (!empty($statistics->instance_with_ssl)) {
1226 $server = 'https://';
1228 $server = 'http://';
1231 $server .= $statistics->instance_address;
1233 $hostname = $statistics->instance_address;
1236 if (!empty($statistics->users)) {
1237 foreach ($statistics->users as $nick => $user) {
1238 $profile_url = $server . '/' . $user->nickname;
1240 $contact = ['url' => $profile_url,
1241 'name' => $user->fullname,
1242 'addr' => $user->nickname . '@' . $hostname,
1243 'nick' => $user->nickname,
1244 "network" => Protocol::OSTATUS,
1245 'photo' => DI::baseUrl() . '/images/person-300.jpg'];
1247 if (isset($user->bio)) {
1248 $contact['about'] = $user->bio;
1251 self::getId($contact);
1257 * Asking GNU Social server on a regular base for their user data
1260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1261 * @throws \ImagickException
1263 public static function discoverGsUsers()
1265 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1267 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1269 $r = DBA::select('gserver', ['nurl', 'url'], [
1271 AND `last_contact` >= `last_failure`
1272 AND `last_poco_query` < ?',
1277 'order' => ['RAND()']
1280 if (!DBA::isResult($r)) {
1284 foreach ($r as $server) {
1285 self::fetchGsUsers($server['url']);
1286 DBA::update('gserver', ['last_poco_query' => DateTimeFormat::utcNow()], ['nurl' => $server['nurl']]);
1291 * Fetches the followers of a given profile and adds them
1293 * @param string $url URL of a profile
1296 public static function discoverFollowers(string $url)
1298 $gcontact = DBA::selectFirst('gcontact', ['id', 'last_discovery'], ['nurl' => Strings::normaliseLink(($url))]);
1299 if (!DBA::isResult($gcontact)) {
1303 if ($gcontact['last_discovery'] > DateTimeFormat::utc('now - 1 month')) {
1304 Logger::info('Last discovery was less then a month before.', ['url' => $url, 'discovery' => $gcontact['last_discovery']]);
1308 $gcid = $gcontact['id'];
1310 $apcontact = APContact::getByURL($url);
1312 if (!empty($apcontact['followers']) && is_string($apcontact['followers'])) {
1313 $followers = ActivityPub::fetchItems($apcontact['followers']);
1318 if (!empty($apcontact['following']) && is_string($apcontact['following'])) {
1319 $followings = ActivityPub::fetchItems($apcontact['following']);
1324 if (!empty($followers) || !empty($followings)) {
1325 if (!empty($followers)) {
1326 // Clear the follower list, since it will be recreated in the next step
1327 DBA::update('gfollower', ['deleted' => true], ['gcid' => $gcid]);
1331 foreach (array_merge($followers, $followings) as $contact) {
1332 if (is_string($contact)) {
1333 $contacts[] = $contact;
1334 } elseif (!empty($contact['url']) && is_string($contact['url'])) {
1335 $contacts[] = $contact['url'];
1338 $contacts = array_unique($contacts);
1340 Logger::info('Discover AP contacts', ['url' => $url, 'contacts' => count($contacts)]);
1341 foreach ($contacts as $contact) {
1342 $gcontact = DBA::selectFirst('gcontact', ['id'], ['nurl' => Strings::normaliseLink(($contact))]);
1343 if (DBA::isResult($gcontact)) {
1345 if (in_array($contact, $followers)) {
1346 $fields = ['gcid' => $gcid, 'follower-gcid' => $gcontact['id']];
1347 } elseif (in_array($contact, $followings)) {
1348 $fields = ['gcid' => $gcontact['id'], 'follower-gcid' => $gcid];
1351 if (!empty($fields)) {
1352 Logger::info('Set relation between contacts', $fields);
1353 DBA::update('gfollower', ['deleted' => false], $fields, true);
1358 if (!Network::isUrlBlocked($contact)) {
1359 Logger::info('Discover new AP contact', ['url' => $contact]);
1360 Worker::add(PRIORITY_LOW, 'UpdateGContact', $contact, 'nodiscover');
1362 Logger::info('No discovery, the URL is blocked.', ['url' => $contact]);
1365 if (!empty($followers)) {
1366 // Delete all followers that aren't undeleted
1367 DBA::delete('gfollower', ['gcid' => $gcid, 'deleted' => true]);
1370 DBA::update('gcontact', ['last_discovery' => DateTimeFormat::utcNow()], ['id' => $gcid]);
1371 Logger::info('AP contacts discovery finished, last discovery set', ['url' => $url]);
1375 $data = Probe::uri($url);
1376 if (empty($data['poco'])) {
1380 $curlResult = Network::curl($data['poco']);
1381 if (!$curlResult->isSuccess()) {
1384 $poco = json_decode($curlResult->getBody(), true);
1385 if (empty($poco['entry'])) {
1389 Logger::info('PoCo Discovery started', ['url' => $url, 'contacts' => count($poco['entry'])]);
1391 foreach ($poco['entry'] as $entries) {
1392 if (!empty($entries['urls'])) {
1393 foreach ($entries['urls'] as $entry) {
1394 if ($entry['type'] == 'profile') {
1395 if (DBA::exists('gcontact', ['nurl' => Strings::normaliseLink(($entry['value']))])) {
1398 if (!Network::isUrlBlocked($entry['value'])) {
1399 Logger::info('Discover new PoCo contact', ['url' => $entry['value']]);
1400 Worker::add(PRIORITY_LOW, 'UpdateGContact', $entry['value'], 'nodiscover');
1402 Logger::info('No discovery, the URL is blocked.', ['url' => $entry['value']]);
1409 DBA::update('gcontact', ['last_discovery' => DateTimeFormat::utcNow()], ['id' => $gcid]);
1410 Logger::info('PoCo Discovery finished', ['url' => $url]);
1414 * Returns a random, global contact of the current node
1416 * @return string The profile URL
1419 public static function getRandomUrl()
1421 $r = DBA::selectFirst('gcontact', ['url'], [
1423 AND `last_contact` >= `last_failure`
1426 DateTimeFormat::utc('now - 1 month'),
1427 ], ['order' => ['RAND()']]);
1429 if (DBA::isResult($r)) {