3 * @file src/Model/GlobalContact.php
4 * @brief This file includes the GlobalContact class with directory related functions
6 namespace Friendica\Model;
11 use Friendica\Core\Config;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\System;
15 use Friendica\Core\Search;
16 use Friendica\Database\DBA;
18 use Friendica\Network\Probe;
19 use Friendica\Protocol\ActivityPub;
20 use Friendica\Protocol\PortableContact;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Strings;
26 * @brief This class handles GlobalContact related functions
31 * @brief Search global contact table by nick or name
33 * @param string $search Name or nick
34 * @param string $mode Search mode (e.g. "community")
36 * @return array with search results
37 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
39 public static function searchByName($search, $mode = '')
45 // check supported networks
46 if (Config::get('system', 'diaspora_enabled')) {
47 $diaspora = Protocol::DIASPORA;
49 $diaspora = Protocol::DFRN;
52 if (!Config::get('system', 'ostatus_disabled')) {
53 $ostatus = Protocol::OSTATUS;
55 $ostatus = Protocol::DFRN;
58 // check if we search only communities or every contact
59 if ($mode === 'community') {
60 $extra_sql = ' AND `community`';
67 $results = DBA::p("SELECT `nurl` FROM `gcontact`
68 WHERE NOT `hide` AND `network` IN (?, ?, ?, ?) AND
69 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
70 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
71 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
72 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $search, $search, $search
76 while ($result = DBA::fetch($results)) {
77 $urlparts = parse_url($result['nurl']);
79 // Ignore results that look strange.
80 // For historic reasons the gcontact table does contain some garbage.
81 if (!empty($urlparts['query']) || !empty($urlparts['fragment'])) {
85 $gcontacts[] = Contact::getDetailsByURL($result['nurl'], local_user());
91 * @brief Link the gcontact entry with user, contact and global contact
93 * @param integer $gcid Global contact ID
94 * @param integer $uid User ID
95 * @param integer $cid Contact ID
96 * @param integer $zcid Global Contact ID
100 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
106 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
107 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
111 * @brief Sanitize the given gcontact data
115 * 1: Profiles on this server
116 * 2: Contacts of profiles on this server
117 * 3: Contacts of contacts of profiles on this server
120 * @param array $gcontact array with gcontact data
121 * @return array $gcontact
124 public static function sanitize($gcontact)
126 if (empty($gcontact['url'])) {
127 throw new Exception('URL is empty');
130 $gcontact['server_url'] = $gcontact['server_url'] ?? '';
132 $urlparts = parse_url($gcontact['url']);
133 if (empty($urlparts['scheme'])) {
134 throw new Exception('This (' . $gcontact['url'] . ") doesn't seem to be an url.");
137 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
138 throw new Exception('Contact from a non federated network ignored. (' . $gcontact['url'] . ')');
141 // Don't store the statusnet connector as network
142 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
143 if ($gcontact['network'] == Protocol::STATUSNET) {
144 $gcontact['network'] = '';
147 // Assure that there are no parameter fragments in the profile url
148 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
149 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
152 // The global contacts should contain the original picture, not the cached one
153 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(DI::baseUrl() . '/photo/'))) {
154 $gcontact['photo'] = '';
157 if (empty($gcontact['network'])) {
158 $gcontact['network'] = '';
160 $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
161 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
162 $contact = DBA::selectFirst('contact', ['network'], $condition);
163 if (DBA::isResult($contact)) {
164 $gcontact['network'] = $contact['network'];
167 if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
168 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
169 $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
170 $contact = DBA::selectFirst('contact', ['network'], $condition);
171 if (DBA::isResult($contact)) {
172 $gcontact['network'] = $contact['network'];
177 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
178 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
179 if (DBA::isResult($gcnt)) {
180 if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
181 $gcontact['network'] = $gcnt['network'];
183 if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
184 $gcontact['updated'] = $gcnt['updated'];
186 if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
187 $gcontact['server_url'] = $gcnt['server_url'];
189 if (!isset($gcontact['addr'])) {
190 $gcontact['addr'] = $gcnt['addr'];
194 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']))
195 && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
197 $data = Probe::uri($gcontact['url']);
199 if ($data['network'] == Protocol::PHANTOM) {
200 throw new Exception('Probing for URL ' . $gcontact['url'] . ' failed');
203 $orig_profile = $gcontact['url'];
205 $gcontact['server_url'] = $data['baseurl'];
207 $gcontact = array_merge($gcontact, $data);
210 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
211 throw new Exception('No name and photo for URL '.$gcontact['url']);
214 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
215 throw new Exception('No federated network (' . $gcontact['network'] . ') detected for URL ' . $gcontact['url']);
218 if (empty($gcontact['server_url'])) {
219 // We check the server url to be sure that it is a real one
220 $server_url = self::getBasepath($gcontact['url']);
222 // We are now sure that it is a correct URL. So we use it in the future
223 if ($server_url != '') {
224 $gcontact['server_url'] = $server_url;
228 // The server URL doesn't seem to be valid, so we don't store it.
229 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
230 $gcontact['server_url'] = '';
237 * @param integer $uid id
238 * @param integer $cid id
242 public static function countCommonFriends($uid, $cid)
245 "SELECT count(*) as `total`
246 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
247 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
248 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
249 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
250 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d) ",
257 if (DBA::isResult($r)) {
258 return $r[0]['total'];
264 * @param integer $uid id
265 * @param integer $zcid zcid
269 public static function countCommonFriendsZcid($uid, $zcid)
272 "SELECT count(*) as `total`
273 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
274 where `glink`.`zcid` = %d
275 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0) ",
280 if (DBA::isResult($r)) {
281 return $r[0]['total'];
288 * @param integer $uid user
289 * @param integer $cid cid
290 * @param integer $start optional, default 0
291 * @param integer $limit optional, default 9999
292 * @param boolean $shuffle optional, default false
296 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
299 $sql_extra = " order by rand() ";
301 $sql_extra = " order by `gcontact`.`name` asc ";
305 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
307 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
308 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
309 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
310 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
311 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
312 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
313 $sql_extra LIMIT %d, %d",
322 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
327 * @param integer $uid user
328 * @param integer $zcid zcid
329 * @param integer $start optional, default 0
330 * @param integer $limit optional, default 9999
331 * @param boolean $shuffle optional, default false
335 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
338 $sql_extra = " order by rand() ";
340 $sql_extra = " order by `gcontact`.`name` asc ";
345 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
346 where `glink`.`zcid` = %d
347 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0)
348 $sql_extra limit %d, %d",
355 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
360 * @param integer $uid user
361 * @param integer $cid cid
365 public static function countAllFriends($uid, $cid)
368 "SELECT count(*) as `total`
369 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
370 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
371 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
376 if (DBA::isResult($r)) {
377 return $r[0]['total'];
384 * @param integer $uid user
385 * @param integer $cid cid
386 * @param integer $start optional, default 0
387 * @param integer $limit optional, default 80
391 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
394 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
396 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
397 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
398 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
399 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
400 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
408 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
413 * @param int $uid user
414 * @param integer $start optional, default 0
415 * @param integer $limit optional, default 80
417 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
419 public static function suggestionQuery($uid, $start = 0, $limit = 80)
425 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
427 if (Config::get('system', 'diaspora_enabled')) {
428 $network[] = Protocol::DIASPORA;
431 if (!Config::get('system', 'ostatus_disabled')) {
432 $network[] = Protocol::OSTATUS;
435 $sql_network = "'" . implode("', '", $network) . "'";
437 /// @todo This query is really slow
438 // By now we cache the data for five minutes
440 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
441 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
442 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
443 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
444 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
445 AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
446 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
447 AND `gcontact`.`network` IN (%s)
448 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
459 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
464 "SELECT gcontact.* FROM gcontact
465 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
466 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
467 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
468 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
469 AND `gcontact`.`updated` >= '%s'
470 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
471 AND `gcontact`.`network` IN (%s)
472 ORDER BY rand() LIMIT %d, %d",
483 foreach ($r2 as $suggestion) {
484 $list[$suggestion['nurl']] = $suggestion;
487 foreach ($r as $suggestion) {
488 $list[$suggestion['nurl']] = $suggestion;
491 while (sizeof($list) > ($limit)) {
500 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
502 public static function updateSuggestions()
506 /// @TODO Check if it is really neccessary to poll the own server
507 PortableContact::loadWorker(0, 0, 0, DI::baseUrl() . '/poco');
509 $done[] = DI::baseUrl() . '/poco';
511 if (strlen(Config::get('system', 'directory'))) {
512 $x = Network::fetchUrl(Search::getGlobalDirectory() . '/pubsites');
514 $j = json_decode($x);
515 if (!empty($j->entries)) {
516 foreach ($j->entries as $entry) {
517 GServer::check($entry->url);
519 $url = $entry->url . '/poco';
520 if (!in_array($url, $done)) {
521 PortableContact::loadWorker(0, 0, 0, $url);
529 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
530 $contacts = DBA::p("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN (?, ?)", Protocol::DFRN, Protocol::DIASPORA);
531 while ($contact = DBA::fetch($contacts)) {
532 $base = substr($contact['poco'], 0, strrpos($contact['poco'], '/'));
533 if (!in_array($base, $done)) {
534 PortableContact::loadWorker(0, 0, 0, $base);
540 * @brief Removes unwanted parts from a contact url
542 * @param string $url Contact url
544 * @return string Contact url with the wanted parts
547 public static function cleanContactUrl($url)
549 $parts = parse_url($url);
551 if (empty($parts['scheme']) || empty($parts['host'])) {
555 $new_url = $parts['scheme'] . '://' . $parts['host'];
557 if (!empty($parts['port'])) {
558 $new_url .= ':' . $parts['port'];
561 if (!empty($parts['path'])) {
562 $new_url .= $parts['path'];
565 if ($new_url != $url) {
566 Logger::info('Cleaned contact url', ['url' => $url, 'new_url' => $new_url, 'callstack' => System::callstack()]);
573 * @brief Fetch the gcontact id, add an entry if not existed
575 * @param array $contact contact array
577 * @return bool|int Returns false if not found, integer if contact was found
578 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
579 * @throws \ImagickException
581 public static function getId($contact)
585 if (empty($contact['network'])) {
586 Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
590 if (in_array($contact['network'], [Protocol::PHANTOM])) {
591 Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
595 if ($contact['network'] == Protocol::STATUSNET) {
596 $contact['network'] = Protocol::OSTATUS;
599 // All new contacts are hidden by default
600 if (!isset($contact['hide'])) {
601 $contact['hide'] = true;
604 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
605 if (in_array($contact['network'], Protocol::FEDERATED)) {
606 $contact['url'] = self::cleanContactUrl($contact['url']);
609 DBA::lock('gcontact');
610 $fields = ['id', 'last_contact', 'last_failure', 'network'];
611 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
612 if (DBA::isResult($gcnt)) {
613 $gcontact_id = $gcnt['id'];
615 $contact['location'] = $contact['location'] ?? '';
616 $contact['about'] = $contact['about'] ?? '';
617 $contact['generation'] = $contact['generation'] ?? 0;
619 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'] ?? '', 'addr' => $contact['addr'] ?? '', 'network' => $contact['network'],
620 'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
621 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
622 'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation']];
624 DBA::insert('gcontact', $fields);
626 $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
627 $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
628 if (DBA::isResult($cnt)) {
629 $gcontact_id = $cnt['id'];
638 * @brief Updates the gcontact table from a given array
640 * @param array $contact contact array
642 * @return bool|int Returns false if not found, integer if contact was found
643 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
644 * @throws \ImagickException
646 public static function update($contact)
648 // Check for invalid "contact-type" value
649 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
650 $contact['contact-type'] = 0;
653 /// @todo update contact table as well
655 $gcontact_id = self::getId($contact);
661 $public_contact = DBA::selectFirst('gcontact', [
662 'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'gender', 'keywords',
663 'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
664 ], ['id' => $gcontact_id]);
666 if (!DBA::isResult($public_contact)) {
670 // Get all field names
672 foreach ($public_contact as $field => $data) {
673 $fields[$field] = $data;
676 unset($fields['url']);
677 unset($fields['updated']);
678 unset($fields['hide']);
680 // Bugfix: We had an error in the storing of keywords which lead to the "0"
681 // This value is still transmitted via poco.
682 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
683 unset($contact['keywords']);
686 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
687 $public_contact['keywords'] = '';
690 // assign all unassigned fields from the database entry
691 foreach ($fields as $field => $data) {
692 if (empty($contact[$field])) {
693 $contact[$field] = $public_contact[$field];
697 if (!isset($contact['hide'])) {
698 $contact['hide'] = $public_contact['hide'];
701 $fields['hide'] = $public_contact['hide'];
703 if ($contact['network'] == Protocol::STATUSNET) {
704 $contact['network'] = Protocol::OSTATUS;
707 if (!isset($contact['updated'])) {
708 $contact['updated'] = DateTimeFormat::utcNow();
711 if ($contact['network'] == Protocol::TWITTER) {
712 $contact['server_url'] = 'http://twitter.com';
715 if (empty($contact['server_url'])) {
716 $data = Probe::uri($contact['url']);
717 if ($data['network'] != Protocol::PHANTOM) {
718 $contact['server_url'] = $data['baseurl'];
721 $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
724 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
725 $hostname = str_replace('http://', '', $contact['server_url']);
726 $contact['addr'] = $contact['nick'] . '@' . $hostname;
729 // Check if any field changed
731 unset($fields['generation']);
733 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
734 foreach ($fields as $field => $data) {
735 if ($contact[$field] != $public_contact[$field]) {
736 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
741 if ($contact['generation'] < $public_contact['generation']) {
742 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
748 Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
749 $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
750 Strings::normaliseLink($contact['url']), $contact['generation']];
751 $contact['updated'] = DateTimeFormat::utc($contact['updated']);
754 'photo' => $contact['photo'], 'name' => $contact['name'],
755 'nick' => $contact['nick'], 'addr' => $contact['addr'],
756 'network' => $contact['network'], 'birthday' => $contact['birthday'],
757 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
758 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
759 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
760 'notify' => $contact['notify'], 'url' => $contact['url'],
761 'location' => $contact['location'], 'about' => $contact['about'],
762 'generation' => $contact['generation'], 'updated' => $contact['updated'],
763 'server_url' => $contact['server_url'], 'connect' => $contact['connect']
766 DBA::update('gcontact', $updated, $condition, $fields);
773 * Set the last date that the contact had posted something
775 * @param string $data Probing result
776 * @param bool $force force updating
778 public static function setLastUpdate(array $data, bool $force = false)
780 // Fetch the global contact
781 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
782 ['nurl' => Strings::normaliseLink($data['url'])]);
783 if (!DBA::isResult($gcontact)) {
787 if (!$force && !GServer::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
788 Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
792 if (self::updateFromNoScrape($data)) {
796 if (!empty($data['outbox'])) {
797 self::updateFromOutbox($data['outbox'], $data);
798 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
799 self::updateFromOutbox($data['poll'], $data);
800 } elseif (!empty($data['poll'])) {
801 self::updateFromFeed($data);
806 * Update a global contact via the "noscrape" endpoint
808 * @param string $data Probing result
810 * @return bool 'true' if update was successful or the server was unreachable
812 private static function updateFromNoScrape(array $data)
814 // Check the 'noscrape' endpoint when it is a Friendica server
815 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
816 Strings::normaliseLink($data['baseurl'])]);
817 if (!DBA::isResult($gserver)) {
821 $curlResult = Network::curl($gserver['noscrape'] . '/' . $data['nick']);
823 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
824 $noscrape = json_decode($curlResult->getBody(), true);
825 if (!empty($noscrape) && !empty($noscrape['updated'])) {
826 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
827 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
828 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
831 } elseif ($curlResult->isTimeout()) {
832 // On a timeout return the existing value, but mark the contact as failure
833 $fields = ['last_failure' => DateTimeFormat::utcNow()];
834 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
841 * Update a global contact via an ActivityPub Outbox
843 * @param string $feed
844 * @param array $data Probing result
845 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
847 private static function updateFromOutbox(string $feed, array $data)
849 $outbox = ActivityPub::fetchContent($feed);
850 if (empty($outbox)) {
854 if (!empty($outbox['orderedItems'])) {
855 $items = $outbox['orderedItems'];
856 } elseif (!empty($outbox['first']['orderedItems'])) {
857 $items = $outbox['first']['orderedItems'];
858 } elseif (!empty($outbox['first']['href'])) {
859 self::updateFromOutbox($outbox['first']['href'], $data);
861 } elseif (!empty($outbox['first'])) {
862 if (is_string($outbox['first'])) {
863 self::updateFromOutbox($outbox['first'], $data);
865 Logger::warning('Unexpected data', ['outbox' => $outbox]);
873 foreach ($items as $activity) {
874 if (!empty($activity['published'])) {
875 $published = DateTimeFormat::utc($activity['published']);
876 } elseif (!empty($activity['object']['published'])) {
877 $published = DateTimeFormat::utc($activity['object']['published']);
882 if ($last_updated < $published) {
883 $last_updated = $published;
887 if (empty($last_updated)) {
891 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
892 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
896 * Update a global contact via an XML feed
898 * @param string $data Probing result
900 private static function updateFromFeed(array $data)
902 // Search for the newest entry in the feed
903 $curlResult = Network::curl($data['poll']);
904 if (!$curlResult->isSuccess()) {
905 $fields = ['last_failure' => DateTimeFormat::utcNow()];
906 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
908 Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
912 $doc = new DOMDocument();
913 @$doc->loadXML($curlResult->getBody());
915 $xpath = new DOMXPath($doc);
916 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
918 $entries = $xpath->query('/atom:feed/atom:entry');
922 foreach ($entries as $entry) {
923 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
924 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
925 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
926 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
928 if (empty($published) || empty($updated)) {
929 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
933 if ($last_updated < $published) {
934 $last_updated = $published;
937 if ($last_updated < $updated) {
938 $last_updated = $updated;
942 if (empty($last_updated)) {
946 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
947 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
950 * @brief Updates the gcontact entry from a given public contact id
952 * @param integer $cid contact id
954 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
955 * @throws \ImagickException
957 public static function updateFromPublicContactID($cid)
959 self::updateFromPublicContact(['id' => $cid]);
963 * @brief Updates the gcontact entry from a given public contact url
965 * @param string $url contact url
966 * @return integer gcontact id
967 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
968 * @throws \ImagickException
970 public static function updateFromPublicContactURL($url)
972 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
976 * @brief Helper function for updateFromPublicContactID and updateFromPublicContactURL
978 * @param array $condition contact condition
979 * @return integer gcontact id
980 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
981 * @throws \ImagickException
983 private static function updateFromPublicContact($condition)
985 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
986 'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
987 'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
988 'baseurl', 'sensitive', 'unsearchable'];
990 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
991 if (!DBA::isResult($contact)) {
995 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender', 'generation',
996 'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
997 'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
998 'server_url', 'nsfw', 'hide', 'id'];
1000 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
1001 $do_insert = !DBA::isResult($old_gcontact);
1008 // These fields are identical in both contact and gcontact
1009 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
1010 'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated'];
1012 foreach ($fields as $field) {
1013 $gcontact[$field] = $contact[$field];
1016 // These fields are having different names but the same content
1017 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
1018 $gcontact['nsfw'] = $contact['sensitive'];
1019 $gcontact['hide'] = $contact['unsearchable'];
1020 $gcontact['archived'] = $contact['archive'];
1021 $gcontact['archive_date'] = $contact['term-date'];
1022 $gcontact['birthday'] = $contact['bd'];
1023 $gcontact['photo'] = $contact['avatar'];
1024 $gcontact['last_contact'] = $contact['success_update'];
1025 $gcontact['last_failure'] = $contact['failure_update'];
1026 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
1028 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
1029 if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
1030 unset($gcontact[$field]);
1034 if (!$gcontact['archived']) {
1035 $gcontact['archive_date'] = DBA::NULL_DATETIME;
1038 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
1039 && ($old_gcontact['created'] <= $gcontact['created'])) {
1040 unset($gcontact['created']);
1043 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
1044 unset($gcontact['birthday']);
1047 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
1048 $gcontact['generation'] = 2; // We fetched the data directly from the other server
1052 DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
1053 return $old_gcontact['id'];
1054 } elseif (!$gcontact['archived']) {
1055 DBA::insert('gcontact', $gcontact);
1056 return DBA::lastInsertId();
1061 * @brief Updates the gcontact entry from probe
1063 * @param string $url profile link
1064 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1066 * @return boolean 'true' when contact had been updated
1068 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1069 * @throws \ImagickException
1071 public static function updateFromProbe($url, $force = false)
1073 $data = Probe::uri($url, $force);
1075 if (in_array($data['network'], [Protocol::PHANTOM])) {
1076 $fields = ['last_failure' => DateTimeFormat::utcNow()];
1077 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1078 Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
1082 $data['server_url'] = $data['baseurl'];
1084 self::update($data);
1086 // Set the date of the latest post
1087 self::setLastUpdate($data, $force);
1093 * @brief Update the gcontact entry for a given user id
1095 * @param int $uid User ID
1097 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1098 * @throws \ImagickException
1100 public static function updateForUser($uid)
1102 $profile = Profile::getByUID($uid);
1103 if (empty($profile)) {
1104 Logger::error('Cannot find profile', ['uid' => $uid]);
1108 $user = User::getOwnerDataById($uid);
1110 Logger::error('Cannot find user', ['uid' => $uid]);
1114 $userdata = array_merge($profile, $user);
1116 $location = Profile::formatLocation(
1117 ['locality' => $userdata['locality'], 'region' => $userdata['region'], 'country-name' => $userdata['country-name']]
1120 $gcontact = ['name' => $userdata['name'], 'location' => $location, 'about' => $userdata['about'],
1121 'gender' => $userdata['gender'], 'keywords' => $userdata['pub_keywords'],
1122 'birthday' => $userdata['dob'], 'photo' => $userdata['photo'],
1123 "notify" => $userdata['notify'], 'url' => $userdata['url'],
1124 "hide" => ($userdata['hidewall'] || !$userdata['net-publish']),
1125 'nick' => $userdata['nickname'], 'addr' => $userdata['addr'],
1126 "connect" => $userdata['addr'], "server_url" => DI::baseUrl(),
1127 "generation" => 1, 'network' => Protocol::DFRN];
1129 self::update($gcontact);
1133 * @brief Get the basepath for a given contact link
1135 * @param string $url The gcontact link
1136 * @param boolean $dont_update Don't update the contact
1138 * @return string basepath
1139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1140 * @throws \ImagickException
1142 public static function getBasepath($url, $dont_update = false)
1144 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1145 if (!empty($gcontact['server_url'])) {
1146 return $gcontact['server_url'];
1147 } elseif ($dont_update) {
1151 self::updateFromProbe($url, true);
1154 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1155 if (empty($gcontact['server_url'])) {
1156 Logger::info('No baseurl for gcontact', ['url' => $url]);
1160 Logger::info('Found baseurl for gcontact', ['url' => $url, 'baseurl' => $gcontact['server_url']]);
1161 return $gcontact['server_url'];
1165 * @brief Fetches users of given GNU Social server
1167 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1169 * @param string $server Server address
1171 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1172 * @throws \ImagickException
1174 public static function fetchGsUsers($server)
1176 Logger::info('Fetching users from GNU Social server', ['server' => $server]);
1178 $url = $server . '/main/statistics';
1180 $curlResult = Network::curl($url);
1181 if (!$curlResult->isSuccess()) {
1185 $statistics = json_decode($curlResult->getBody());
1187 if (!empty($statistics->config->instance_address)) {
1188 if (!empty($statistics->config->instance_with_ssl)) {
1189 $server = 'https://';
1191 $server = 'http://';
1194 $server .= $statistics->config->instance_address;
1196 $hostname = $statistics->config->instance_address;
1197 } elseif (!empty($statistics->instance_address)) {
1198 if (!empty($statistics->instance_with_ssl)) {
1199 $server = 'https://';
1201 $server = 'http://';
1204 $server .= $statistics->instance_address;
1206 $hostname = $statistics->instance_address;
1209 if (!empty($statistics->users)) {
1210 foreach ($statistics->users as $nick => $user) {
1211 $profile_url = $server . '/' . $user->nickname;
1213 $contact = ['url' => $profile_url,
1214 'name' => $user->fullname,
1215 'addr' => $user->nickname . '@' . $hostname,
1216 'nick' => $user->nickname,
1217 "network" => Protocol::OSTATUS,
1218 'photo' => DI::baseUrl() . '/images/person-300.jpg'];
1220 if (isset($user->bio)) {
1221 $contact['about'] = $user->bio;
1224 self::getId($contact);
1230 * @brief Asking GNU Social server on a regular base for their user data
1232 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1233 * @throws \ImagickException
1235 public static function discoverGsUsers()
1237 $requery_days = intval(Config::get('system', 'poco_requery_days'));
1239 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1241 $r = DBA::select('gserver', ['nurl', 'url'], [
1243 AND `last_contact` >= `last_failure`
1244 AND `last_poco_query` < ?',
1249 'order' => ['RAND()']
1252 if (!DBA::isResult($r)) {
1256 foreach ($r as $server) {
1257 self::fetchGsUsers($server['url']);
1258 DBA::update('gserver', ['last_poco_query' => DateTimeFormat::utcNow()], ['nurl' => $server['nurl']]);
1263 * Returns a random, global contact of the current node
1265 * @return string The profile URL
1268 public static function getRandomUrl()
1270 $r = DBA::selectFirst('gcontact', ['url'], [
1272 AND `last_contact` >= `last_failure`
1275 DateTimeFormat::utc('now - 1 month'),
1276 ], ['order' => ['RAND()']]);
1278 if (DBA::isResult($r)) {