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\Database\DBA;
33 use Friendica\Network\Probe;
34 use Friendica\Protocol\ActivityPub;
35 use Friendica\Protocol\PortableContact;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
41 * This class handles GlobalContact related functions
46 * Search global contact table by nick or name
48 * @param string $search Name or nick
49 * @param string $mode Search mode (e.g. "community")
51 * @return array with search results
52 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
54 public static function searchByName($search, $mode = '')
60 // check supported networks
61 if (DI::config()->get('system', 'diaspora_enabled')) {
62 $diaspora = Protocol::DIASPORA;
64 $diaspora = Protocol::DFRN;
67 if (!DI::config()->get('system', 'ostatus_disabled')) {
68 $ostatus = Protocol::OSTATUS;
70 $ostatus = Protocol::DFRN;
73 // check if we search only communities or every contact
74 if ($mode === 'community') {
75 $extra_sql = ' AND `community`';
82 $results = DBA::p("SELECT `nurl` FROM `gcontact`
83 WHERE NOT `hide` AND `network` IN (?, ?, ?, ?) AND
84 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
85 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
86 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
87 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $search, $search, $search
91 while ($result = DBA::fetch($results)) {
92 $urlparts = parse_url($result['nurl']);
94 // Ignore results that look strange.
95 // For historic reasons the gcontact table does contain some garbage.
96 if (!empty($urlparts['query']) || !empty($urlparts['fragment'])) {
100 $gcontacts[] = Contact::getDetailsByURL($result['nurl'], local_user());
106 * Link the gcontact entry with user, contact and global contact
108 * @param integer $gcid Global contact ID
109 * @param integer $uid User ID
110 * @param integer $cid Contact ID
111 * @param integer $zcid Global Contact ID
115 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
121 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
122 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
126 * Sanitize the given gcontact data
130 * 1: Profiles on this server
131 * 2: Contacts of profiles on this server
132 * 3: Contacts of contacts of profiles on this server
135 * @param array $gcontact array with gcontact data
136 * @return array $gcontact
139 public static function sanitize($gcontact)
141 if (empty($gcontact['url'])) {
142 throw new Exception('URL is empty');
145 $gcontact['server_url'] = $gcontact['server_url'] ?? '';
147 $urlparts = parse_url($gcontact['url']);
148 if (empty($urlparts['scheme'])) {
149 throw new Exception('This (' . $gcontact['url'] . ") doesn't seem to be an url.");
152 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
153 throw new Exception('Contact from a non federated network ignored. (' . $gcontact['url'] . ')');
156 // Don't store the statusnet connector as network
157 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
158 if ($gcontact['network'] == Protocol::STATUSNET) {
159 $gcontact['network'] = '';
162 // Assure that there are no parameter fragments in the profile url
163 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
164 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
167 // The global contacts should contain the original picture, not the cached one
168 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(DI::baseUrl() . '/photo/'))) {
169 $gcontact['photo'] = '';
172 if (empty($gcontact['network'])) {
173 $gcontact['network'] = '';
175 $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
176 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
177 $contact = DBA::selectFirst('contact', ['network'], $condition);
178 if (DBA::isResult($contact)) {
179 $gcontact['network'] = $contact['network'];
182 if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
183 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
184 $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
185 $contact = DBA::selectFirst('contact', ['network'], $condition);
186 if (DBA::isResult($contact)) {
187 $gcontact['network'] = $contact['network'];
192 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
193 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
194 if (DBA::isResult($gcnt)) {
195 if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
196 $gcontact['network'] = $gcnt['network'];
198 if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
199 $gcontact['updated'] = $gcnt['updated'];
201 if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
202 $gcontact['server_url'] = $gcnt['server_url'];
204 if (!isset($gcontact['addr'])) {
205 $gcontact['addr'] = $gcnt['addr'];
209 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']))
210 && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
212 $data = Probe::uri($gcontact['url']);
214 if ($data['network'] == Protocol::PHANTOM) {
215 throw new Exception('Probing for URL ' . $gcontact['url'] . ' failed');
218 $orig_profile = $gcontact['url'];
220 $gcontact['server_url'] = $data['baseurl'];
222 $gcontact = array_merge($gcontact, $data);
225 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
226 throw new Exception('No name and photo for URL '.$gcontact['url']);
229 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
230 throw new Exception('No federated network (' . $gcontact['network'] . ') detected for URL ' . $gcontact['url']);
233 if (empty($gcontact['server_url'])) {
234 // We check the server url to be sure that it is a real one
235 $server_url = self::getBasepath($gcontact['url']);
237 // We are now sure that it is a correct URL. So we use it in the future
238 if ($server_url != '') {
239 $gcontact['server_url'] = $server_url;
243 // The server URL doesn't seem to be valid, so we don't store it.
244 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
245 $gcontact['server_url'] = '';
252 * @param integer $uid id
253 * @param integer $cid id
257 public static function countCommonFriends($uid, $cid)
260 "SELECT count(*) as `total`
261 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
262 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
263 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
264 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
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 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
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 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
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 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
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 `gcontact`.`last_contact` >= `gcontact`.`last_failure`
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 `gcontact`.`last_contact` >= `gcontact`.`last_failure`
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 = Network::fetchUrl(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);
555 * Removes unwanted parts from a contact url
557 * @param string $url Contact url
559 * @return string Contact url with the wanted parts
562 public static function cleanContactUrl($url)
564 $parts = parse_url($url);
566 if (empty($parts['scheme']) || empty($parts['host'])) {
570 $new_url = $parts['scheme'] . '://' . $parts['host'];
572 if (!empty($parts['port'])) {
573 $new_url .= ':' . $parts['port'];
576 if (!empty($parts['path'])) {
577 $new_url .= $parts['path'];
580 if ($new_url != $url) {
581 Logger::info('Cleaned contact url', ['url' => $url, 'new_url' => $new_url, 'callstack' => System::callstack()]);
588 * Fetch the gcontact id, add an entry if not existed
590 * @param array $contact contact array
592 * @return bool|int Returns false if not found, integer if contact was found
593 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
594 * @throws \ImagickException
596 public static function getId($contact)
600 if (empty($contact['network'])) {
601 Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
605 if (in_array($contact['network'], [Protocol::PHANTOM])) {
606 Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
610 if ($contact['network'] == Protocol::STATUSNET) {
611 $contact['network'] = Protocol::OSTATUS;
614 // All new contacts are hidden by default
615 if (!isset($contact['hide'])) {
616 $contact['hide'] = true;
619 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
620 if (in_array($contact['network'], Protocol::FEDERATED)) {
621 $contact['url'] = self::cleanContactUrl($contact['url']);
624 DBA::lock('gcontact');
625 $fields = ['id', 'last_contact', 'last_failure', 'network'];
626 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
627 if (DBA::isResult($gcnt)) {
628 $gcontact_id = $gcnt['id'];
630 $contact['location'] = $contact['location'] ?? '';
631 $contact['about'] = $contact['about'] ?? '';
632 $contact['generation'] = $contact['generation'] ?? 0;
634 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'] ?? '', 'addr' => $contact['addr'] ?? '', 'network' => $contact['network'],
635 'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
636 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
637 'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation']];
639 DBA::insert('gcontact', $fields);
641 $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
642 $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
643 if (DBA::isResult($cnt)) {
644 $gcontact_id = $cnt['id'];
653 * Updates the gcontact table from a given array
655 * @param array $contact contact array
657 * @return bool|int Returns false if not found, integer if contact was found
658 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
659 * @throws \ImagickException
661 public static function update($contact)
663 // Check for invalid "contact-type" value
664 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
665 $contact['contact-type'] = 0;
668 /// @todo update contact table as well
670 $gcontact_id = self::getId($contact);
676 $public_contact = DBA::selectFirst('gcontact', [
677 'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'keywords',
678 'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
679 ], ['id' => $gcontact_id]);
681 if (!DBA::isResult($public_contact)) {
685 // Get all field names
687 foreach ($public_contact as $field => $data) {
688 $fields[$field] = $data;
691 unset($fields['url']);
692 unset($fields['updated']);
693 unset($fields['hide']);
695 // Bugfix: We had an error in the storing of keywords which lead to the "0"
696 // This value is still transmitted via poco.
697 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
698 unset($contact['keywords']);
701 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
702 $public_contact['keywords'] = '';
705 // assign all unassigned fields from the database entry
706 foreach ($fields as $field => $data) {
707 if (empty($contact[$field])) {
708 $contact[$field] = $public_contact[$field];
712 if (!isset($contact['hide'])) {
713 $contact['hide'] = $public_contact['hide'];
716 $fields['hide'] = $public_contact['hide'];
718 if ($contact['network'] == Protocol::STATUSNET) {
719 $contact['network'] = Protocol::OSTATUS;
722 if (!isset($contact['updated'])) {
723 $contact['updated'] = DateTimeFormat::utcNow();
726 if ($contact['network'] == Protocol::TWITTER) {
727 $contact['server_url'] = 'http://twitter.com';
730 if (empty($contact['server_url'])) {
731 $data = Probe::uri($contact['url']);
732 if ($data['network'] != Protocol::PHANTOM) {
733 $contact['server_url'] = $data['baseurl'];
736 $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
739 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
740 $hostname = str_replace('http://', '', $contact['server_url']);
741 $contact['addr'] = $contact['nick'] . '@' . $hostname;
744 // Check if any field changed
746 unset($fields['generation']);
748 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
749 foreach ($fields as $field => $data) {
750 if ($contact[$field] != $public_contact[$field]) {
751 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
756 if ($contact['generation'] < $public_contact['generation']) {
757 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
763 Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
764 $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
765 Strings::normaliseLink($contact['url']), $contact['generation']];
766 $contact['updated'] = DateTimeFormat::utc($contact['updated']);
769 'photo' => $contact['photo'], 'name' => $contact['name'],
770 'nick' => $contact['nick'], 'addr' => $contact['addr'],
771 'network' => $contact['network'], 'birthday' => $contact['birthday'],
772 'keywords' => $contact['keywords'],
773 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
774 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
775 'notify' => $contact['notify'], 'url' => $contact['url'],
776 'location' => $contact['location'], 'about' => $contact['about'],
777 'generation' => $contact['generation'], 'updated' => $contact['updated'],
778 'server_url' => $contact['server_url'], 'connect' => $contact['connect']
781 DBA::update('gcontact', $updated, $condition, $fields);
788 * Set the last date that the contact had posted something
790 * @param string $data Probing result
791 * @param bool $force force updating
793 public static function setLastUpdate(array $data, bool $force = false)
795 // Fetch the global contact
796 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
797 ['nurl' => Strings::normaliseLink($data['url'])]);
798 if (!DBA::isResult($gcontact)) {
802 if (!$force && !GServer::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
803 Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
807 if (self::updateFromNoScrape($data)) {
811 if (!empty($data['outbox'])) {
812 self::updateFromOutbox($data['outbox'], $data);
813 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
814 self::updateFromOutbox($data['poll'], $data);
815 } elseif (!empty($data['poll'])) {
816 self::updateFromFeed($data);
821 * Update a global contact via the "noscrape" endpoint
823 * @param string $data Probing result
825 * @return bool 'true' if update was successful or the server was unreachable
827 private static function updateFromNoScrape(array $data)
829 // Check the 'noscrape' endpoint when it is a Friendica server
830 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
831 Strings::normaliseLink($data['baseurl'])]);
832 if (!DBA::isResult($gserver)) {
836 $curlResult = Network::curl($gserver['noscrape'] . '/' . $data['nick']);
838 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
839 $noscrape = json_decode($curlResult->getBody(), true);
840 if (!empty($noscrape) && !empty($noscrape['updated'])) {
841 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
842 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
843 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
846 } elseif ($curlResult->isTimeout()) {
847 // On a timeout return the existing value, but mark the contact as failure
848 $fields = ['last_failure' => DateTimeFormat::utcNow()];
849 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
856 * Update a global contact via an ActivityPub Outbox
858 * @param string $feed
859 * @param array $data Probing result
860 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
862 private static function updateFromOutbox(string $feed, array $data)
864 $outbox = ActivityPub::fetchContent($feed);
865 if (empty($outbox)) {
869 if (!empty($outbox['orderedItems'])) {
870 $items = $outbox['orderedItems'];
871 } elseif (!empty($outbox['first']['orderedItems'])) {
872 $items = $outbox['first']['orderedItems'];
873 } elseif (!empty($outbox['first']['href'])) {
874 self::updateFromOutbox($outbox['first']['href'], $data);
876 } elseif (!empty($outbox['first'])) {
877 if (is_string($outbox['first'])) {
878 self::updateFromOutbox($outbox['first'], $data);
880 Logger::warning('Unexpected data', ['outbox' => $outbox]);
888 foreach ($items as $activity) {
889 if (!empty($activity['published'])) {
890 $published = DateTimeFormat::utc($activity['published']);
891 } elseif (!empty($activity['object']['published'])) {
892 $published = DateTimeFormat::utc($activity['object']['published']);
897 if ($last_updated < $published) {
898 $last_updated = $published;
902 if (empty($last_updated)) {
906 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
907 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
911 * Update a global contact via an XML feed
913 * @param string $data Probing result
915 private static function updateFromFeed(array $data)
917 // Search for the newest entry in the feed
918 $curlResult = Network::curl($data['poll']);
919 if (!$curlResult->isSuccess()) {
920 $fields = ['last_failure' => DateTimeFormat::utcNow()];
921 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
923 Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
927 $doc = new DOMDocument();
928 @$doc->loadXML($curlResult->getBody());
930 $xpath = new DOMXPath($doc);
931 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
933 $entries = $xpath->query('/atom:feed/atom:entry');
937 foreach ($entries as $entry) {
938 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
939 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
940 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
941 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
943 if (empty($published) || empty($updated)) {
944 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
948 if ($last_updated < $published) {
949 $last_updated = $published;
952 if ($last_updated < $updated) {
953 $last_updated = $updated;
957 if (empty($last_updated)) {
961 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
962 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
965 * Updates the gcontact entry from a given public contact id
967 * @param integer $cid contact id
969 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
970 * @throws \ImagickException
972 public static function updateFromPublicContactID($cid)
974 self::updateFromPublicContact(['id' => $cid]);
978 * Updates the gcontact entry from a given public contact url
980 * @param string $url contact url
981 * @return integer gcontact id
982 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
983 * @throws \ImagickException
985 public static function updateFromPublicContactURL($url)
987 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
991 * Helper function for updateFromPublicContactID and updateFromPublicContactURL
993 * @param array $condition contact condition
994 * @return integer gcontact id
995 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
996 * @throws \ImagickException
998 private static function updateFromPublicContact($condition)
1000 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords',
1001 'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
1002 'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
1003 'baseurl', 'sensitive', 'unsearchable'];
1005 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
1006 if (!DBA::isResult($contact)) {
1010 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'generation',
1011 'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
1012 'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
1013 'server_url', 'nsfw', 'hide', 'id'];
1015 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
1016 $do_insert = !DBA::isResult($old_gcontact);
1023 // These fields are identical in both contact and gcontact
1024 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords',
1025 'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated'];
1027 foreach ($fields as $field) {
1028 $gcontact[$field] = $contact[$field];
1031 // These fields are having different names but the same content
1032 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
1033 $gcontact['nsfw'] = $contact['sensitive'];
1034 $gcontact['hide'] = $contact['unsearchable'];
1035 $gcontact['archived'] = $contact['archive'];
1036 $gcontact['archive_date'] = $contact['term-date'];
1037 $gcontact['birthday'] = $contact['bd'];
1038 $gcontact['photo'] = $contact['avatar'];
1039 $gcontact['last_contact'] = $contact['success_update'];
1040 $gcontact['last_failure'] = $contact['failure_update'];
1041 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
1043 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
1044 if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
1045 unset($gcontact[$field]);
1049 if (!$gcontact['archived']) {
1050 $gcontact['archive_date'] = DBA::NULL_DATETIME;
1053 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
1054 && ($old_gcontact['created'] <= $gcontact['created'])) {
1055 unset($gcontact['created']);
1058 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
1059 unset($gcontact['birthday']);
1062 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
1063 $gcontact['generation'] = 2; // We fetched the data directly from the other server
1067 DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
1068 return $old_gcontact['id'];
1069 } elseif (!$gcontact['archived']) {
1070 DBA::insert('gcontact', $gcontact);
1071 return DBA::lastInsertId();
1076 * Updates the gcontact entry from probe
1078 * @param string $url profile link
1079 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1081 * @return boolean 'true' when contact had been updated
1083 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1084 * @throws \ImagickException
1086 public static function updateFromProbe($url, $force = false)
1088 $data = Probe::uri($url, $force);
1090 if (in_array($data['network'], [Protocol::PHANTOM])) {
1091 $fields = ['last_failure' => DateTimeFormat::utcNow()];
1092 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1093 Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
1097 $data['server_url'] = $data['baseurl'];
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 = Network::curl($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'], [
1259 AND `last_contact` >= `last_failure`
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'], [
1288 AND `last_contact` >= `last_failure`
1291 DateTimeFormat::utc('now - 1 month'),
1292 ], ['order' => ['RAND()']]);
1294 if (DBA::isResult($r)) {