3 * @copyright Copyright (C) 2010-2023, the Friendica project
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\Protocol;
28 use Friendica\Content\PageInfo;
29 use Friendica\Content\Text\BBCode;
30 use Friendica\Content\Text\HTML;
31 use Friendica\Core\Cache\Enum\Duration;
32 use Friendica\Core\Logger;
33 use Friendica\Core\Protocol;
34 use Friendica\Core\Worker;
35 use Friendica\Database\DBA;
37 use Friendica\Model\Contact;
38 use Friendica\Model\Conversation;
39 use Friendica\Model\Item;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Network\HTTPException;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Network;
46 use Friendica\Util\ParseUrl;
47 use Friendica\Util\Proxy;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
50 use GuzzleHttp\Exception\TransferException;
53 * This class contain functions to import feeds (RSS/RDF/Atom)
58 * Read a RSS/RDF/Atom feed and create an item entry for it
60 * @param string $xml The feed data
61 * @param array $importer The user record of the importer
62 * @param array $contact The contact record of the feed
64 * @return array Returns the header and the first item in dry run mode
65 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
67 public static function import(string $xml, array $importer = [], array $contact = []): array
69 $dryRun = empty($importer) && empty($contact);
72 Logger::info("Test Atom/RSS feed");
74 Logger::info('Import Atom/RSS feed "' . $contact['name'] . '" (Contact ' . $contact['id'] . ') for user ' . $importer['uid']);
80 Logger::info('XML is empty.');
84 if (!empty($contact['poll'])) {
85 $basepath = $contact['poll'];
86 } elseif (!empty($contact['url'])) {
87 $basepath = $contact['url'];
92 $doc = new DOMDocument();
94 $xpath = new DOMXPath($doc);
95 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
96 $xpath->registerNamespace('dc', 'http://purl.org/dc/elements/1.1/');
97 $xpath->registerNamespace('content', 'http://purl.org/rss/1.0/modules/content/');
98 $xpath->registerNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
99 $xpath->registerNamespace('rss', 'http://purl.org/rss/1.0/');
100 $xpath->registerNamespace('media', 'http://search.yahoo.com/mrss/');
101 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
105 $protocol = Conversation::PARCEL_UNKNOWN;
108 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
109 $protocol = Conversation::PARCEL_RDF;
110 $author['author-link'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
111 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
113 if (empty($author['author-name'])) {
114 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
116 $entries = $xpath->query('/rdf:RDF/rss:item');
120 if ($xpath->query('/atom:feed')->length > 0) {
121 $protocol = Conversation::PARCEL_ATOM;
122 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
123 if (is_object($alternate)) {
124 foreach ($alternate as $attribute) {
125 if ($attribute->name == 'href') {
126 $author['author-link'] = $attribute->textContent;
131 if (empty($author['author-link'])) {
132 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
133 if (is_object($self)) {
134 foreach ($self as $attribute) {
135 if ($attribute->name == 'href') {
136 $author['author-link'] = $attribute->textContent;
142 if (empty($author['author-link'])) {
143 $author['author-link'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
145 $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
147 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
149 if (empty($author['author-name'])) {
150 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
153 if (empty($author['author-name'])) {
154 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
157 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
159 $author['author-name'] = $value;
163 $author['author-id'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
165 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
166 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
168 $author['author-link'] = $value;
171 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
173 $author['author-nick'] = $value;
176 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
178 $author['author-location'] = $value;
181 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
183 $author['author-about'] = $value;
186 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
187 if (is_object($avatar)) {
188 foreach ($avatar as $attribute) {
189 if ($attribute->name == 'href') {
190 $author['author-avatar'] = $attribute->textContent;
196 $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
198 $author['app'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
200 $entries = $xpath->query('/atom:feed/atom:entry');
204 if ($xpath->query('/rss/channel')->length > 0) {
205 $protocol = Conversation::PARCEL_RSS;
206 $author['author-link'] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
208 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
210 if (empty($author['author-name'])) {
211 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
214 if (empty($author['author-name'])) {
215 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
218 $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
220 if (empty($author['author-avatar'])) {
221 $avatar = XML::getFirstAttributes($xpath, '/rss/channel/itunes:image');
222 if (is_object($avatar)) {
223 foreach ($avatar as $attribute) {
224 if ($attribute->name == 'href') {
225 $author['author-avatar'] = $attribute->textContent;
231 $author['author-about'] = HTML::toBBCode(XML::getFirstNodeValue($xpath, '/rss/channel/description/text()'), $basepath);
233 if (empty($author['author-about'])) {
234 $author['author-about'] = XML::getFirstNodeValue($xpath, '/rss/channel/itunes:summary/text()');
237 $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
239 $author['app'] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
241 $entries = $xpath->query('/rss/channel/item');
245 $author['author-link'] = $contact['url'];
247 if (empty($author['author-name'])) {
248 $author['author-name'] = $contact['name'];
251 $author['author-avatar'] = $contact['thumb'];
253 $author['owner-link'] = $contact['url'];
254 $author['owner-name'] = $contact['name'];
255 $author['owner-avatar'] = $contact['thumb'];
259 'uid' => $importer['uid'] ?? 0,
260 'network' => Protocol::FEED,
263 'gravity' => Item::GRAVITY_PARENT,
264 'private' => Item::PUBLIC,
265 'verb' => Activity::POST,
266 'object-type' => Activity\ObjectType::NOTE,
267 'post-type' => Item::PT_ARTICLE,
268 'contact-id' => $contact['id'] ?? 0,
271 $datarray['protocol'] = $protocol;
272 $datarray['direction'] = Conversation::PULL;
274 if (!is_object($entries)) {
275 Logger::info("There are no entries in this feed.");
280 $creation_dates = [];
282 // Limit the number of items that are about to be fetched
283 $total_items = ($entries->length - 1);
284 $max_items = DI::config()->get('system', 'max_feed_items');
285 if (($max_items > 0) && ($total_items > $max_items)) {
286 $total_items = $max_items;
291 // Importing older entries first
292 for ($i = $total_items; $i >= 0; --$i) {
293 $entry = $entries->item($i);
295 $item = array_merge($header, $author);
297 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
298 if (!is_object($alternate)) {
299 $alternate = XML::getFirstAttributes($xpath, 'atom:link', $entry);
301 if (is_object($alternate)) {
302 foreach ($alternate as $attribute) {
303 if ($attribute->name == 'href') {
304 $item['plink'] = $attribute->textContent;
309 if (empty($item['plink'])) {
310 $item['plink'] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
313 if (empty($item['plink'])) {
314 $item['plink'] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
317 // Add the base path if missing
318 $item['plink'] = Network::addBasePath($item['plink'], $basepath);
320 $item['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
322 $guid = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
324 $item['uri'] = $guid;
326 // Don't use the GUID value directly but instead use it as a basis for the GUID
327 $item['guid'] = Item::guidFromUri($guid, parse_url($guid, PHP_URL_HOST) ?? parse_url($item['plink'], PHP_URL_HOST));
330 if (empty($item['uri'])) {
331 $item['uri'] = $item['plink'];
334 $orig_plink = $item['plink'];
337 $item['plink'] = DI::httpClient()->finalUrl($item['plink']);
338 } catch (TransferException $exception) {
339 Logger::notice('Item URL couldn\'t get expanded', ['url' => $item['plink'], 'exception' => $exception]);
342 $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
344 if (empty($item['title'])) {
345 $item['title'] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
348 if (empty($item['title'])) {
349 $item['title'] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
352 if (empty($item['title'])) {
353 $item['title'] = XML::getFirstNodeValue($xpath, 'itunes:title/text()', $entry);
356 $item['title'] = html_entity_decode($item['title'], ENT_QUOTES, 'UTF-8');
358 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
360 if (empty($published)) {
361 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
364 if (empty($published)) {
365 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
368 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
370 if (empty($updated) && !empty($published)) {
371 $updated = $published;
374 if (empty($published) && !empty($updated)) {
375 $published = $updated;
378 if ($published != '') {
379 $item['created'] = trim($published);
382 if ($updated != '') {
383 $item['edited'] = trim($updated);
387 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
388 $importer['uid'], $item['uri'], Protocol::FEED, Protocol::DFRN];
389 $previous = Post::selectFirst(['id', 'created'], $condition);
390 if (DBA::isResult($previous)) {
391 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
392 $creation_dates[] = $previous['created'];
393 Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']);
396 $creation_dates[] = DateTimeFormat::utc($item['created']);
399 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
401 if (empty($creator)) {
402 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
405 if (empty($creator)) {
406 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
409 if ($creator != '') {
410 $item['author-name'] = $creator;
413 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
415 if ($creator != '') {
416 $item['author-name'] = $creator;
420 // <category>Ausland</category>
421 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
425 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
426 foreach ($enclosures as $enclosure) {
431 foreach ($enclosure->attributes as $attribute) {
432 if (in_array($attribute->name, ['url', 'href'])) {
433 $href = $attribute->textContent;
434 } elseif ($attribute->name == 'length') {
435 $length = (int)$attribute->textContent;
436 } elseif ($attribute->name == 'type') {
437 $type = $attribute->textContent;
442 $attachment = ['uri-id' => -1, 'type' => Post\Media::UNKNOWN, 'url' => $href, 'mimetype' => $type, 'size' => $length];
444 $attachment = Post\Media::fetchAdditionalData($attachment);
446 // By now we separate the visible media types (audio, video, image) from the rest
447 // In the future we should try to avoid the DOCUMENT type and only use the real one - but not in the RC phase.
448 if (!in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO])) {
449 $attachment['type'] = Post\Media::DOCUMENT;
451 $attachments[] = $attachment;
456 $categories = $xpath->query('category', $entry);
457 foreach ($categories as $category) {
458 $taglist[] = $category->nodeValue;
461 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
464 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
467 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
469 if (empty($summary)) {
470 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
478 if ($body == $summary) {
482 // remove the content of the title if it is identically to the body
483 // This helps with auto generated titles e.g. from tumblr
484 if (self::titleIsBody($item['title'], $body)) {
487 $item['body'] = HTML::toBBCode($body, $basepath);
489 // Remove tracking pixels
490 $item['body'] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item['body']);
492 if (($item['body'] == '') && ($item['title'] != '')) {
493 $item['body'] = $item['title'];
498 $item['attachments'] = $attachments;
501 } elseif (!Item::isValid($item)) {
502 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
504 } elseif (Item::isTooOld($item)) {
505 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
510 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] < 3)) {
511 // Handle enclosures and treat them as preview picture
512 foreach ($attachments as $attachment) {
513 if ($attachment['mimetype'] == 'image/jpeg') {
514 $preview = $attachment['url'];
518 // Remove a possible link to the item itself
519 $item['body'] = str_replace($item['plink'], '', $item['body']);
520 $item['body'] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item['body']));
522 // Replace the content when the title is longer than the body
523 $replace = (strlen($item['title']) > strlen($item['body']));
525 // Replace it, when there is an image in the body
526 if (strstr($item['body'], '[/img]')) {
530 // Replace it, when there is a link in the body
531 if (strstr($item['body'], '[/url]')) {
535 $saved_body = $item['body'];
536 $saved_title = $item['title'];
539 $item['body'] = trim($item['title']);
542 $data = ParseUrl::getSiteinfoCached($item['plink']);
543 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
544 // When the fetched page info text is longer than the body, we do try to enhance the body
545 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
546 // The body is not part of the fetched page info title or page info text. So we add the text to the body
547 $item['body'] .= "\n\n" . $data['text'];
549 // Else we replace the body with the page info text
550 $item['body'] = $data['text'];
554 $data = PageInfo::queryUrl($item['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_denylist'] ?? '');
557 // Take the data that was provided by the feed if the query is empty
558 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
559 $data['title'] = $saved_title;
560 $item['body'] = $saved_body;
563 $data_text = strip_tags(trim($data['text'] ?? ''));
564 $item_body = strip_tags(trim($item['body'] ?? ''));
566 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
570 // We always strip the title since it will be added in the page information
572 $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false);
573 $taglist = $contact['fetch_further_information'] == 2 ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : [];
574 $item['object-type'] = Activity\ObjectType::BOOKMARK;
577 foreach (['audio', 'video'] as $elementname) {
578 if (!empty($data[$elementname])) {
579 foreach ($data[$elementname] as $element) {
580 if (!empty($element['src'])) {
581 $src = $element['src'];
582 } elseif (!empty($element['content'])) {
583 $src = $element['content'];
589 'type' => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
591 'preview' => $element['image'] ?? null,
592 'mimetype' => $element['contenttype'] ?? null,
593 'name' => $element['name'] ?? null,
594 'description' => $element['description'] ?? null,
601 if (!empty($summary)) {
602 $item['body'] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item['body'];
605 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] == 3)) {
606 if (empty($taglist)) {
607 $taglist = PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '');
609 $item['body'] .= "\n" . self::tagToString($taglist);
614 // Add the link to the original feed entry if not present in feed
615 if (($item['plink'] != '') && !strstr($item['body'], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
616 $item['body'] .= '[hr][url]' . $item['plink'] . '[/url]';
620 if (empty($item['title'])) {
621 $item['post-type'] = Item::PT_NOTE;
624 Logger::info('Stored feed', ['item' => $item]);
626 $notify = Item::isRemoteSelf($contact, $item);
627 $item['wall'] = (bool)$notify;
629 // Distributed items should have a well-formatted URI.
630 // Additionally, we have to avoid conflicts with identical URI between imported feeds and these items.
632 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
633 $item['uri'] = Item::newURI($item['guid']);
634 unset($item['thr-parent']);
635 unset($item['parent-uri']);
637 // Set the delivery priority for "remote self" to "medium"
638 $notify = Worker::PRIORITY_MEDIUM;
641 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
642 if (!Post::exists($condition) && !Post\Delayed::exists($item['uri'], $item['uid'])) {
644 Post\Delayed::publish($item, $notify, $taglist, $attachments);
646 $postings[] = ['item' => $item, 'notify' => $notify,
647 'taglist' => $taglist, 'attachments' => $attachments];
650 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]);
654 if (!empty($postings)) {
655 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
656 $total = count($postings);
658 // Posts shouldn't be delayed more than a day
659 $interval = min(1440, self::getPollInterval($contact));
660 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
661 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
668 foreach ($postings as $posting) {
670 $publish_time = time() + $post_delay;
671 $post_delay += $delay;
673 $publish_time = time();
676 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
677 $next_publish = max($last_publish + (60 * $min_posting), time());
678 if ($publish_time < $next_publish) {
679 $publish_time = $next_publish;
681 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
683 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
684 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
689 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
690 self::adjustPollFrequency($contact, $creation_dates);
693 return ['header' => $author, 'items' => $items];
697 * Automatically adjust the poll frequency according to the post frequency
699 * @param array $contact Contact array
700 * @param array $creation_dates
703 private static function adjustPollFrequency(array $contact, array $creation_dates)
705 if ($contact['network'] != Protocol::FEED) {
706 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
710 if (!empty($creation_dates)) {
711 // Count the post frequency and the earliest and latest post date
715 $oldest_date = $newest_date = '';
717 foreach ($creation_dates as $date) {
718 $timestamp = strtotime($date);
719 $day = intdiv($timestamp, 86400);
720 $hour = $timestamp % 86400;
722 // Only have a look at values from the last seven days
723 if (((time() / 86400) - $day) < 7) {
724 if (empty($frequency[$day])) {
725 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
727 ++$frequency[$day]['count'];
728 if ($frequency[$day]['low'] > $hour) {
729 $frequency[$day]['low'] = $hour;
731 if ($frequency[$day]['high'] < $hour) {
732 $frequency[$day]['high'] = $hour;
736 if ($oldest > $day) {
738 $oldest_date = $date;
741 if ($newest < $day) {
743 $newest_date = $date;
747 if (count($creation_dates) == 1) {
748 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
749 $priority = 8; // Poll once a day
752 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
753 Logger::info('Feed had not posted for two years, switching to monthly polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
754 $priority = 10; // Poll every month
757 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
758 Logger::info('Feed had not posted for a year, switching to weekly polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
759 $priority = 9; // Poll every week
762 if (empty($priority) && empty($frequency)) {
763 Logger::info('Feed had not posted for at least a week, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
764 $priority = 8; // Poll once a day
767 if (empty($priority)) {
768 // Calculate the highest "posts per day" value
770 foreach ($frequency as $entry) {
771 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
775 // We take the earliest and latest post day and interpolate the number of post per day
776 // that would had been created with this post frequency
778 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
779 $duration = max($entry['high'] - $entry['low'], 14400);
780 $ppd = (86400 / $duration) * $entry['count'];
786 $priority = 1; // Poll every quarter hour
787 } elseif ($max > 24) {
788 $priority = 2; // Poll half an hour
789 } elseif ($max > 12) {
790 $priority = 3; // Poll hourly
791 } elseif ($max > 8) {
792 $priority = 4; // Poll every two hours
793 } elseif ($max > 4) {
794 $priority = 5; // Poll every three hours
795 } elseif ($max > 2) {
796 $priority = 6; // Poll every six hours
798 $priority = 7; // Poll twice a day
800 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
803 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
804 $priority = 8; // Poll once a day
807 if ($contact['rating'] != $priority) {
808 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
809 Contact::update(['rating' => $priority], ['id' => $contact['id']]);
814 * Get the poll interval for the given contact array
816 * @param array $contact
817 * @return int Poll interval in minutes
819 public static function getPollInterval(array $contact): int
821 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
822 $ratings = [0, 3, 7, 8, 9, 10];
823 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
824 $rating = $contact['rating'];
825 } elseif (array_key_exists($contact['priority'], $ratings)) {
826 $rating = $ratings[$contact['priority']];
831 // Check once a week per default for all other networks
835 // Friendica and OStatus are checked once a day
836 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
840 // Check archived contacts or contacts with unsupported protocols once a month
841 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
849 * Based on $contact['priority'], should we poll this site now? Or later?
852 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
854 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
856 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
857 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
859 return $poll_intervals[$rating];
863 * Convert a tag array to a tag string
866 * @return string tag string
868 private static function tagToString(array $tags): string
872 foreach ($tags as $tag) {
877 $tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
883 private static function titleIsBody(string $title, string $body): bool
885 $title = strip_tags($title);
886 $title = trim($title);
887 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
888 $title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
890 $body = strip_tags($body);
892 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
893 $body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
895 if (strlen($title) < strlen($body)) {
896 $body = substr($body, 0, strlen($title));
899 if (($title != $body) && (substr($title, -3) == '...')) {
900 $pos = strrpos($title, '...');
902 $title = substr($title, 0, $pos);
903 $body = substr($body, 0, $pos);
906 return ($title == $body);
910 * Creates the Atom feed for a given nickname
913 * - activity (default): all the public posts
914 * - posts: all the public top-level posts
915 * - comments: all the public replies
917 * Updates the provided last_update parameter if the result comes from the
918 * cache or it is empty
920 * @param array $owner owner-view record of the feed owner
921 * @param string $last_update Date of the last update
922 * @param integer $max_items Number of maximum items to fetch
923 * @param string $filter Feed items filter (activity, posts or comments)
924 * @param boolean $nocache Wether to bypass caching
926 * @return string Atom feed
927 * @throws HTTPException\InternalServerErrorException
928 * @throws \ImagickException
930 public static function atom(array $owner, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
932 $stamp = microtime(true);
934 $cachekey = 'feed:feed:' . $owner['nickname'] . ':' . $filter . ':' . $last_update;
936 // Display events in the user's timezone
937 if (strlen($owner['timezone'])) {
938 DI::app()->setTimeZone($owner['timezone']);
941 $previous_created = $last_update;
943 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
944 if ((time() - strtotime($owner['last-item'])) < 15*60) {
945 $result = DI::cache()->get($cachekey);
946 if (!$nocache && !is_null($result)) {
947 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
948 return $result['feed'];
952 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
953 $authorid = Contact::getIdForURL($owner['url']);
955 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
956 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
957 $owner['uid'], $check_date, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT,
958 Item::PRIVATE, Protocol::ACTIVITYPUB,
959 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
961 if ($filter === 'comments') {
962 $condition[0] .= " AND `gravity` = ? ";
963 $condition[] = Item::GRAVITY_COMMENT;
966 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
967 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
968 $condition[] = $owner['id'];
969 $condition[] = $authorid;
972 $params = ['order' => ['received' => true], 'limit' => $max_items];
974 if ($filter === 'posts') {
975 $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
977 $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
980 $items = Post::toArray($ret);
982 $doc = new DOMDocument('1.0', 'utf-8');
983 $doc->formatOutput = true;
985 $root = self::addHeader($doc, $owner, $filter);
987 foreach ($items as $item) {
988 $entry = self::noteEntry($doc, $item, $owner);
989 $root->appendChild($entry);
991 if ($last_update < $item['created']) {
992 $last_update = $item['created'];
996 $feeddata = trim($doc->saveXML());
998 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
999 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1001 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
1007 * Adds the header elements to the XML document
1009 * @param DOMDocument $doc XML document
1010 * @param array $owner Contact data of the poster
1011 * @param string $filter The related feed filter (activity, posts or comments)
1013 * @return DOMElement Header root element
1014 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1016 private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1018 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1019 $doc->appendChild($root);
1022 $selfUri = '/feed/' . $owner['nick'] . '/';
1025 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1026 $selfUri .= $filter;
1029 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1032 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1033 $selfUri .= $filter;
1037 $attributes = ['uri' => 'https://friendi.ca', 'version' => App::VERSION . '-' . DB_UPDATE_VERSION];
1038 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1039 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1040 XML::addElement($doc, $root, 'title', $title);
1041 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1042 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1043 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1045 $author = self::addAuthor($doc, $owner);
1046 $root->appendChild($author);
1048 $attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
1049 XML::addElement($doc, $root, 'link', '', $attributes);
1051 OStatus::addHubLink($doc, $root, $owner['nick']);
1053 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1054 XML::addElement($doc, $root, 'link', '', $attributes);
1060 * Adds the author element to the XML document
1062 * @param DOMDocument $doc XML document
1063 * @param array $owner Contact data of the poster
1064 * @return DOMElement author element
1065 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1067 private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
1069 $author = $doc->createElement('author');
1070 XML::addElement($doc, $author, 'uri', $owner['url']);
1071 XML::addElement($doc, $author, 'name', $owner['nick']);
1072 XML::addElement($doc, $author, 'email', $owner['addr']);
1078 * Adds a regular entry element
1080 * @param DOMDocument $doc XML document
1081 * @param array $item Data of the item that is to be posted
1082 * @param array $owner Contact data of the poster
1083 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1084 * @return DOMElement Entry element
1085 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1086 * @throws \ImagickException
1088 private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
1090 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1091 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
1094 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1096 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1098 self::entryFooter($doc, $entry, $item, $owner);
1104 * Adds elements to the XML document
1106 * @param DOMDocument $doc XML document
1107 * @param \DOMElement $entry Entry element where the content is added
1108 * @param array $item Data of the item that is to be posted
1109 * @param array $owner Contact data of the poster
1110 * @param string $title Title for the post
1111 * @param string $verb The activity verb
1112 * @param bool $complete Add the "status_net" element?
1114 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1116 private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
1119 $verb = OStatus::constructVerb($item);
1122 XML::addElement($doc, $entry, 'id', $item['uri']);
1123 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1125 $body = OStatus::formatPicturePost($item['body'], $item['uri-id']);
1127 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1129 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1131 XML::addElement($doc, $entry, 'link', '', ['rel' => 'alternate', 'type' => 'text/html',
1132 'href' => DI::baseUrl() . '/display/' . $item['guid']]
1135 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1136 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1140 * Adds the elements at the foot of an entry to the XML document
1142 * @param DOMDocument $doc XML document
1143 * @param object $entry The entry element where the elements are added
1144 * @param array $item Data of the item that is to be posted
1145 * @param array $owner Contact data of the poster
1146 * @param bool $complete default true
1148 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1150 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1154 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1155 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1157 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1159 if (DBA::isResult($thrparent)) {
1160 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1161 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1162 $parent_plink = $thrparent['plink'];
1163 } elseif (DBA::isResult($parent)) {
1164 $mentioned[$parent['author-link']] = $parent['author-link'];
1165 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1166 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1168 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1171 if (isset($parent_plink)) {
1173 'ref' => $item['thr-parent'],
1174 'href' => $parent_plink];
1175 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1179 'href' => $parent_plink];
1180 XML::addElement($doc, $entry, 'link', '', $attributes);
1184 // uri-id isn't present for follow entry pseudo-items
1185 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1186 foreach ($tags as $tag) {
1187 $mentioned[$tag['url']] = $tag['url'];
1190 foreach ($tags as $tag) {
1191 if ($tag['type'] == Tag::HASHTAG) {
1192 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1196 OStatus::getAttachment($doc, $entry, $item);
1200 * Fetch or create title for feed entry
1202 * @param array $item
1203 * @return string title
1205 private static function getTitle(array $item): string
1207 if ($item['title'] != '') {
1208 return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1211 // Fetch information about the post
1212 $siteinfo = BBCode::getAttachedData($item['body']);
1213 if (isset($siteinfo['title'])) {
1214 return $siteinfo['title'];
1217 // If no bookmark is found then take the first line
1218 // Remove the share element before fetching the first line
1219 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
1221 $title = BBCode::toPlaintext($title)."\n";
1222 $pos = strpos($title, "\n");
1224 if (($pos == 0) || ($pos > 100)) {
1229 return substr($title, 0, $pos) . $trailer;