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\Search;
30 use Friendica\Core\System;
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\Strings;
40 * This class handles GlobalContact related functions
45 * Link the gcontact entry with user, contact and global contact
47 * @param integer $gcid Global contact ID
48 * @param integer $uid User ID
49 * @param integer $cid Contact ID
50 * @param integer $zcid Global Contact ID
54 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
60 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
61 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
65 * Sanitize the given gcontact data
69 * 1: Profiles on this server
70 * 2: Contacts of profiles on this server
71 * 3: Contacts of contacts of profiles on this server
74 * @param array $gcontact array with gcontact data
75 * @return array $gcontact
78 public static function sanitize($gcontact)
80 if (empty($gcontact['url'])) {
81 throw new Exception('URL is empty');
84 $gcontact['server_url'] = $gcontact['server_url'] ?? '';
86 $urlparts = parse_url($gcontact['url']);
87 if (empty($urlparts['scheme'])) {
88 throw new Exception('This (' . $gcontact['url'] . ") doesn't seem to be an url.");
91 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
92 throw new Exception('Contact from a non federated network ignored. (' . $gcontact['url'] . ')');
95 // Don't store the statusnet connector as network
96 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
97 if ($gcontact['network'] == Protocol::STATUSNET) {
98 $gcontact['network'] = '';
101 // Assure that there are no parameter fragments in the profile url
102 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
103 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
106 // The global contacts should contain the original picture, not the cached one
107 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(DI::baseUrl() . '/photo/'))) {
108 $gcontact['photo'] = '';
111 if (empty($gcontact['network'])) {
112 $gcontact['network'] = '';
114 $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
115 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
116 $contact = DBA::selectFirst('contact', ['network'], $condition);
117 if (DBA::isResult($contact)) {
118 $gcontact['network'] = $contact['network'];
121 if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
122 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
123 $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
124 $contact = DBA::selectFirst('contact', ['network'], $condition);
125 if (DBA::isResult($contact)) {
126 $gcontact['network'] = $contact['network'];
131 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
132 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
133 if (DBA::isResult($gcnt)) {
134 if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
135 $gcontact['network'] = $gcnt['network'];
137 if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
138 $gcontact['updated'] = $gcnt['updated'];
140 if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
141 $gcontact['server_url'] = $gcnt['server_url'];
143 if (!isset($gcontact['addr'])) {
144 $gcontact['addr'] = $gcnt['addr'];
148 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']))
149 && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
151 $data = Probe::uri($gcontact['url']);
153 if ($data['network'] == Protocol::PHANTOM) {
154 throw new Exception('Probing for URL ' . $gcontact['url'] . ' failed');
157 $gcontact['server_url'] = $data['baseurl'];
158 $gcontact['failed'] = false;
160 $gcontact = array_merge($gcontact, $data);
163 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
164 throw new Exception('No name and photo for URL '.$gcontact['url']);
167 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
168 throw new Exception('No federated network (' . $gcontact['network'] . ') detected for URL ' . $gcontact['url']);
171 if (empty($gcontact['server_url'])) {
172 // We check the server url to be sure that it is a real one
173 $server_url = self::getBasepath($gcontact['url']);
175 // We are now sure that it is a correct URL. So we use it in the future
176 if ($server_url != '') {
177 $gcontact['server_url'] = $server_url;
181 // The server URL doesn't seem to be valid, so we don't store it.
182 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
183 $gcontact['server_url'] = '';
190 * @param integer $uid id
191 * @param integer $cid id
195 public static function countCommonFriends($uid, $cid)
198 "SELECT count(*) as `total`
199 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
200 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
201 NOT `gcontact`.`failed`
202 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d) ",
209 if (DBA::isResult($r)) {
210 return $r[0]['total'];
216 * @param integer $uid id
217 * @param integer $zcid zcid
221 public static function countCommonFriendsZcid($uid, $zcid)
224 "SELECT count(*) as `total`
225 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
226 where `glink`.`zcid` = %d
227 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0) ",
232 if (DBA::isResult($r)) {
233 return $r[0]['total'];
240 * @param integer $uid user
241 * @param integer $cid cid
242 * @param integer $start optional, default 0
243 * @param integer $limit optional, default 9999
244 * @param boolean $shuffle optional, default false
248 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
251 $sql_extra = " order by rand() ";
253 $sql_extra = " order by `gcontact`.`name` asc ";
257 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
259 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
260 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
261 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
262 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
263 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
264 AND NOT `gcontact`.`failed`
265 $sql_extra LIMIT %d, %d",
274 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
279 * @param integer $uid user
280 * @param integer $zcid zcid
281 * @param integer $start optional, default 0
282 * @param integer $limit optional, default 9999
283 * @param boolean $shuffle optional, default false
287 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
290 $sql_extra = " order by rand() ";
292 $sql_extra = " order by `gcontact`.`name` asc ";
297 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
298 where `glink`.`zcid` = %d
299 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0)
300 $sql_extra limit %d, %d",
307 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
312 * @param integer $uid user
313 * @param integer $cid cid
317 public static function countAllFriends($uid, $cid)
320 "SELECT count(*) as `total`
321 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
322 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
323 NOT `gcontact`.`failed`",
328 if (DBA::isResult($r)) {
329 return $r[0]['total'];
336 * @param integer $uid user
337 * @param integer $cid cid
338 * @param integer $start optional, default 0
339 * @param integer $limit optional, default 80
343 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
346 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
348 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
349 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
350 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
351 NOT `gcontact`.`failed`
352 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
360 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
366 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
368 public static function updateSuggestions()
372 /// @TODO Check if it is really neccessary to poll the own server
373 PortableContact::loadWorker(0, 0, 0, DI::baseUrl() . '/poco');
375 $done[] = DI::baseUrl() . '/poco';
377 if (strlen(DI::config()->get('system', 'directory'))) {
378 $x = DI::httpRequest()->fetch(Search::getGlobalDirectory() . '/pubsites');
380 $j = json_decode($x);
381 if (!empty($j->entries)) {
382 foreach ($j->entries as $entry) {
383 GServer::check($entry->url);
385 $url = $entry->url . '/poco';
386 if (!in_array($url, $done)) {
387 PortableContact::loadWorker(0, 0, 0, $url);
395 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
396 $contacts = DBA::p("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN (?, ?)", Protocol::DFRN, Protocol::DIASPORA);
397 while ($contact = DBA::fetch($contacts)) {
398 $base = substr($contact['poco'], 0, strrpos($contact['poco'], '/'));
399 if (!in_array($base, $done)) {
400 PortableContact::loadWorker(0, 0, 0, $base);
403 DBA::close($contacts);
407 * Removes unwanted parts from a contact url
409 * @param string $url Contact url
411 * @return string Contact url with the wanted parts
414 public static function cleanContactUrl($url)
416 $parts = parse_url($url);
418 if (empty($parts['scheme']) || empty($parts['host'])) {
422 $new_url = $parts['scheme'] . '://' . $parts['host'];
424 if (!empty($parts['port'])) {
425 $new_url .= ':' . $parts['port'];
428 if (!empty($parts['path'])) {
429 $new_url .= $parts['path'];
432 if ($new_url != $url) {
433 Logger::info('Cleaned contact url', ['url' => $url, 'new_url' => $new_url, 'callstack' => System::callstack()]);
440 * Fetch the gcontact id, add an entry if not existed
442 * @param array $contact contact array
444 * @return bool|int Returns false if not found, integer if contact was found
445 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
446 * @throws \ImagickException
448 public static function getId($contact)
450 if (empty($contact['network'])) {
451 Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
455 if (in_array($contact['network'], [Protocol::PHANTOM])) {
456 Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
460 if ($contact['network'] == Protocol::STATUSNET) {
461 $contact['network'] = Protocol::OSTATUS;
464 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
465 if (in_array($contact['network'], Protocol::FEDERATED)) {
466 $contact['url'] = self::cleanContactUrl($contact['url']);
469 $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
470 $gcontact = DBA::selectFirst('gcontact', ['id'], $condition, ['order' => ['id']]);
471 if (DBA::isResult($gcontact)) {
472 return $gcontact['id'];
475 $contact['location'] = $contact['location'] ?? '';
476 $contact['about'] = $contact['about'] ?? '';
477 $contact['generation'] = $contact['generation'] ?? 0;
478 $contact['hide'] = $contact['hide'] ?? true;
480 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'] ?? '', 'addr' => $contact['addr'] ?? '', 'network' => $contact['network'],
481 'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
482 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
483 'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation'], 'failed' => false];
485 DBA::insert('gcontact', $fields);
487 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
488 $gcontact = DBA::selectFirst('gcontact', ['id'], $condition, ['order' => ['id']]);
489 if (!DBA::isResult($gcontact)) {
490 Logger::info('GContact creation failed', $fields);
494 return $gcontact['id'];
498 * Updates the gcontact table from a given array
500 * @param array $contact contact array
502 * @return bool|int Returns false if not found, integer if contact was found
503 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
504 * @throws \ImagickException
506 public static function update($contact)
508 // Check for invalid "contact-type" value
509 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
510 $contact['contact-type'] = 0;
513 /// @todo update contact table as well
515 $gcontact_id = self::getId($contact);
521 $public_contact = DBA::selectFirst('gcontact', [
522 'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'keywords', 'gsid', 'failed',
523 'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
524 ], ['id' => $gcontact_id]);
526 if (!DBA::isResult($public_contact)) {
530 // Get all field names
532 foreach ($public_contact as $field => $data) {
533 $fields[$field] = $data;
536 unset($fields['url']);
537 unset($fields['updated']);
538 unset($fields['hide']);
540 // Bugfix: We had an error in the storing of keywords which lead to the "0"
541 // This value is still transmitted via poco.
542 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
543 unset($contact['keywords']);
546 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
547 $public_contact['keywords'] = '';
550 // assign all unassigned fields from the database entry
551 foreach ($fields as $field => $data) {
552 if (empty($contact[$field])) {
553 $contact[$field] = $public_contact[$field];
557 if (!isset($contact['hide'])) {
558 $contact['hide'] = $public_contact['hide'];
561 $fields['hide'] = $public_contact['hide'];
563 if ($contact['network'] == Protocol::STATUSNET) {
564 $contact['network'] = Protocol::OSTATUS;
567 if (!isset($contact['updated'])) {
568 $contact['updated'] = DateTimeFormat::utcNow();
571 if ($contact['network'] == Protocol::TWITTER) {
572 $contact['server_url'] = 'http://twitter.com';
575 if (empty($contact['server_url'])) {
576 $data = Probe::uri($contact['url']);
577 if ($data['network'] != Protocol::PHANTOM) {
578 $contact['server_url'] = $data['baseurl'];
581 $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
584 if (!empty($contact['server_url']) && empty($contact['gsid'])) {
585 $contact['gsid'] = GServer::getID($contact['server_url']);
588 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
589 $hostname = str_replace('http://', '', $contact['server_url']);
590 $contact['addr'] = $contact['nick'] . '@' . $hostname;
593 // Check if any field changed
595 unset($fields['generation']);
597 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
598 foreach ($fields as $field => $data) {
599 if ($contact[$field] != $public_contact[$field]) {
600 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
605 if ($contact['generation'] < $public_contact['generation']) {
606 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
612 Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
613 $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
614 Strings::normaliseLink($contact['url']), $contact['generation']];
615 $contact['updated'] = DateTimeFormat::utc($contact['updated']);
618 'photo' => $contact['photo'], 'name' => $contact['name'],
619 'nick' => $contact['nick'], 'addr' => $contact['addr'],
620 'network' => $contact['network'], 'birthday' => $contact['birthday'],
621 'keywords' => $contact['keywords'],
622 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
623 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
624 'notify' => $contact['notify'], 'url' => $contact['url'],
625 'location' => $contact['location'], 'about' => $contact['about'],
626 'generation' => $contact['generation'], 'updated' => $contact['updated'],
627 'server_url' => $contact['server_url'], 'connect' => $contact['connect'],
628 'failed' => $contact['failed'], 'gsid' => $contact['gsid']
631 DBA::update('gcontact', $updated, $condition, $fields);
638 * Set the last date that the contact had posted something
640 * @param string $data Probing result
641 * @param bool $force force updating
643 public static function setLastUpdate(array $data, bool $force = false)
645 // Fetch the global contact
646 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
647 ['nurl' => Strings::normaliseLink($data['url'])]);
648 if (!DBA::isResult($gcontact)) {
652 if (!$force && !GServer::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
653 Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
657 if (self::updateFromNoScrape($data)) {
661 if (!empty($data['outbox'])) {
662 self::updateFromOutbox($data['outbox'], $data);
663 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
664 self::updateFromOutbox($data['poll'], $data);
665 } elseif (!empty($data['poll'])) {
666 self::updateFromFeed($data);
671 * Update a global contact via the "noscrape" endpoint
673 * @param string $data Probing result
675 * @return bool 'true' if update was successful or the server was unreachable
677 private static function updateFromNoScrape(array $data)
679 // Check the 'noscrape' endpoint when it is a Friendica server
680 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
681 Strings::normaliseLink($data['baseurl'])]);
682 if (!DBA::isResult($gserver)) {
686 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
688 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
689 $noscrape = json_decode($curlResult->getBody(), true);
690 if (!empty($noscrape) && !empty($noscrape['updated'])) {
691 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
692 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
693 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
696 } elseif ($curlResult->isTimeout()) {
697 // On a timeout return the existing value, but mark the contact as failure
698 $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
699 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
706 * Update a global contact via an ActivityPub Outbox
708 * @param string $feed
709 * @param array $data Probing result
710 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
712 private static function updateFromOutbox(string $feed, array $data)
714 $outbox = ActivityPub::fetchContent($feed);
715 if (empty($outbox)) {
719 if (!empty($outbox['orderedItems'])) {
720 $items = $outbox['orderedItems'];
721 } elseif (!empty($outbox['first']['orderedItems'])) {
722 $items = $outbox['first']['orderedItems'];
723 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
724 self::updateFromOutbox($outbox['first']['href'], $data);
726 } elseif (!empty($outbox['first'])) {
727 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
728 self::updateFromOutbox($outbox['first'], $data);
730 Logger::warning('Unexpected data', ['outbox' => $outbox]);
738 foreach ($items as $activity) {
739 if (!empty($activity['published'])) {
740 $published = DateTimeFormat::utc($activity['published']);
741 } elseif (!empty($activity['object']['published'])) {
742 $published = DateTimeFormat::utc($activity['object']['published']);
747 if ($last_updated < $published) {
748 $last_updated = $published;
752 if (empty($last_updated)) {
756 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
757 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
761 * Update a global contact via an XML feed
763 * @param string $data Probing result
765 private static function updateFromFeed(array $data)
767 // Search for the newest entry in the feed
768 $curlResult = DI::httpRequest()->get($data['poll']);
769 if (!$curlResult->isSuccess()) {
770 $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
771 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
773 Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
777 $doc = new DOMDocument();
778 @$doc->loadXML($curlResult->getBody());
780 $xpath = new DOMXPath($doc);
781 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
783 $entries = $xpath->query('/atom:feed/atom:entry');
787 foreach ($entries as $entry) {
788 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
789 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
790 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
791 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
793 if (empty($published) || empty($updated)) {
794 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
798 if ($last_updated < $published) {
799 $last_updated = $published;
802 if ($last_updated < $updated) {
803 $last_updated = $updated;
807 if (empty($last_updated)) {
811 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
812 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
815 * Updates the gcontact entry from a given public contact id
817 * @param integer $cid contact id
819 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
820 * @throws \ImagickException
822 public static function updateFromPublicContactID($cid)
824 self::updateFromPublicContact(['id' => $cid]);
828 * Updates the gcontact entry from a given public contact url
830 * @param string $url contact url
831 * @return integer gcontact id
832 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
833 * @throws \ImagickException
835 public static function updateFromPublicContactURL($url)
837 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
841 * Helper function for updateFromPublicContactID and updateFromPublicContactURL
843 * @param array $condition contact condition
844 * @return integer gcontact id
845 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
846 * @throws \ImagickException
848 private static function updateFromPublicContact($condition)
850 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords',
851 'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
852 'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
853 'baseurl', 'gsid', 'sensitive', 'unsearchable', 'failed'];
855 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
856 if (!DBA::isResult($contact)) {
860 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'generation',
861 'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
862 'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
863 'server_url', 'gsid', 'nsfw', 'hide', 'id', 'failed'];
865 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
866 $do_insert = !DBA::isResult($old_gcontact);
873 // These fields are identical in both contact and gcontact
874 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gsid',
875 'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated', 'failed'];
877 foreach ($fields as $field) {
878 $gcontact[$field] = $contact[$field];
881 // These fields are having different names but the same content
882 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
883 $gcontact['nsfw'] = $contact['sensitive'];
884 $gcontact['hide'] = $contact['unsearchable'];
885 $gcontact['archived'] = $contact['archive'];
886 $gcontact['archive_date'] = $contact['term-date'];
887 $gcontact['birthday'] = $contact['bd'];
888 $gcontact['photo'] = $contact['avatar'];
889 $gcontact['last_contact'] = $contact['success_update'];
890 $gcontact['last_failure'] = $contact['failure_update'];
891 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
893 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
894 if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
895 unset($gcontact[$field]);
899 if (!$gcontact['archived']) {
900 $gcontact['archive_date'] = DBA::NULL_DATETIME;
903 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
904 && ($old_gcontact['created'] <= $gcontact['created'])) {
905 unset($gcontact['created']);
908 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
909 unset($gcontact['birthday']);
912 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
913 $gcontact['generation'] = 2; // We fetched the data directly from the other server
917 DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
918 return $old_gcontact['id'];
919 } elseif (!$gcontact['archived']) {
920 DBA::insert('gcontact', $gcontact);
921 return DBA::lastInsertId();
926 * Updates the gcontact entry from probe
928 * @param string $url profile link
929 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
931 * @return boolean 'true' when contact had been updated
933 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
934 * @throws \ImagickException
936 public static function updateFromProbe($url, $force = false)
938 $data = Probe::uri($url, $force);
940 if (in_array($data['network'], [Protocol::PHANTOM])) {
941 $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
942 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
943 Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
947 $data['server_url'] = $data['baseurl'];
948 $data['failed'] = false;
952 // Set the date of the latest post
953 self::setLastUpdate($data, $force);
959 * Update the gcontact entry for a given user id
961 * @param int $uid User ID
963 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
964 * @throws \ImagickException
966 public static function updateForUser($uid)
968 $profile = Profile::getByUID($uid);
969 if (empty($profile)) {
970 Logger::error('Cannot find profile', ['uid' => $uid]);
974 $user = User::getOwnerDataById($uid);
976 Logger::error('Cannot find user', ['uid' => $uid]);
980 $userdata = array_merge($profile, $user);
982 $location = Profile::formatLocation(
983 ['locality' => $userdata['locality'], 'region' => $userdata['region'], 'country-name' => $userdata['country-name']]
986 $gcontact = ['name' => $userdata['name'], 'location' => $location, 'about' => $userdata['about'],
987 'keywords' => $userdata['pub_keywords'],
988 'birthday' => $userdata['dob'], 'photo' => $userdata['photo'],
989 "notify" => $userdata['notify'], 'url' => $userdata['url'],
990 "hide" => !$userdata['net-publish'],
991 'nick' => $userdata['nickname'], 'addr' => $userdata['addr'],
992 "connect" => $userdata['addr'], "server_url" => DI::baseUrl(),
993 "generation" => 1, 'network' => Protocol::DFRN];
995 self::update($gcontact);
999 * Get the basepath for a given contact link
1001 * @param string $url The gcontact link
1002 * @param boolean $dont_update Don't update the contact
1004 * @return string basepath
1005 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1006 * @throws \ImagickException
1008 public static function getBasepath($url, $dont_update = false)
1010 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1011 if (!empty($gcontact['server_url'])) {
1012 return $gcontact['server_url'];
1013 } elseif ($dont_update) {
1017 self::updateFromProbe($url, true);
1020 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1021 if (empty($gcontact['server_url'])) {
1022 Logger::info('No baseurl for gcontact', ['url' => $url]);
1026 Logger::info('Found baseurl for gcontact', ['url' => $url, 'baseurl' => $gcontact['server_url']]);
1027 return $gcontact['server_url'];
1031 * Fetches users of given GNU Social server
1033 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1035 * @param string $server Server address
1037 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1038 * @throws \ImagickException
1040 public static function fetchGsUsers($server)
1042 Logger::info('Fetching users from GNU Social server', ['server' => $server]);
1044 $url = $server . '/main/statistics';
1046 $curlResult = DI::httpRequest()->get($url);
1047 if (!$curlResult->isSuccess()) {
1051 $statistics = json_decode($curlResult->getBody());
1053 if (!empty($statistics->config->instance_address)) {
1054 if (!empty($statistics->config->instance_with_ssl)) {
1055 $server = 'https://';
1057 $server = 'http://';
1060 $server .= $statistics->config->instance_address;
1062 $hostname = $statistics->config->instance_address;
1063 } elseif (!empty($statistics->instance_address)) {
1064 if (!empty($statistics->instance_with_ssl)) {
1065 $server = 'https://';
1067 $server = 'http://';
1070 $server .= $statistics->instance_address;
1072 $hostname = $statistics->instance_address;
1075 if (!empty($statistics->users)) {
1076 foreach ($statistics->users as $nick => $user) {
1077 $profile_url = $server . '/' . $user->nickname;
1079 $contact = ['url' => $profile_url,
1080 'name' => $user->fullname,
1081 'addr' => $user->nickname . '@' . $hostname,
1082 'nick' => $user->nickname,
1083 "network" => Protocol::OSTATUS,
1084 'photo' => DI::baseUrl() . '/images/person-300.jpg'];
1086 if (isset($user->bio)) {
1087 $contact['about'] = $user->bio;
1090 self::getId($contact);
1096 * Asking GNU Social server on a regular base for their user data
1099 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1100 * @throws \ImagickException
1102 public static function discoverGsUsers()
1104 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1106 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1108 $r = DBA::select('gserver', ['nurl', 'url'], [
1111 AND `last_poco_query` < ?',
1116 'order' => ['RAND()']
1119 if (!DBA::isResult($r)) {
1123 foreach ($r as $server) {
1124 self::fetchGsUsers($server['url']);
1125 DBA::update('gserver', ['last_poco_query' => DateTimeFormat::utcNow()], ['nurl' => $server['nurl']]);
1130 * Returns a random, global contact of the current node
1132 * @return string The profile URL
1135 public static function getRandomUrl()
1137 $r = DBA::selectFirst('gcontact', ['url'], [
1142 DateTimeFormat::utc('now - 1 month'),
1143 ], ['order' => ['RAND()']]);
1145 if (DBA::isResult($r)) {