3 * @file src/Model/GlobalContact.php
4 * This file includes the GlobalContact class with directory related functions
6 namespace Friendica\Model;
11 use Friendica\Core\Logger;
12 use Friendica\Core\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Core\Search;
15 use Friendica\Database\DBA;
17 use Friendica\Network\Probe;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Protocol\PortableContact;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Network;
22 use Friendica\Util\Strings;
25 * This class handles GlobalContact related functions
30 * Search global contact table by nick or name
32 * @param string $search Name or nick
33 * @param string $mode Search mode (e.g. "community")
35 * @return array with search results
36 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
38 public static function searchByName($search, $mode = '')
44 // check supported networks
45 if (DI::config()->get('system', 'diaspora_enabled')) {
46 $diaspora = Protocol::DIASPORA;
48 $diaspora = Protocol::DFRN;
51 if (!DI::config()->get('system', 'ostatus_disabled')) {
52 $ostatus = Protocol::OSTATUS;
54 $ostatus = Protocol::DFRN;
57 // check if we search only communities or every contact
58 if ($mode === 'community') {
59 $extra_sql = ' AND `community`';
66 $results = DBA::p("SELECT `nurl` FROM `gcontact`
67 WHERE NOT `hide` AND `network` IN (?, ?, ?, ?) AND
68 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
69 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
70 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
71 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $search, $search, $search
75 while ($result = DBA::fetch($results)) {
76 $urlparts = parse_url($result['nurl']);
78 // Ignore results that look strange.
79 // For historic reasons the gcontact table does contain some garbage.
80 if (!empty($urlparts['query']) || !empty($urlparts['fragment'])) {
84 $gcontacts[] = Contact::getDetailsByURL($result['nurl'], local_user());
90 * Link the gcontact entry with user, contact and global contact
92 * @param integer $gcid Global contact ID
93 * @param integer $uid User ID
94 * @param integer $cid Contact ID
95 * @param integer $zcid Global Contact ID
99 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
105 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
106 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
110 * Sanitize the given gcontact data
114 * 1: Profiles on this server
115 * 2: Contacts of profiles on this server
116 * 3: Contacts of contacts of profiles on this server
119 * @param array $gcontact array with gcontact data
120 * @return array $gcontact
123 public static function sanitize($gcontact)
125 if (empty($gcontact['url'])) {
126 throw new Exception('URL is empty');
129 $gcontact['server_url'] = $gcontact['server_url'] ?? '';
131 $urlparts = parse_url($gcontact['url']);
132 if (empty($urlparts['scheme'])) {
133 throw new Exception('This (' . $gcontact['url'] . ") doesn't seem to be an url.");
136 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
137 throw new Exception('Contact from a non federated network ignored. (' . $gcontact['url'] . ')');
140 // Don't store the statusnet connector as network
141 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
142 if ($gcontact['network'] == Protocol::STATUSNET) {
143 $gcontact['network'] = '';
146 // Assure that there are no parameter fragments in the profile url
147 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
148 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
151 // The global contacts should contain the original picture, not the cached one
152 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(DI::baseUrl() . '/photo/'))) {
153 $gcontact['photo'] = '';
156 if (empty($gcontact['network'])) {
157 $gcontact['network'] = '';
159 $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
160 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
161 $contact = DBA::selectFirst('contact', ['network'], $condition);
162 if (DBA::isResult($contact)) {
163 $gcontact['network'] = $contact['network'];
166 if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
167 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
168 $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
169 $contact = DBA::selectFirst('contact', ['network'], $condition);
170 if (DBA::isResult($contact)) {
171 $gcontact['network'] = $contact['network'];
176 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
177 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
178 if (DBA::isResult($gcnt)) {
179 if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
180 $gcontact['network'] = $gcnt['network'];
182 if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
183 $gcontact['updated'] = $gcnt['updated'];
185 if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
186 $gcontact['server_url'] = $gcnt['server_url'];
188 if (!isset($gcontact['addr'])) {
189 $gcontact['addr'] = $gcnt['addr'];
193 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']))
194 && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
196 $data = Probe::uri($gcontact['url']);
198 if ($data['network'] == Protocol::PHANTOM) {
199 throw new Exception('Probing for URL ' . $gcontact['url'] . ' failed');
202 $orig_profile = $gcontact['url'];
204 $gcontact['server_url'] = $data['baseurl'];
206 $gcontact = array_merge($gcontact, $data);
209 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
210 throw new Exception('No name and photo for URL '.$gcontact['url']);
213 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
214 throw new Exception('No federated network (' . $gcontact['network'] . ') detected for URL ' . $gcontact['url']);
217 if (empty($gcontact['server_url'])) {
218 // We check the server url to be sure that it is a real one
219 $server_url = self::getBasepath($gcontact['url']);
221 // We are now sure that it is a correct URL. So we use it in the future
222 if ($server_url != '') {
223 $gcontact['server_url'] = $server_url;
227 // The server URL doesn't seem to be valid, so we don't store it.
228 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
229 $gcontact['server_url'] = '';
236 * @param integer $uid id
237 * @param integer $cid id
241 public static function countCommonFriends($uid, $cid)
244 "SELECT count(*) as `total`
245 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
246 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
247 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
248 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
249 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d) ",
256 if (DBA::isResult($r)) {
257 return $r[0]['total'];
263 * @param integer $uid id
264 * @param integer $zcid zcid
268 public static function countCommonFriendsZcid($uid, $zcid)
271 "SELECT count(*) as `total`
272 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
273 where `glink`.`zcid` = %d
274 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0) ",
279 if (DBA::isResult($r)) {
280 return $r[0]['total'];
287 * @param integer $uid user
288 * @param integer $cid cid
289 * @param integer $start optional, default 0
290 * @param integer $limit optional, default 9999
291 * @param boolean $shuffle optional, default false
295 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
298 $sql_extra = " order by rand() ";
300 $sql_extra = " order by `gcontact`.`name` asc ";
304 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
306 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
307 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
308 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
309 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
310 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
311 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
312 $sql_extra LIMIT %d, %d",
321 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
326 * @param integer $uid user
327 * @param integer $zcid zcid
328 * @param integer $start optional, default 0
329 * @param integer $limit optional, default 9999
330 * @param boolean $shuffle optional, default false
334 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
337 $sql_extra = " order by rand() ";
339 $sql_extra = " order by `gcontact`.`name` asc ";
344 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
345 where `glink`.`zcid` = %d
346 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0)
347 $sql_extra limit %d, %d",
354 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
359 * @param integer $uid user
360 * @param integer $cid cid
364 public static function countAllFriends($uid, $cid)
367 "SELECT count(*) as `total`
368 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
369 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
370 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
375 if (DBA::isResult($r)) {
376 return $r[0]['total'];
383 * @param integer $uid user
384 * @param integer $cid cid
385 * @param integer $start optional, default 0
386 * @param integer $limit optional, default 80
390 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
393 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
395 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
396 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
397 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
398 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
399 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
407 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
412 * @param int $uid user
413 * @param integer $start optional, default 0
414 * @param integer $limit optional, default 80
416 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418 public static function suggestionQuery($uid, $start = 0, $limit = 80)
424 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
426 if (DI::config()->get('system', 'diaspora_enabled')) {
427 $network[] = Protocol::DIASPORA;
430 if (!DI::config()->get('system', 'ostatus_disabled')) {
431 $network[] = Protocol::OSTATUS;
434 $sql_network = "'" . implode("', '", $network) . "'";
436 /// @todo This query is really slow
437 // By now we cache the data for five minutes
439 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
440 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
441 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
442 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
443 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
444 AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
445 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
446 AND `gcontact`.`network` IN (%s)
447 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
458 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
463 "SELECT gcontact.* FROM gcontact
464 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
465 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
466 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
467 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
468 AND `gcontact`.`updated` >= '%s'
469 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
470 AND `gcontact`.`network` IN (%s)
471 ORDER BY rand() LIMIT %d, %d",
482 foreach ($r2 as $suggestion) {
483 $list[$suggestion['nurl']] = $suggestion;
486 foreach ($r as $suggestion) {
487 $list[$suggestion['nurl']] = $suggestion;
490 while (sizeof($list) > ($limit)) {
499 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501 public static function updateSuggestions()
505 /// @TODO Check if it is really neccessary to poll the own server
506 PortableContact::loadWorker(0, 0, 0, DI::baseUrl() . '/poco');
508 $done[] = DI::baseUrl() . '/poco';
510 if (strlen(DI::config()->get('system', 'directory'))) {
511 $x = Network::fetchUrl(Search::getGlobalDirectory() . '/pubsites');
513 $j = json_decode($x);
514 if (!empty($j->entries)) {
515 foreach ($j->entries as $entry) {
516 GServer::check($entry->url);
518 $url = $entry->url . '/poco';
519 if (!in_array($url, $done)) {
520 PortableContact::loadWorker(0, 0, 0, $url);
528 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
529 $contacts = DBA::p("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN (?, ?)", Protocol::DFRN, Protocol::DIASPORA);
530 while ($contact = DBA::fetch($contacts)) {
531 $base = substr($contact['poco'], 0, strrpos($contact['poco'], '/'));
532 if (!in_array($base, $done)) {
533 PortableContact::loadWorker(0, 0, 0, $base);
539 * Removes unwanted parts from a contact url
541 * @param string $url Contact url
543 * @return string Contact url with the wanted parts
546 public static function cleanContactUrl($url)
548 $parts = parse_url($url);
550 if (empty($parts['scheme']) || empty($parts['host'])) {
554 $new_url = $parts['scheme'] . '://' . $parts['host'];
556 if (!empty($parts['port'])) {
557 $new_url .= ':' . $parts['port'];
560 if (!empty($parts['path'])) {
561 $new_url .= $parts['path'];
564 if ($new_url != $url) {
565 Logger::info('Cleaned contact url', ['url' => $url, 'new_url' => $new_url, 'callstack' => System::callstack()]);
572 * Fetch the gcontact id, add an entry if not existed
574 * @param array $contact contact array
576 * @return bool|int Returns false if not found, integer if contact was found
577 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
578 * @throws \ImagickException
580 public static function getId($contact)
584 if (empty($contact['network'])) {
585 Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
589 if (in_array($contact['network'], [Protocol::PHANTOM])) {
590 Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
594 if ($contact['network'] == Protocol::STATUSNET) {
595 $contact['network'] = Protocol::OSTATUS;
598 // All new contacts are hidden by default
599 if (!isset($contact['hide'])) {
600 $contact['hide'] = true;
603 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
604 if (in_array($contact['network'], Protocol::FEDERATED)) {
605 $contact['url'] = self::cleanContactUrl($contact['url']);
608 DBA::lock('gcontact');
609 $fields = ['id', 'last_contact', 'last_failure', 'network'];
610 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
611 if (DBA::isResult($gcnt)) {
612 $gcontact_id = $gcnt['id'];
614 $contact['location'] = $contact['location'] ?? '';
615 $contact['about'] = $contact['about'] ?? '';
616 $contact['generation'] = $contact['generation'] ?? 0;
618 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'] ?? '', 'addr' => $contact['addr'] ?? '', 'network' => $contact['network'],
619 'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
620 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
621 'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation']];
623 DBA::insert('gcontact', $fields);
625 $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
626 $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
627 if (DBA::isResult($cnt)) {
628 $gcontact_id = $cnt['id'];
637 * Updates the gcontact table from a given array
639 * @param array $contact contact array
641 * @return bool|int Returns false if not found, integer if contact was found
642 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
643 * @throws \ImagickException
645 public static function update($contact)
647 // Check for invalid "contact-type" value
648 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
649 $contact['contact-type'] = 0;
652 /// @todo update contact table as well
654 $gcontact_id = self::getId($contact);
660 $public_contact = DBA::selectFirst('gcontact', [
661 'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'gender', 'keywords',
662 'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
663 ], ['id' => $gcontact_id]);
665 if (!DBA::isResult($public_contact)) {
669 // Get all field names
671 foreach ($public_contact as $field => $data) {
672 $fields[$field] = $data;
675 unset($fields['url']);
676 unset($fields['updated']);
677 unset($fields['hide']);
679 // Bugfix: We had an error in the storing of keywords which lead to the "0"
680 // This value is still transmitted via poco.
681 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
682 unset($contact['keywords']);
685 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
686 $public_contact['keywords'] = '';
689 // assign all unassigned fields from the database entry
690 foreach ($fields as $field => $data) {
691 if (empty($contact[$field])) {
692 $contact[$field] = $public_contact[$field];
696 if (!isset($contact['hide'])) {
697 $contact['hide'] = $public_contact['hide'];
700 $fields['hide'] = $public_contact['hide'];
702 if ($contact['network'] == Protocol::STATUSNET) {
703 $contact['network'] = Protocol::OSTATUS;
706 if (!isset($contact['updated'])) {
707 $contact['updated'] = DateTimeFormat::utcNow();
710 if ($contact['network'] == Protocol::TWITTER) {
711 $contact['server_url'] = 'http://twitter.com';
714 if (empty($contact['server_url'])) {
715 $data = Probe::uri($contact['url']);
716 if ($data['network'] != Protocol::PHANTOM) {
717 $contact['server_url'] = $data['baseurl'];
720 $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
723 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
724 $hostname = str_replace('http://', '', $contact['server_url']);
725 $contact['addr'] = $contact['nick'] . '@' . $hostname;
728 // Check if any field changed
730 unset($fields['generation']);
732 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
733 foreach ($fields as $field => $data) {
734 if ($contact[$field] != $public_contact[$field]) {
735 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
740 if ($contact['generation'] < $public_contact['generation']) {
741 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
747 Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
748 $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
749 Strings::normaliseLink($contact['url']), $contact['generation']];
750 $contact['updated'] = DateTimeFormat::utc($contact['updated']);
753 'photo' => $contact['photo'], 'name' => $contact['name'],
754 'nick' => $contact['nick'], 'addr' => $contact['addr'],
755 'network' => $contact['network'], 'birthday' => $contact['birthday'],
756 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
757 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
758 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
759 'notify' => $contact['notify'], 'url' => $contact['url'],
760 'location' => $contact['location'], 'about' => $contact['about'],
761 'generation' => $contact['generation'], 'updated' => $contact['updated'],
762 'server_url' => $contact['server_url'], 'connect' => $contact['connect']
765 DBA::update('gcontact', $updated, $condition, $fields);
772 * Set the last date that the contact had posted something
774 * @param string $data Probing result
775 * @param bool $force force updating
777 public static function setLastUpdate(array $data, bool $force = false)
779 // Fetch the global contact
780 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
781 ['nurl' => Strings::normaliseLink($data['url'])]);
782 if (!DBA::isResult($gcontact)) {
786 if (!$force && !GServer::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
787 Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
791 if (self::updateFromNoScrape($data)) {
795 if (!empty($data['outbox'])) {
796 self::updateFromOutbox($data['outbox'], $data);
797 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
798 self::updateFromOutbox($data['poll'], $data);
799 } elseif (!empty($data['poll'])) {
800 self::updateFromFeed($data);
805 * Update a global contact via the "noscrape" endpoint
807 * @param string $data Probing result
809 * @return bool 'true' if update was successful or the server was unreachable
811 private static function updateFromNoScrape(array $data)
813 // Check the 'noscrape' endpoint when it is a Friendica server
814 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
815 Strings::normaliseLink($data['baseurl'])]);
816 if (!DBA::isResult($gserver)) {
820 $curlResult = Network::curl($gserver['noscrape'] . '/' . $data['nick']);
822 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
823 $noscrape = json_decode($curlResult->getBody(), true);
824 if (!empty($noscrape) && !empty($noscrape['updated'])) {
825 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
826 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
827 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
830 } elseif ($curlResult->isTimeout()) {
831 // On a timeout return the existing value, but mark the contact as failure
832 $fields = ['last_failure' => DateTimeFormat::utcNow()];
833 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
840 * Update a global contact via an ActivityPub Outbox
842 * @param string $feed
843 * @param array $data Probing result
844 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
846 private static function updateFromOutbox(string $feed, array $data)
848 $outbox = ActivityPub::fetchContent($feed);
849 if (empty($outbox)) {
853 if (!empty($outbox['orderedItems'])) {
854 $items = $outbox['orderedItems'];
855 } elseif (!empty($outbox['first']['orderedItems'])) {
856 $items = $outbox['first']['orderedItems'];
857 } elseif (!empty($outbox['first']['href'])) {
858 self::updateFromOutbox($outbox['first']['href'], $data);
860 } elseif (!empty($outbox['first'])) {
861 if (is_string($outbox['first'])) {
862 self::updateFromOutbox($outbox['first'], $data);
864 Logger::warning('Unexpected data', ['outbox' => $outbox]);
872 foreach ($items as $activity) {
873 if (!empty($activity['published'])) {
874 $published = DateTimeFormat::utc($activity['published']);
875 } elseif (!empty($activity['object']['published'])) {
876 $published = DateTimeFormat::utc($activity['object']['published']);
881 if ($last_updated < $published) {
882 $last_updated = $published;
886 if (empty($last_updated)) {
890 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
891 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
895 * Update a global contact via an XML feed
897 * @param string $data Probing result
899 private static function updateFromFeed(array $data)
901 // Search for the newest entry in the feed
902 $curlResult = Network::curl($data['poll']);
903 if (!$curlResult->isSuccess()) {
904 $fields = ['last_failure' => DateTimeFormat::utcNow()];
905 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
907 Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
911 $doc = new DOMDocument();
912 @$doc->loadXML($curlResult->getBody());
914 $xpath = new DOMXPath($doc);
915 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
917 $entries = $xpath->query('/atom:feed/atom:entry');
921 foreach ($entries as $entry) {
922 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
923 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
924 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
925 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
927 if (empty($published) || empty($updated)) {
928 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
932 if ($last_updated < $published) {
933 $last_updated = $published;
936 if ($last_updated < $updated) {
937 $last_updated = $updated;
941 if (empty($last_updated)) {
945 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
946 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
949 * Updates the gcontact entry from a given public contact id
951 * @param integer $cid contact id
953 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
954 * @throws \ImagickException
956 public static function updateFromPublicContactID($cid)
958 self::updateFromPublicContact(['id' => $cid]);
962 * Updates the gcontact entry from a given public contact url
964 * @param string $url contact url
965 * @return integer gcontact id
966 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
967 * @throws \ImagickException
969 public static function updateFromPublicContactURL($url)
971 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
975 * Helper function for updateFromPublicContactID and updateFromPublicContactURL
977 * @param array $condition contact condition
978 * @return integer gcontact id
979 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
980 * @throws \ImagickException
982 private static function updateFromPublicContact($condition)
984 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
985 'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
986 'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
987 'baseurl', 'sensitive', 'unsearchable'];
989 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
990 if (!DBA::isResult($contact)) {
994 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender', 'generation',
995 'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
996 'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
997 'server_url', 'nsfw', 'hide', 'id'];
999 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
1000 $do_insert = !DBA::isResult($old_gcontact);
1007 // These fields are identical in both contact and gcontact
1008 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
1009 'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated'];
1011 foreach ($fields as $field) {
1012 $gcontact[$field] = $contact[$field];
1015 // These fields are having different names but the same content
1016 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
1017 $gcontact['nsfw'] = $contact['sensitive'];
1018 $gcontact['hide'] = $contact['unsearchable'];
1019 $gcontact['archived'] = $contact['archive'];
1020 $gcontact['archive_date'] = $contact['term-date'];
1021 $gcontact['birthday'] = $contact['bd'];
1022 $gcontact['photo'] = $contact['avatar'];
1023 $gcontact['last_contact'] = $contact['success_update'];
1024 $gcontact['last_failure'] = $contact['failure_update'];
1025 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
1027 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
1028 if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
1029 unset($gcontact[$field]);
1033 if (!$gcontact['archived']) {
1034 $gcontact['archive_date'] = DBA::NULL_DATETIME;
1037 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
1038 && ($old_gcontact['created'] <= $gcontact['created'])) {
1039 unset($gcontact['created']);
1042 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
1043 unset($gcontact['birthday']);
1046 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
1047 $gcontact['generation'] = 2; // We fetched the data directly from the other server
1051 DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
1052 return $old_gcontact['id'];
1053 } elseif (!$gcontact['archived']) {
1054 DBA::insert('gcontact', $gcontact);
1055 return DBA::lastInsertId();
1060 * Updates the gcontact entry from probe
1062 * @param string $url profile link
1063 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1065 * @return boolean 'true' when contact had been updated
1067 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1068 * @throws \ImagickException
1070 public static function updateFromProbe($url, $force = false)
1072 $data = Probe::uri($url, $force);
1074 if (in_array($data['network'], [Protocol::PHANTOM])) {
1075 $fields = ['last_failure' => DateTimeFormat::utcNow()];
1076 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1077 Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
1081 $data['server_url'] = $data['baseurl'];
1083 self::update($data);
1085 // Set the date of the latest post
1086 self::setLastUpdate($data, $force);
1092 * Update the gcontact entry for a given user id
1094 * @param int $uid User ID
1096 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1097 * @throws \ImagickException
1099 public static function updateForUser($uid)
1101 $profile = Profile::getByUID($uid);
1102 if (empty($profile)) {
1103 Logger::error('Cannot find profile', ['uid' => $uid]);
1107 $user = User::getOwnerDataById($uid);
1109 Logger::error('Cannot find user', ['uid' => $uid]);
1113 $userdata = array_merge($profile, $user);
1115 $location = Profile::formatLocation(
1116 ['locality' => $userdata['locality'], 'region' => $userdata['region'], 'country-name' => $userdata['country-name']]
1119 $gcontact = ['name' => $userdata['name'], 'location' => $location, 'about' => $userdata['about'],
1120 'gender' => $userdata['gender'], 'keywords' => $userdata['pub_keywords'],
1121 'birthday' => $userdata['dob'], 'photo' => $userdata['photo'],
1122 "notify" => $userdata['notify'], 'url' => $userdata['url'],
1123 "hide" => ($userdata['hidewall'] || !$userdata['net-publish']),
1124 'nick' => $userdata['nickname'], 'addr' => $userdata['addr'],
1125 "connect" => $userdata['addr'], "server_url" => DI::baseUrl(),
1126 "generation" => 1, 'network' => Protocol::DFRN];
1128 self::update($gcontact);
1132 * Get the basepath for a given contact link
1134 * @param string $url The gcontact link
1135 * @param boolean $dont_update Don't update the contact
1137 * @return string basepath
1138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1139 * @throws \ImagickException
1141 public static function getBasepath($url, $dont_update = false)
1143 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1144 if (!empty($gcontact['server_url'])) {
1145 return $gcontact['server_url'];
1146 } elseif ($dont_update) {
1150 self::updateFromProbe($url, true);
1153 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1154 if (empty($gcontact['server_url'])) {
1155 Logger::info('No baseurl for gcontact', ['url' => $url]);
1159 Logger::info('Found baseurl for gcontact', ['url' => $url, 'baseurl' => $gcontact['server_url']]);
1160 return $gcontact['server_url'];
1164 * Fetches users of given GNU Social server
1166 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1168 * @param string $server Server address
1170 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1171 * @throws \ImagickException
1173 public static function fetchGsUsers($server)
1175 Logger::info('Fetching users from GNU Social server', ['server' => $server]);
1177 $url = $server . '/main/statistics';
1179 $curlResult = Network::curl($url);
1180 if (!$curlResult->isSuccess()) {
1184 $statistics = json_decode($curlResult->getBody());
1186 if (!empty($statistics->config->instance_address)) {
1187 if (!empty($statistics->config->instance_with_ssl)) {
1188 $server = 'https://';
1190 $server = 'http://';
1193 $server .= $statistics->config->instance_address;
1195 $hostname = $statistics->config->instance_address;
1196 } elseif (!empty($statistics->instance_address)) {
1197 if (!empty($statistics->instance_with_ssl)) {
1198 $server = 'https://';
1200 $server = 'http://';
1203 $server .= $statistics->instance_address;
1205 $hostname = $statistics->instance_address;
1208 if (!empty($statistics->users)) {
1209 foreach ($statistics->users as $nick => $user) {
1210 $profile_url = $server . '/' . $user->nickname;
1212 $contact = ['url' => $profile_url,
1213 'name' => $user->fullname,
1214 'addr' => $user->nickname . '@' . $hostname,
1215 'nick' => $user->nickname,
1216 "network" => Protocol::OSTATUS,
1217 'photo' => DI::baseUrl() . '/images/person-300.jpg'];
1219 if (isset($user->bio)) {
1220 $contact['about'] = $user->bio;
1223 self::getId($contact);
1229 * 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(DI::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)) {