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);
96 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
97 $xpath->registerNamespace('atom03', ActivityNamespace::ATOM03);
98 $xpath->registerNamespace('dc', 'http://purl.org/dc/elements/1.1/');
99 $xpath->registerNamespace('content', 'http://purl.org/rss/1.0/modules/content/');
100 $xpath->registerNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
101 $xpath->registerNamespace('rss', 'http://purl.org/rss/1.0/');
102 $xpath->registerNamespace('media', 'http://search.yahoo.com/mrss/');
103 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
108 $protocol = Conversation::PARCEL_UNKNOWN;
111 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
112 $protocol = Conversation::PARCEL_RDF;
113 $author['author-link'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
114 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
116 if (empty($author['author-name'])) {
117 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
119 $entries = $xpath->query('/rdf:RDF/rss:item');
122 if ($xpath->query('/opml')->length > 0) {
123 $protocol = Conversation::PARCEL_OPML;
124 $author['author-name'] = XML::getFirstNodeValue($xpath, '/opml/head/title/text()');
125 $entries = $xpath->query('/opml/body/outline');
129 if ($xpath->query('/atom:feed')->length > 0) {
130 $protocol = Conversation::PARCEL_ATOM;
131 } elseif ($xpath->query('/atom03:feed')->length > 0) {
132 $protocol = Conversation::PARCEL_ATOM03;
136 if (in_array($protocol, [Conversation::PARCEL_ATOM, Conversation::PARCEL_ATOM03])) {
137 $alternate = XML::getFirstAttributes($xpath, $atomns . ":link[@rel='alternate']");
138 if (is_object($alternate)) {
139 foreach ($alternate as $attribute) {
140 if ($attribute->name == 'href') {
141 $author['author-link'] = $attribute->textContent;
146 if (empty($author['author-link'])) {
147 $self = XML::getFirstAttributes($xpath, $atomns . ":link[@rel='self']");
148 if (is_object($self)) {
149 foreach ($self as $attribute) {
150 if ($attribute->name == 'href') {
151 $author['author-link'] = $attribute->textContent;
157 if (empty($author['author-link'])) {
158 $author['author-link'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':id/text()');
160 $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':logo/text()');
162 $author['author-name'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':title/text()');
164 if (empty($author['author-name'])) {
165 $author['author-name'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':subtitle/text()');
168 if (empty($author['author-name'])) {
169 $author['author-name'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':author/' . $atomns . ':name/text()');
172 $value = XML::getFirstNodeValue($xpath, '' . $atomns . ':author/poco:displayName/text()');
174 $author['author-name'] = $value;
178 $author['author-id'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':author/' . $atomns . ':id/text()');
180 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
181 $value = XML::getFirstNodeValue($xpath, $atomns . ':author/' . $atomns . ':uri/text()');
183 $author['author-link'] = $value;
186 $value = XML::getFirstNodeValue($xpath, $atomns . ':author/poco:preferredUsername/text()');
188 $author['author-nick'] = $value;
191 $value = XML::getFirstNodeValue($xpath, $atomns . ':author/poco:address/poco:formatted/text()');
193 $author['author-location'] = $value;
196 $value = XML::getFirstNodeValue($xpath, $atomns . ':author/poco:note/text()');
198 $author['author-about'] = $value;
201 $avatar = XML::getFirstAttributes($xpath, $atomns . ":author/' . $atomns . ':link[@rel='avatar']");
202 if (is_object($avatar)) {
203 foreach ($avatar as $attribute) {
204 if ($attribute->name == 'href') {
205 $author['author-avatar'] = $attribute->textContent;
211 $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':updated/text()');
213 $author['app'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':generator/text()');
215 $entries = $xpath->query('/' . $atomns . ':feed/' . $atomns . ':entry');
219 if ($xpath->query('/rss/channel')->length > 0) {
220 $protocol = Conversation::PARCEL_RSS;
221 $author['author-link'] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
223 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
225 if (empty($author['author-name'])) {
226 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
229 if (empty($author['author-name'])) {
230 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
233 $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
235 if (empty($author['author-avatar'])) {
236 $avatar = XML::getFirstAttributes($xpath, '/rss/channel/itunes:image');
237 if (is_object($avatar)) {
238 foreach ($avatar as $attribute) {
239 if ($attribute->name == 'href') {
240 $author['author-avatar'] = $attribute->textContent;
246 $author['author-about'] = HTML::toBBCode(XML::getFirstNodeValue($xpath, '/rss/channel/description/text()'), $basepath);
248 if (empty($author['author-about'])) {
249 $author['author-about'] = XML::getFirstNodeValue($xpath, '/rss/channel/itunes:summary/text()');
252 $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
254 $author['app'] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
256 $entries = $xpath->query('/rss/channel/item');
260 $author['author-link'] = $contact['url'];
262 if (empty($author['author-name'])) {
263 $author['author-name'] = $contact['name'];
266 $author['author-avatar'] = $contact['thumb'];
268 $author['owner-link'] = $contact['url'];
269 $author['owner-name'] = $contact['name'];
270 $author['owner-avatar'] = $contact['thumb'];
274 'uid' => $importer['uid'] ?? 0,
275 'network' => Protocol::FEED,
278 'gravity' => Item::GRAVITY_PARENT,
279 'private' => Item::PUBLIC,
280 'verb' => Activity::POST,
281 'object-type' => Activity\ObjectType::NOTE,
282 'post-type' => Item::PT_ARTICLE,
283 'contact-id' => $contact['id'] ?? 0,
286 $datarray['protocol'] = $protocol;
287 $datarray['direction'] = Conversation::PULL;
289 if (!is_object($entries)) {
290 Logger::info("There are no entries in this feed.");
295 $creation_dates = [];
297 // Limit the number of items that are about to be fetched
298 $total_items = ($entries->length - 1);
299 $max_items = DI::config()->get('system', 'max_feed_items');
300 if (($max_items > 0) && ($total_items > $max_items)) {
301 $total_items = $max_items;
306 // Importing older entries first
307 for ($i = $total_items; $i >= 0; --$i) {
308 $entry = $entries->item($i);
310 $item = array_merge($header, $author);
312 $alternate = XML::getFirstAttributes($xpath, $atomns . ":link[@rel='alternate']", $entry);
313 if (!is_object($alternate)) {
314 $alternate = XML::getFirstAttributes($xpath, $atomns . ':link', $entry);
316 if (is_object($alternate)) {
317 foreach ($alternate as $attribute) {
318 if ($attribute->name == 'href') {
319 $item['plink'] = $attribute->textContent;
324 if ($entry->nodeName == 'outline') {
328 foreach ($entry->attributes as $attribute) {
329 switch ($attribute->nodeName) {
331 $item['title'] = $attribute->nodeValue;
335 $body = $attribute->nodeValue;
339 $plink = $attribute->nodeValue;
343 $uri = $attribute->nodeValue;
347 $isrss = $attribute->nodeValue == 'rss';
351 $item['plink'] = $plink ?: $uri;
352 $item['uri'] = $uri ?: $plink;
353 if (!$isrss || empty($item['uri'])) {
358 if (empty($item['plink'])) {
359 $item['plink'] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
362 if (empty($item['plink'])) {
363 $item['plink'] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
366 // Add the base path if missing
367 $item['plink'] = Network::addBasePath($item['plink'], $basepath);
369 if (empty($item['uri'])) {
370 $item['uri'] = XML::getFirstNodeValue($xpath, $atomns . ':id/text()', $entry);
373 $guid = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
375 $item['uri'] = $guid;
377 // Don't use the GUID value directly but instead use it as a basis for the GUID
378 $item['guid'] = Item::guidFromUri($guid, parse_url($guid, PHP_URL_HOST) ?? parse_url($item['plink'], PHP_URL_HOST));
381 if (empty($item['uri'])) {
382 $item['uri'] = $item['plink'];
385 $orig_plink = $item['plink'];
388 $item['plink'] = DI::httpClient()->finalUrl($item['plink']);
389 } catch (TransferException $exception) {
390 Logger::notice('Item URL couldn\'t get expanded', ['url' => $item['plink'], 'exception' => $exception]);
393 if (empty($item['title'])) {
394 $item['title'] = XML::getFirstNodeValue($xpath, $atomns . ':title/text()', $entry);
397 if (empty($item['title'])) {
398 $item['title'] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
401 if (empty($item['title'])) {
402 $item['title'] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
405 if (empty($item['title'])) {
406 $item['title'] = XML::getFirstNodeValue($xpath, 'itunes:title/text()', $entry);
409 $item['title'] = html_entity_decode($item['title'], ENT_QUOTES, 'UTF-8');
411 $published = XML::getFirstNodeValue($xpath, $atomns . ':published/text()', $entry);
413 if (empty($published)) {
414 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
417 if (empty($published)) {
418 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
421 $updated = XML::getFirstNodeValue($xpath, $atomns . ':updated/text()', $entry);
423 if (empty($updated) && !empty($published)) {
424 $updated = $published;
427 if (empty($published) && !empty($updated)) {
428 $published = $updated;
431 if ($published != '') {
432 $item['created'] = trim($published);
435 if ($updated != '') {
436 $item['edited'] = trim($updated);
441 "`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
442 $importer['uid'], $item['uri'], Protocol::FEED, Protocol::DFRN
444 $previous = Post::selectFirst(['id', 'created'], $condition);
445 if (DBA::isResult($previous)) {
446 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
447 $creation_dates[] = $previous['created'];
448 Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']);
451 $creation_dates[] = DateTimeFormat::utc($item['created']);
454 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
456 if (empty($creator)) {
457 $creator = XML::getFirstNodeValue($xpath, $atomns . ':author/' . $atomns . ':name/text()', $entry);
460 if (empty($creator)) {
461 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
464 if ($creator != '') {
465 $item['author-name'] = $creator;
468 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
470 if ($creator != '') {
471 $item['author-name'] = $creator;
475 // <category>Ausland</category>
476 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
480 $enclosures = $xpath->query("enclosure|' . $atomns . ':link[@rel='enclosure']", $entry);
481 if (!empty($enclosures)) {
482 foreach ($enclosures as $enclosure) {
487 foreach ($enclosure->attributes as $attribute) {
488 if (in_array($attribute->name, ['url', 'href'])) {
489 $href = $attribute->textContent;
490 } elseif ($attribute->name == 'length') {
491 $length = (int)$attribute->textContent;
492 } elseif ($attribute->name == 'type') {
493 $type = $attribute->textContent;
498 $attachment = ['uri-id' => -1, 'type' => Post\Media::UNKNOWN, 'url' => $href, 'mimetype' => $type, 'size' => $length];
500 $attachment = Post\Media::fetchAdditionalData($attachment);
502 // By now we separate the visible media types (audio, video, image) from the rest
503 // In the future we should try to avoid the DOCUMENT type and only use the real one - but not in the RC phase.
504 if (!in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO])) {
505 $attachment['type'] = Post\Media::DOCUMENT;
507 $attachments[] = $attachment;
513 $categories = $xpath->query('category', $entry);
514 foreach ($categories as $category) {
515 $taglist[] = $category->nodeValue;
519 $body = trim(XML::getFirstNodeValue($xpath, $atomns . ':content/text()', $entry));
523 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
526 $summary = trim(XML::getFirstNodeValue($xpath, $atomns . ':summary/text()', $entry));
528 if (empty($summary)) {
529 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
537 if ($body == $summary) {
541 // remove the content of the title if it is identically to the body
542 // This helps with auto generated titles e.g. from tumblr
543 if (self::titleIsBody($item['title'], $body)) {
546 $item['body'] = HTML::toBBCode($body, $basepath);
548 // Remove tracking pixels
549 $item['body'] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item['body']);
551 if (($item['body'] == '') && ($item['title'] != '')) {
552 $item['body'] = $item['title'];
557 $item['attachments'] = $attachments;
560 } elseif (!Item::isValid($item)) {
561 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
563 } elseif (Item::isTooOld($item)) {
564 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
569 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] < 3)) {
570 // Handle enclosures and treat them as preview picture
571 foreach ($attachments as $attachment) {
572 if ($attachment['mimetype'] == 'image/jpeg') {
573 $preview = $attachment['url'];
577 // Remove a possible link to the item itself
578 $item['body'] = str_replace($item['plink'], '', $item['body']);
579 $item['body'] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item['body']));
581 // Replace the content when the title is longer than the body
582 $replace = (strlen($item['title']) > strlen($item['body']));
584 // Replace it, when there is an image in the body
585 if (strstr($item['body'], '[/img]')) {
589 // Replace it, when there is a link in the body
590 if (strstr($item['body'], '[/url]')) {
594 $saved_body = $item['body'];
595 $saved_title = $item['title'];
598 $item['body'] = trim($item['title']);
601 $data = ParseUrl::getSiteinfoCached($item['plink']);
602 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
603 // When the fetched page info text is longer than the body, we do try to enhance the body
604 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
605 // The body is not part of the fetched page info title or page info text. So we add the text to the body
606 $item['body'] .= "\n\n" . $data['text'];
608 // Else we replace the body with the page info text
609 $item['body'] = $data['text'];
613 $data = PageInfo::queryUrl($item['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_denylist'] ?? '');
616 // Take the data that was provided by the feed if the query is empty
617 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
618 $data['title'] = $saved_title;
619 $item['body'] = $saved_body;
622 $data_text = strip_tags(trim($data['text'] ?? ''));
623 $item_body = strip_tags(trim($item['body'] ?? ''));
625 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
629 // We always strip the title since it will be added in the page information
631 $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false);
632 $taglist = $contact['fetch_further_information'] == 2 ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : [];
633 $item['object-type'] = Activity\ObjectType::BOOKMARK;
636 foreach (['audio', 'video'] as $elementname) {
637 if (!empty($data[$elementname])) {
638 foreach ($data[$elementname] as $element) {
639 if (!empty($element['src'])) {
640 $src = $element['src'];
641 } elseif (!empty($element['content'])) {
642 $src = $element['content'];
648 'type' => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
650 'preview' => $element['image'] ?? null,
651 'mimetype' => $element['contenttype'] ?? null,
652 'name' => $element['name'] ?? null,
653 'description' => $element['description'] ?? null,
660 if (!empty($summary)) {
661 $item['body'] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item['body'];
664 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] == 3)) {
665 if (empty($taglist)) {
666 $taglist = PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '');
668 $item['body'] .= "\n" . self::tagToString($taglist);
673 // Add the link to the original feed entry if not present in feed
674 if (($item['plink'] != '') && !strstr($item['body'], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
675 $item['body'] .= '[hr][url]' . $item['plink'] . '[/url]';
679 if (empty($item['title'])) {
680 $item['post-type'] = Item::PT_NOTE;
683 Logger::info('Stored feed', ['item' => $item]);
685 $notify = Item::isRemoteSelf($contact, $item);
686 $item['wall'] = (bool)$notify;
688 // Distributed items should have a well-formatted URI.
689 // Additionally, we have to avoid conflicts with identical URI between imported feeds and these items.
691 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHost());
692 $item['uri'] = Item::newURI($item['guid']);
693 unset($item['plink']);
694 unset($item['thr-parent']);
695 unset($item['parent-uri']);
697 // Set the delivery priority for "remote self" to "medium"
698 $notify = Worker::PRIORITY_MEDIUM;
701 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
702 if (!Post::exists($condition) && !Post\Delayed::exists($item['uri'], $item['uid'])) {
704 Post\Delayed::publish($item, $notify, $taglist, $attachments);
707 'item' => $item, 'notify' => $notify,
708 'taglist' => $taglist, 'attachments' => $attachments
712 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]);
716 if (!empty($postings)) {
717 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
718 $total = count($postings);
720 // Posts shouldn't be delayed more than a day
721 $interval = min(1440, self::getPollInterval($contact));
722 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
723 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
730 foreach ($postings as $posting) {
732 $publish_time = time() + $post_delay;
733 $post_delay += $delay;
735 $publish_time = time();
738 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
739 $next_publish = max($last_publish + (60 * $min_posting), time());
740 if ($publish_time < $next_publish) {
741 $publish_time = $next_publish;
743 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
745 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
746 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
751 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
752 self::adjustPollFrequency($contact, $creation_dates);
755 return ['header' => $author, 'items' => $items];
759 * Automatically adjust the poll frequency according to the post frequency
761 * @param array $contact Contact array
762 * @param array $creation_dates
765 private static function adjustPollFrequency(array $contact, array $creation_dates)
767 if ($contact['network'] != Protocol::FEED) {
768 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
772 if (!empty($creation_dates)) {
773 // Count the post frequency and the earliest and latest post date
777 $oldest_date = $newest_date = '';
779 foreach ($creation_dates as $date) {
780 $timestamp = strtotime($date);
781 $day = intdiv($timestamp, 86400);
782 $hour = $timestamp % 86400;
784 // Only have a look at values from the last seven days
785 if (((time() / 86400) - $day) < 7) {
786 if (empty($frequency[$day])) {
787 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
789 ++$frequency[$day]['count'];
790 if ($frequency[$day]['low'] > $hour) {
791 $frequency[$day]['low'] = $hour;
793 if ($frequency[$day]['high'] < $hour) {
794 $frequency[$day]['high'] = $hour;
798 if ($oldest > $day) {
800 $oldest_date = $date;
803 if ($newest < $day) {
805 $newest_date = $date;
809 if (count($creation_dates) == 1) {
810 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
811 $priority = 8; // Poll once a day
814 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
815 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']]);
816 $priority = 10; // Poll every month
819 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
820 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']]);
821 $priority = 9; // Poll every week
824 if (empty($priority) && empty($frequency)) {
825 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']]);
826 $priority = 8; // Poll once a day
829 if (empty($priority)) {
830 // Calculate the highest "posts per day" value
832 foreach ($frequency as $entry) {
833 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
837 // We take the earliest and latest post day and interpolate the number of post per day
838 // that would had been created with this post frequency
840 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
841 $duration = max($entry['high'] - $entry['low'], 14400);
842 $ppd = (86400 / $duration) * $entry['count'];
848 $priority = 1; // Poll every quarter hour
849 } elseif ($max > 24) {
850 $priority = 2; // Poll half an hour
851 } elseif ($max > 12) {
852 $priority = 3; // Poll hourly
853 } elseif ($max > 8) {
854 $priority = 4; // Poll every two hours
855 } elseif ($max > 4) {
856 $priority = 5; // Poll every three hours
857 } elseif ($max > 2) {
858 $priority = 6; // Poll every six hours
860 $priority = 7; // Poll twice a day
862 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
865 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
866 $priority = 8; // Poll once a day
869 if ($contact['rating'] != $priority) {
870 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
871 Contact::update(['rating' => $priority], ['id' => $contact['id']]);
876 * Get the poll interval for the given contact array
878 * @param array $contact
879 * @return int Poll interval in minutes
881 public static function getPollInterval(array $contact): int
883 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
884 $ratings = [0, 3, 7, 8, 9, 10];
885 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
886 $rating = $contact['rating'];
887 } elseif (array_key_exists($contact['priority'], $ratings)) {
888 $rating = $ratings[$contact['priority']];
893 // Check once a week per default for all other networks
897 // Friendica and OStatus are checked once a day
898 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
902 // Check archived contacts or contacts with unsupported protocols once a month
903 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
911 * Based on $contact['priority'], should we poll this site now? Or later?
914 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
916 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720, 1440, 10080, 43200];
918 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
919 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
921 return $poll_intervals[$rating];
925 * Convert a tag array to a tag string
928 * @return string tag string
930 private static function tagToString(array $tags): string
934 foreach ($tags as $tag) {
939 $tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
945 private static function titleIsBody(string $title, string $body): bool
947 $title = strip_tags($title);
948 $title = trim($title);
949 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
950 $title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
952 $body = strip_tags($body);
954 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
955 $body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
957 if (strlen($title) < strlen($body)) {
958 $body = substr($body, 0, strlen($title));
961 if (($title != $body) && (substr($title, -3) == '...')) {
962 $pos = strrpos($title, '...');
964 $title = substr($title, 0, $pos);
965 $body = substr($body, 0, $pos);
968 return ($title == $body);
972 * Creates the Atom feed for a given nickname
975 * - activity (default): all the public posts
976 * - posts: all the public top-level posts
977 * - comments: all the public replies
979 * Updates the provided last_update parameter if the result comes from the
980 * cache or it is empty
982 * @param array $owner owner-view record of the feed owner
983 * @param string $last_update Date of the last update
984 * @param integer $max_items Number of maximum items to fetch
985 * @param string $filter Feed items filter (activity, posts or comments)
986 * @param boolean $nocache Wether to bypass caching
988 * @return string Atom feed
989 * @throws HTTPException\InternalServerErrorException
990 * @throws \ImagickException
992 public static function atom(array $owner, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
994 $stamp = microtime(true);
996 $cachekey = 'feed:feed:' . $owner['nickname'] . ':' . $filter . ':' . $last_update;
998 // Display events in the user's timezone
999 if (strlen($owner['timezone'])) {
1000 DI::app()->setTimeZone($owner['timezone']);
1003 $previous_created = $last_update;
1005 // Don't cache when the last item was posted less than 15 minutes ago (Cache duration)
1006 if ((time() - strtotime($owner['last-item'])) < 15 * 60) {
1007 $result = DI::cache()->get($cachekey);
1008 if (!$nocache && !is_null($result)) {
1009 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
1010 return $result['feed'];
1014 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
1015 $authorid = Contact::getIdForURL($owner['url']);
1018 "`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
1019 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
1020 $owner['uid'], $check_date, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT,
1021 Item::PRIVATE, Protocol::ACTIVITYPUB,
1022 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA
1025 if ($filter === 'comments') {
1026 $condition[0] .= " AND `gravity` = ? ";
1027 $condition[] = Item::GRAVITY_COMMENT;
1030 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1031 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
1032 $condition[] = $owner['id'];
1033 $condition[] = $authorid;
1036 $params = ['order' => ['received' => true], 'limit' => $max_items];
1038 if ($filter === 'posts') {
1039 $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
1041 $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
1044 $items = Post::toArray($ret);
1046 $doc = new DOMDocument('1.0', 'utf-8');
1047 $doc->formatOutput = true;
1049 $root = self::addHeader($doc, $owner, $filter);
1051 foreach ($items as $item) {
1052 $entry = self::noteEntry($doc, $item, $owner);
1053 $root->appendChild($entry);
1055 if ($last_update < $item['created']) {
1056 $last_update = $item['created'];
1060 $feeddata = trim($doc->saveXML());
1062 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
1063 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1065 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
1071 * Adds the header elements to the XML document
1073 * @param DOMDocument $doc XML document
1074 * @param array $owner Contact data of the poster
1075 * @param string $filter The related feed filter (activity, posts or comments)
1077 * @return DOMElement Header root element
1078 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1080 private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1082 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1083 $doc->appendChild($root);
1086 $selfUri = '/feed/' . $owner['nick'] . '/';
1089 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1090 $selfUri .= $filter;
1093 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1096 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1097 $selfUri .= $filter;
1101 $attributes = ['uri' => 'https://friendi.ca', 'version' => App::VERSION . '-' . DB_UPDATE_VERSION];
1102 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1103 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1104 XML::addElement($doc, $root, 'title', $title);
1105 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1106 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1107 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1109 $author = self::addAuthor($doc, $owner);
1110 $root->appendChild($author);
1112 $attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
1113 XML::addElement($doc, $root, 'link', '', $attributes);
1115 OStatus::addHubLink($doc, $root, $owner['nick']);
1117 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1118 XML::addElement($doc, $root, 'link', '', $attributes);
1124 * Adds the author element to the XML document
1126 * @param DOMDocument $doc XML document
1127 * @param array $owner Contact data of the poster
1128 * @return DOMElement author element
1129 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1131 private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
1133 $author = $doc->createElement('author');
1134 XML::addElement($doc, $author, 'uri', $owner['url']);
1135 XML::addElement($doc, $author, 'name', $owner['nick']);
1136 XML::addElement($doc, $author, 'email', $owner['addr']);
1142 * Adds a regular entry element
1144 * @param DOMDocument $doc XML document
1145 * @param array $item Data of the item that is to be posted
1146 * @param array $owner Contact data of the poster
1147 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1148 * @return DOMElement Entry element
1149 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1150 * @throws \ImagickException
1152 private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
1154 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1155 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
1158 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1160 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1162 self::entryFooter($doc, $entry, $item, $owner);
1168 * Adds elements to the XML document
1170 * @param DOMDocument $doc XML document
1171 * @param \DOMElement $entry Entry element where the content is added
1172 * @param array $item Data of the item that is to be posted
1173 * @param array $owner Contact data of the poster
1174 * @param string $title Title for the post
1175 * @param string $verb The activity verb
1176 * @param bool $complete Add the "status_net" element?
1178 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1180 private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
1183 $verb = OStatus::constructVerb($item);
1186 XML::addElement($doc, $entry, 'id', $item['uri']);
1187 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1189 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
1190 $body = Post\Media::addHTMLLinkToBody($item['uri-id'], $body);
1192 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1194 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1202 'rel' => 'alternate', 'type' => 'text/html',
1203 'href' => DI::baseUrl() . '/display/' . $item['guid']
1207 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1208 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1212 * Adds the elements at the foot of an entry to the XML document
1214 * @param DOMDocument $doc XML document
1215 * @param object $entry The entry element where the elements are added
1216 * @param array $item Data of the item that is to be posted
1217 * @param array $owner Contact data of the poster
1218 * @param bool $complete default true
1220 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1222 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1226 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1227 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1229 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1231 if (DBA::isResult($thrparent)) {
1232 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1233 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1234 $parent_plink = $thrparent['plink'];
1235 } elseif (DBA::isResult($parent)) {
1236 $mentioned[$parent['author-link']] = $parent['author-link'];
1237 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1238 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1240 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1243 if (isset($parent_plink)) {
1245 'ref' => $item['thr-parent'],
1246 'href' => $parent_plink
1248 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1252 'href' => $parent_plink
1254 XML::addElement($doc, $entry, 'link', '', $attributes);
1258 // uri-id isn't present for follow entry pseudo-items
1259 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1260 foreach ($tags as $tag) {
1261 $mentioned[$tag['url']] = $tag['url'];
1264 foreach ($tags as $tag) {
1265 if ($tag['type'] == Tag::HASHTAG) {
1266 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1270 OStatus::getAttachment($doc, $entry, $item);
1274 * Fetch or create title for feed entry
1276 * @param array $item
1277 * @return string title
1279 private static function getTitle(array $item): string
1281 if ($item['title'] != '') {
1282 return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1285 // Fetch information about the post
1286 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1287 if (!empty($media) && !empty($media[0]['name']) && ($media[0]['name'] != $media[0]['url'])) {
1288 return $media[0]['name'];
1291 // If no bookmark is found then take the first line
1292 // Remove the share element before fetching the first line
1293 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
1295 $title = BBCode::toPlaintext($title) . "\n";
1296 $pos = strpos($title, "\n");
1298 if (($pos == 0) || ($pos > 100)) {
1303 return substr($title, 0, $pos) . $trailer;