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 * 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
85 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) 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($urlparts['query']) || !empty($urlparts['fragment'])) {
101 $gcontacts[] = Contact::getDetailsByURL($result['nurl'], local_user());
107 * Link the gcontact entry with user, contact and global contact
109 * @param integer $gcid Global contact ID
110 * @param integer $uid User ID
111 * @param integer $cid Contact ID
112 * @param integer $zcid Global Contact ID
116 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
122 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
123 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
127 * Sanitize the given gcontact data
131 * 1: Profiles on this server
132 * 2: Contacts of profiles on this server
133 * 3: Contacts of contacts of profiles on this server
136 * @param array $gcontact array with gcontact data
137 * @return array $gcontact
140 public static function sanitize($gcontact)
142 if (empty($gcontact['url'])) {
143 throw new Exception('URL is empty');
146 $gcontact['server_url'] = $gcontact['server_url'] ?? '';
148 $urlparts = parse_url($gcontact['url']);
149 if (empty($urlparts['scheme'])) {
150 throw new Exception('This (' . $gcontact['url'] . ") doesn't seem to be an url.");
153 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
154 throw new Exception('Contact from a non federated network ignored. (' . $gcontact['url'] . ')');
157 // Don't store the statusnet connector as network
158 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
159 if ($gcontact['network'] == Protocol::STATUSNET) {
160 $gcontact['network'] = '';
163 // Assure that there are no parameter fragments in the profile url
164 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
165 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
168 // The global contacts should contain the original picture, not the cached one
169 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(DI::baseUrl() . '/photo/'))) {
170 $gcontact['photo'] = '';
173 if (empty($gcontact['network'])) {
174 $gcontact['network'] = '';
176 $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
177 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
178 $contact = DBA::selectFirst('contact', ['network'], $condition);
179 if (DBA::isResult($contact)) {
180 $gcontact['network'] = $contact['network'];
183 if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
184 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
185 $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
186 $contact = DBA::selectFirst('contact', ['network'], $condition);
187 if (DBA::isResult($contact)) {
188 $gcontact['network'] = $contact['network'];
193 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
194 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
195 if (DBA::isResult($gcnt)) {
196 if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
197 $gcontact['network'] = $gcnt['network'];
199 if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
200 $gcontact['updated'] = $gcnt['updated'];
202 if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
203 $gcontact['server_url'] = $gcnt['server_url'];
205 if (!isset($gcontact['addr'])) {
206 $gcontact['addr'] = $gcnt['addr'];
210 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']))
211 && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
213 $data = Probe::uri($gcontact['url']);
215 if ($data['network'] == Protocol::PHANTOM) {
216 throw new Exception('Probing for URL ' . $gcontact['url'] . ' failed');
219 $orig_profile = $gcontact['url'];
221 $gcontact['server_url'] = $data['baseurl'];
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 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
265 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
266 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d) ",
273 if (DBA::isResult($r)) {
274 return $r[0]['total'];
280 * @param integer $uid id
281 * @param integer $zcid zcid
285 public static function countCommonFriendsZcid($uid, $zcid)
288 "SELECT count(*) as `total`
289 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
290 where `glink`.`zcid` = %d
291 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0) ",
296 if (DBA::isResult($r)) {
297 return $r[0]['total'];
304 * @param integer $uid user
305 * @param integer $cid cid
306 * @param integer $start optional, default 0
307 * @param integer $limit optional, default 9999
308 * @param boolean $shuffle optional, default false
312 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
315 $sql_extra = " order by rand() ";
317 $sql_extra = " order by `gcontact`.`name` asc ";
321 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
323 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
324 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
325 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
326 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
327 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
328 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
329 $sql_extra LIMIT %d, %d",
338 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
343 * @param integer $uid user
344 * @param integer $zcid zcid
345 * @param integer $start optional, default 0
346 * @param integer $limit optional, default 9999
347 * @param boolean $shuffle optional, default false
351 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
354 $sql_extra = " order by rand() ";
356 $sql_extra = " order by `gcontact`.`name` asc ";
361 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
362 where `glink`.`zcid` = %d
363 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0)
364 $sql_extra limit %d, %d",
371 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
376 * @param integer $uid user
377 * @param integer $cid cid
381 public static function countAllFriends($uid, $cid)
384 "SELECT count(*) as `total`
385 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
386 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
387 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
392 if (DBA::isResult($r)) {
393 return $r[0]['total'];
400 * @param integer $uid user
401 * @param integer $cid cid
402 * @param integer $start optional, default 0
403 * @param integer $limit optional, default 80
407 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
410 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
412 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
413 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
414 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
415 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
416 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
424 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
429 * @param int $uid user
430 * @param integer $start optional, default 0
431 * @param integer $limit optional, default 80
433 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
435 public static function suggestionQuery($uid, $start = 0, $limit = 80)
441 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
443 if (DI::config()->get('system', 'diaspora_enabled')) {
444 $network[] = Protocol::DIASPORA;
447 if (!DI::config()->get('system', 'ostatus_disabled')) {
448 $network[] = Protocol::OSTATUS;
451 $sql_network = "'" . implode("', '", $network) . "'";
453 /// @todo This query is really slow
454 // By now we cache the data for five minutes
456 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
457 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
458 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
459 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
460 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
461 AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
462 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
463 AND `gcontact`.`network` IN (%s)
464 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
475 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
480 "SELECT gcontact.* FROM gcontact
481 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
482 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
483 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
484 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
485 AND `gcontact`.`updated` >= '%s'
486 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
487 AND `gcontact`.`network` IN (%s)
488 ORDER BY rand() LIMIT %d, %d",
499 foreach ($r2 as $suggestion) {
500 $list[$suggestion['nurl']] = $suggestion;
503 foreach ($r as $suggestion) {
504 $list[$suggestion['nurl']] = $suggestion;
507 while (sizeof($list) > ($limit)) {
516 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
518 public static function updateSuggestions()
522 /// @TODO Check if it is really neccessary to poll the own server
523 PortableContact::loadWorker(0, 0, 0, DI::baseUrl() . '/poco');
525 $done[] = DI::baseUrl() . '/poco';
527 if (strlen(DI::config()->get('system', 'directory'))) {
528 $x = Network::fetchUrl(Search::getGlobalDirectory() . '/pubsites');
530 $j = json_decode($x);
531 if (!empty($j->entries)) {
532 foreach ($j->entries as $entry) {
533 GServer::check($entry->url);
535 $url = $entry->url . '/poco';
536 if (!in_array($url, $done)) {
537 PortableContact::loadWorker(0, 0, 0, $url);
545 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
546 $contacts = DBA::p("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN (?, ?)", Protocol::DFRN, Protocol::DIASPORA);
547 while ($contact = DBA::fetch($contacts)) {
548 $base = substr($contact['poco'], 0, strrpos($contact['poco'], '/'));
549 if (!in_array($base, $done)) {
550 PortableContact::loadWorker(0, 0, 0, $base);
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)
601 if (empty($contact['network'])) {
602 Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
606 if (in_array($contact['network'], [Protocol::PHANTOM])) {
607 Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
611 if ($contact['network'] == Protocol::STATUSNET) {
612 $contact['network'] = Protocol::OSTATUS;
615 // All new contacts are hidden by default
616 if (!isset($contact['hide'])) {
617 $contact['hide'] = true;
620 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
621 if (in_array($contact['network'], Protocol::FEDERATED)) {
622 $contact['url'] = self::cleanContactUrl($contact['url']);
625 DBA::lock('gcontact');
626 $fields = ['id', 'last_contact', 'last_failure', 'network'];
627 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
628 if (DBA::isResult($gcnt)) {
629 $gcontact_id = $gcnt['id'];
631 $contact['location'] = $contact['location'] ?? '';
632 $contact['about'] = $contact['about'] ?? '';
633 $contact['generation'] = $contact['generation'] ?? 0;
635 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'] ?? '', 'addr' => $contact['addr'] ?? '', 'network' => $contact['network'],
636 'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
637 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
638 'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation']];
640 DBA::insert('gcontact', $fields);
642 $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
643 $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
644 if (DBA::isResult($cnt)) {
645 $gcontact_id = $cnt['id'];
654 * Updates the gcontact table from a given array
656 * @param array $contact contact array
658 * @return bool|int Returns false if not found, integer if contact was found
659 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
660 * @throws \ImagickException
662 public static function update($contact)
664 // Check for invalid "contact-type" value
665 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
666 $contact['contact-type'] = 0;
669 /// @todo update contact table as well
671 $gcontact_id = self::getId($contact);
677 $public_contact = DBA::selectFirst('gcontact', [
678 'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'keywords',
679 'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
680 ], ['id' => $gcontact_id]);
682 if (!DBA::isResult($public_contact)) {
686 // Get all field names
688 foreach ($public_contact as $field => $data) {
689 $fields[$field] = $data;
692 unset($fields['url']);
693 unset($fields['updated']);
694 unset($fields['hide']);
696 // Bugfix: We had an error in the storing of keywords which lead to the "0"
697 // This value is still transmitted via poco.
698 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
699 unset($contact['keywords']);
702 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
703 $public_contact['keywords'] = '';
706 // assign all unassigned fields from the database entry
707 foreach ($fields as $field => $data) {
708 if (empty($contact[$field])) {
709 $contact[$field] = $public_contact[$field];
713 if (!isset($contact['hide'])) {
714 $contact['hide'] = $public_contact['hide'];
717 $fields['hide'] = $public_contact['hide'];
719 if ($contact['network'] == Protocol::STATUSNET) {
720 $contact['network'] = Protocol::OSTATUS;
723 if (!isset($contact['updated'])) {
724 $contact['updated'] = DateTimeFormat::utcNow();
727 if ($contact['network'] == Protocol::TWITTER) {
728 $contact['server_url'] = 'http://twitter.com';
731 if (empty($contact['server_url'])) {
732 $data = Probe::uri($contact['url']);
733 if ($data['network'] != Protocol::PHANTOM) {
734 $contact['server_url'] = $data['baseurl'];
737 $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
740 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
741 $hostname = str_replace('http://', '', $contact['server_url']);
742 $contact['addr'] = $contact['nick'] . '@' . $hostname;
745 // Check if any field changed
747 unset($fields['generation']);
749 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
750 foreach ($fields as $field => $data) {
751 if ($contact[$field] != $public_contact[$field]) {
752 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
757 if ($contact['generation'] < $public_contact['generation']) {
758 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
764 Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
765 $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
766 Strings::normaliseLink($contact['url']), $contact['generation']];
767 $contact['updated'] = DateTimeFormat::utc($contact['updated']);
770 'photo' => $contact['photo'], 'name' => $contact['name'],
771 'nick' => $contact['nick'], 'addr' => $contact['addr'],
772 'network' => $contact['network'], 'birthday' => $contact['birthday'],
773 'keywords' => $contact['keywords'],
774 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
775 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
776 'notify' => $contact['notify'], 'url' => $contact['url'],
777 'location' => $contact['location'], 'about' => $contact['about'],
778 'generation' => $contact['generation'], 'updated' => $contact['updated'],
779 'server_url' => $contact['server_url'], 'connect' => $contact['connect']
782 DBA::update('gcontact', $updated, $condition, $fields);
789 * Set the last date that the contact had posted something
791 * @param string $data Probing result
792 * @param bool $force force updating
794 public static function setLastUpdate(array $data, bool $force = false)
796 // Fetch the global contact
797 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
798 ['nurl' => Strings::normaliseLink($data['url'])]);
799 if (!DBA::isResult($gcontact)) {
803 if (!$force && !GServer::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
804 Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
808 if (self::updateFromNoScrape($data)) {
812 if (!empty($data['outbox'])) {
813 self::updateFromOutbox($data['outbox'], $data);
814 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
815 self::updateFromOutbox($data['poll'], $data);
816 } elseif (!empty($data['poll'])) {
817 self::updateFromFeed($data);
822 * Update a global contact via the "noscrape" endpoint
824 * @param string $data Probing result
826 * @return bool 'true' if update was successful or the server was unreachable
828 private static function updateFromNoScrape(array $data)
830 // Check the 'noscrape' endpoint when it is a Friendica server
831 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
832 Strings::normaliseLink($data['baseurl'])]);
833 if (!DBA::isResult($gserver)) {
837 $curlResult = Network::curl($gserver['noscrape'] . '/' . $data['nick']);
839 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
840 $noscrape = json_decode($curlResult->getBody(), true);
841 if (!empty($noscrape) && !empty($noscrape['updated'])) {
842 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
843 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
844 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
847 } elseif ($curlResult->isTimeout()) {
848 // On a timeout return the existing value, but mark the contact as failure
849 $fields = ['last_failure' => DateTimeFormat::utcNow()];
850 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
857 * Update a global contact via an ActivityPub Outbox
859 * @param string $feed
860 * @param array $data Probing result
861 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
863 private static function updateFromOutbox(string $feed, array $data)
865 $outbox = ActivityPub::fetchContent($feed);
866 if (empty($outbox)) {
870 if (!empty($outbox['orderedItems'])) {
871 $items = $outbox['orderedItems'];
872 } elseif (!empty($outbox['first']['orderedItems'])) {
873 $items = $outbox['first']['orderedItems'];
874 } elseif (!empty($outbox['first']['href'])) {
875 self::updateFromOutbox($outbox['first']['href'], $data);
877 } elseif (!empty($outbox['first'])) {
878 if (is_string($outbox['first'])) {
879 self::updateFromOutbox($outbox['first'], $data);
881 Logger::warning('Unexpected data', ['outbox' => $outbox]);
889 foreach ($items as $activity) {
890 if (!empty($activity['published'])) {
891 $published = DateTimeFormat::utc($activity['published']);
892 } elseif (!empty($activity['object']['published'])) {
893 $published = DateTimeFormat::utc($activity['object']['published']);
898 if ($last_updated < $published) {
899 $last_updated = $published;
903 if (empty($last_updated)) {
907 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
908 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
912 * Update a global contact via an XML feed
914 * @param string $data Probing result
916 private static function updateFromFeed(array $data)
918 // Search for the newest entry in the feed
919 $curlResult = Network::curl($data['poll']);
920 if (!$curlResult->isSuccess()) {
921 $fields = ['last_failure' => DateTimeFormat::utcNow()];
922 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
924 Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
928 $doc = new DOMDocument();
929 @$doc->loadXML($curlResult->getBody());
931 $xpath = new DOMXPath($doc);
932 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
934 $entries = $xpath->query('/atom:feed/atom:entry');
938 foreach ($entries as $entry) {
939 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
940 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
941 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
942 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
944 if (empty($published) || empty($updated)) {
945 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
949 if ($last_updated < $published) {
950 $last_updated = $published;
953 if ($last_updated < $updated) {
954 $last_updated = $updated;
958 if (empty($last_updated)) {
962 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
963 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
966 * Updates the gcontact entry from a given public contact id
968 * @param integer $cid contact id
970 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
971 * @throws \ImagickException
973 public static function updateFromPublicContactID($cid)
975 self::updateFromPublicContact(['id' => $cid]);
979 * Updates the gcontact entry from a given public contact url
981 * @param string $url contact url
982 * @return integer gcontact id
983 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
984 * @throws \ImagickException
986 public static function updateFromPublicContactURL($url)
988 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
992 * Helper function for updateFromPublicContactID and updateFromPublicContactURL
994 * @param array $condition contact condition
995 * @return integer gcontact id
996 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
997 * @throws \ImagickException
999 private static function updateFromPublicContact($condition)
1001 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords',
1002 'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
1003 'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
1004 'baseurl', 'sensitive', 'unsearchable'];
1006 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
1007 if (!DBA::isResult($contact)) {
1011 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'generation',
1012 'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
1013 'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
1014 'server_url', 'nsfw', 'hide', 'id'];
1016 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
1017 $do_insert = !DBA::isResult($old_gcontact);
1024 // These fields are identical in both contact and gcontact
1025 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords',
1026 'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated'];
1028 foreach ($fields as $field) {
1029 $gcontact[$field] = $contact[$field];
1032 // These fields are having different names but the same content
1033 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
1034 $gcontact['nsfw'] = $contact['sensitive'];
1035 $gcontact['hide'] = $contact['unsearchable'];
1036 $gcontact['archived'] = $contact['archive'];
1037 $gcontact['archive_date'] = $contact['term-date'];
1038 $gcontact['birthday'] = $contact['bd'];
1039 $gcontact['photo'] = $contact['avatar'];
1040 $gcontact['last_contact'] = $contact['success_update'];
1041 $gcontact['last_failure'] = $contact['failure_update'];
1042 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
1044 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
1045 if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
1046 unset($gcontact[$field]);
1050 if (!$gcontact['archived']) {
1051 $gcontact['archive_date'] = DBA::NULL_DATETIME;
1054 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
1055 && ($old_gcontact['created'] <= $gcontact['created'])) {
1056 unset($gcontact['created']);
1059 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
1060 unset($gcontact['birthday']);
1063 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
1064 $gcontact['generation'] = 2; // We fetched the data directly from the other server
1068 DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
1069 return $old_gcontact['id'];
1070 } elseif (!$gcontact['archived']) {
1071 DBA::insert('gcontact', $gcontact);
1072 return DBA::lastInsertId();
1077 * Updates the gcontact entry from probe
1079 * @param string $url profile link
1080 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1082 * @return boolean 'true' when contact had been updated
1084 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1085 * @throws \ImagickException
1087 public static function updateFromProbe($url, $force = false)
1089 $data = Probe::uri($url, $force);
1091 if (in_array($data['network'], [Protocol::PHANTOM])) {
1092 $fields = ['last_failure' => DateTimeFormat::utcNow()];
1093 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1094 Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
1098 $data['server_url'] = $data['baseurl'];
1100 self::update($data);
1102 // Set the date of the latest post
1103 self::setLastUpdate($data, $force);
1109 * Update the gcontact entry for a given user id
1111 * @param int $uid User ID
1113 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1114 * @throws \ImagickException
1116 public static function updateForUser($uid)
1118 $profile = Profile::getByUID($uid);
1119 if (empty($profile)) {
1120 Logger::error('Cannot find profile', ['uid' => $uid]);
1124 $user = User::getOwnerDataById($uid);
1126 Logger::error('Cannot find user', ['uid' => $uid]);
1130 $userdata = array_merge($profile, $user);
1132 $location = Profile::formatLocation(
1133 ['locality' => $userdata['locality'], 'region' => $userdata['region'], 'country-name' => $userdata['country-name']]
1136 $gcontact = ['name' => $userdata['name'], 'location' => $location, 'about' => $userdata['about'],
1137 'keywords' => $userdata['pub_keywords'],
1138 'birthday' => $userdata['dob'], 'photo' => $userdata['photo'],
1139 "notify" => $userdata['notify'], 'url' => $userdata['url'],
1140 "hide" => !$userdata['net-publish'],
1141 'nick' => $userdata['nickname'], 'addr' => $userdata['addr'],
1142 "connect" => $userdata['addr'], "server_url" => DI::baseUrl(),
1143 "generation" => 1, 'network' => Protocol::DFRN];
1145 self::update($gcontact);
1149 * Get the basepath for a given contact link
1151 * @param string $url The gcontact link
1152 * @param boolean $dont_update Don't update the contact
1154 * @return string basepath
1155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1156 * @throws \ImagickException
1158 public static function getBasepath($url, $dont_update = false)
1160 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1161 if (!empty($gcontact['server_url'])) {
1162 return $gcontact['server_url'];
1163 } elseif ($dont_update) {
1167 self::updateFromProbe($url, true);
1170 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1171 if (empty($gcontact['server_url'])) {
1172 Logger::info('No baseurl for gcontact', ['url' => $url]);
1176 Logger::info('Found baseurl for gcontact', ['url' => $url, 'baseurl' => $gcontact['server_url']]);
1177 return $gcontact['server_url'];
1181 * Fetches users of given GNU Social server
1183 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1185 * @param string $server Server address
1187 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1188 * @throws \ImagickException
1190 public static function fetchGsUsers($server)
1192 Logger::info('Fetching users from GNU Social server', ['server' => $server]);
1194 $url = $server . '/main/statistics';
1196 $curlResult = Network::curl($url);
1197 if (!$curlResult->isSuccess()) {
1201 $statistics = json_decode($curlResult->getBody());
1203 if (!empty($statistics->config->instance_address)) {
1204 if (!empty($statistics->config->instance_with_ssl)) {
1205 $server = 'https://';
1207 $server = 'http://';
1210 $server .= $statistics->config->instance_address;
1212 $hostname = $statistics->config->instance_address;
1213 } elseif (!empty($statistics->instance_address)) {
1214 if (!empty($statistics->instance_with_ssl)) {
1215 $server = 'https://';
1217 $server = 'http://';
1220 $server .= $statistics->instance_address;
1222 $hostname = $statistics->instance_address;
1225 if (!empty($statistics->users)) {
1226 foreach ($statistics->users as $nick => $user) {
1227 $profile_url = $server . '/' . $user->nickname;
1229 $contact = ['url' => $profile_url,
1230 'name' => $user->fullname,
1231 'addr' => $user->nickname . '@' . $hostname,
1232 'nick' => $user->nickname,
1233 "network" => Protocol::OSTATUS,
1234 'photo' => DI::baseUrl() . '/images/person-300.jpg'];
1236 if (isset($user->bio)) {
1237 $contact['about'] = $user->bio;
1240 self::getId($contact);
1246 * Asking GNU Social server on a regular base for their user data
1249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1250 * @throws \ImagickException
1252 public static function discoverGsUsers()
1254 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1256 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1258 $r = DBA::select('gserver', ['nurl', 'url'], [
1260 AND `last_contact` >= `last_failure`
1261 AND `last_poco_query` < ?',
1266 'order' => ['RAND()']
1269 if (!DBA::isResult($r)) {
1273 foreach ($r as $server) {
1274 self::fetchGsUsers($server['url']);
1275 DBA::update('gserver', ['last_poco_query' => DateTimeFormat::utcNow()], ['nurl' => $server['nurl']]);
1280 * Fetches the followers of a given profile and adds them
1282 * @param string $url URL of a profile
1285 public static function discoverFollowers(string $url)
1287 $apcontact = APContact::getByURL($url);
1289 if (!empty($apcontact['followers']) && is_string($apcontact['followers'])) {
1290 $followers = ActivityPub::fetchItems($apcontact['followers']);
1295 if (!empty($apcontact['following']) && is_string($apcontact['following'])) {
1296 $followings = ActivityPub::fetchItems($apcontact['following']);
1301 if (!empty($followers) || !empty($followings)) {
1302 $gcontact = DBA::selectFirst('gcontact', ['id'], ['nurl' => Strings::normaliseLink(($url))]);
1303 $gcid = $gcontact['id'];
1304 if (!empty($followers)) {
1305 // Clear the follower list, since it will be recreated in the next step
1306 DBA::delete('gfollower', ['gcid' => $gcid]);
1309 $contacts = array_unique(array_merge($followers, $followings));
1310 Logger::info('Discover AP contacts', ['url' => $url, 'contacts' => count($contacts)]);
1311 foreach ($contacts as $contact) {
1312 $gcontact = DBA::selectFirst('gcontact', ['id'], ['nurl' => Strings::normaliseLink(($contact))]);
1313 if (DBA::isResult($gcontact)) {
1314 if (in_array($contact, $followers)) {
1315 $fields = ['gcid' => $gcid, 'follower-gcid' => $gcontact['id']];
1316 } elseif (in_array($contact, $followings)) {
1317 $fields = ['gcid' => $gcontact['id'], 'follower-gcid' => $gcid];
1319 Logger::info('Set relation between contacts', $fields);
1320 DBA::update('gfollower', $fields, $fields, true);
1323 Logger::info('Discover new AP contact', ['url' => $contact]);
1324 Worker::add(PRIORITY_LOW, 'UpdateGContact', $contact);
1326 Logger::info('AP contacts discovery finished', ['url' => $url]);
1330 $data = Probe::uri($url);
1331 if (empty($data['poco'])) {
1335 $curlResult = Network::curl($data['poco']);
1336 if (!$curlResult->isSuccess()) {
1339 $poco = json_decode($curlResult->getBody(), true);
1340 if (empty($poco['entry'])) {
1344 Logger::info('PoCo Discovery started', ['url' => $url, 'contacts' => count($poco['entry'])]);
1346 foreach ($poco['entry'] as $entries) {
1347 if (!empty($entries['urls'])) {
1348 foreach ($entries['urls'] as $entry) {
1349 if ($entry['type'] == 'profile') {
1350 if (DBA::exists('gcontact', ['nurl' => Strings::normaliseLink(($entry['value']))])) {
1353 Logger::info('Discover new PoCo contact', ['url' => $entry['value']]);
1354 Worker::add(PRIORITY_LOW, 'UpdateGContact', $entry['value']);
1359 Logger::info('PoCo Discovery finished', ['url' => $url]);
1363 * Returns a random, global contact of the current node
1365 * @return string The profile URL
1368 public static function getRandomUrl()
1370 $r = DBA::selectFirst('gcontact', ['url'], [
1372 AND `last_contact` >= `last_failure`
1375 DateTimeFormat::utc('now - 1 month'),
1376 ], ['order' => ['RAND()']]);
1378 if (DBA::isResult($r)) {