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);
388 "`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
389 $importer['uid'], $item['uri'], Protocol::FEED, Protocol::DFRN
391 $previous = Post::selectFirst(['id', 'created'], $condition);
392 if (DBA::isResult($previous)) {
393 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
394 $creation_dates[] = $previous['created'];
395 Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']);
398 $creation_dates[] = DateTimeFormat::utc($item['created']);
401 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
403 if (empty($creator)) {
404 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
407 if (empty($creator)) {
408 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
411 if ($creator != '') {
412 $item['author-name'] = $creator;
415 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
417 if ($creator != '') {
418 $item['author-name'] = $creator;
422 // <category>Ausland</category>
423 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
427 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
428 foreach ($enclosures as $enclosure) {
433 foreach ($enclosure->attributes as $attribute) {
434 if (in_array($attribute->name, ['url', 'href'])) {
435 $href = $attribute->textContent;
436 } elseif ($attribute->name == 'length') {
437 $length = (int)$attribute->textContent;
438 } elseif ($attribute->name == 'type') {
439 $type = $attribute->textContent;
444 $attachment = ['uri-id' => -1, 'type' => Post\Media::UNKNOWN, 'url' => $href, 'mimetype' => $type, 'size' => $length];
446 $attachment = Post\Media::fetchAdditionalData($attachment);
448 // By now we separate the visible media types (audio, video, image) from the rest
449 // In the future we should try to avoid the DOCUMENT type and only use the real one - but not in the RC phase.
450 if (!in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO])) {
451 $attachment['type'] = Post\Media::DOCUMENT;
453 $attachments[] = $attachment;
458 $categories = $xpath->query('category', $entry);
459 foreach ($categories as $category) {
460 $taglist[] = $category->nodeValue;
463 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
466 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
469 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
471 if (empty($summary)) {
472 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
480 if ($body == $summary) {
484 // remove the content of the title if it is identically to the body
485 // This helps with auto generated titles e.g. from tumblr
486 if (self::titleIsBody($item['title'], $body)) {
489 $item['body'] = HTML::toBBCode($body, $basepath);
491 // Remove tracking pixels
492 $item['body'] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item['body']);
494 if (($item['body'] == '') && ($item['title'] != '')) {
495 $item['body'] = $item['title'];
500 $item['attachments'] = $attachments;
503 } elseif (!Item::isValid($item)) {
504 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
506 } elseif (Item::isTooOld($item)) {
507 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
512 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] < 3)) {
513 // Handle enclosures and treat them as preview picture
514 foreach ($attachments as $attachment) {
515 if ($attachment['mimetype'] == 'image/jpeg') {
516 $preview = $attachment['url'];
520 // Remove a possible link to the item itself
521 $item['body'] = str_replace($item['plink'], '', $item['body']);
522 $item['body'] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item['body']));
524 // Replace the content when the title is longer than the body
525 $replace = (strlen($item['title']) > strlen($item['body']));
527 // Replace it, when there is an image in the body
528 if (strstr($item['body'], '[/img]')) {
532 // Replace it, when there is a link in the body
533 if (strstr($item['body'], '[/url]')) {
537 $saved_body = $item['body'];
538 $saved_title = $item['title'];
541 $item['body'] = trim($item['title']);
544 $data = ParseUrl::getSiteinfoCached($item['plink']);
545 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
546 // When the fetched page info text is longer than the body, we do try to enhance the body
547 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
548 // The body is not part of the fetched page info title or page info text. So we add the text to the body
549 $item['body'] .= "\n\n" . $data['text'];
551 // Else we replace the body with the page info text
552 $item['body'] = $data['text'];
556 $data = PageInfo::queryUrl($item['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_denylist'] ?? '');
559 // Take the data that was provided by the feed if the query is empty
560 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
561 $data['title'] = $saved_title;
562 $item['body'] = $saved_body;
565 $data_text = strip_tags(trim($data['text'] ?? ''));
566 $item_body = strip_tags(trim($item['body'] ?? ''));
568 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
572 // We always strip the title since it will be added in the page information
574 $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false);
575 $taglist = $contact['fetch_further_information'] == 2 ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : [];
576 $item['object-type'] = Activity\ObjectType::BOOKMARK;
579 foreach (['audio', 'video'] as $elementname) {
580 if (!empty($data[$elementname])) {
581 foreach ($data[$elementname] as $element) {
582 if (!empty($element['src'])) {
583 $src = $element['src'];
584 } elseif (!empty($element['content'])) {
585 $src = $element['content'];
591 'type' => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
593 'preview' => $element['image'] ?? null,
594 'mimetype' => $element['contenttype'] ?? null,
595 'name' => $element['name'] ?? null,
596 'description' => $element['description'] ?? null,
603 if (!empty($summary)) {
604 $item['body'] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item['body'];
607 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] == 3)) {
608 if (empty($taglist)) {
609 $taglist = PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '');
611 $item['body'] .= "\n" . self::tagToString($taglist);
616 // Add the link to the original feed entry if not present in feed
617 if (($item['plink'] != '') && !strstr($item['body'], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
618 $item['body'] .= '[hr][url]' . $item['plink'] . '[/url]';
622 if (empty($item['title'])) {
623 $item['post-type'] = Item::PT_NOTE;
626 Logger::info('Stored feed', ['item' => $item]);
628 $notify = Item::isRemoteSelf($contact, $item);
629 $item['wall'] = (bool)$notify;
631 // Distributed items should have a well-formatted URI.
632 // Additionally, we have to avoid conflicts with identical URI between imported feeds and these items.
634 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHost());
635 $item['uri'] = Item::newURI($item['guid']);
636 unset($item['plink']);
637 unset($item['thr-parent']);
638 unset($item['parent-uri']);
640 // Set the delivery priority for "remote self" to "medium"
641 $notify = Worker::PRIORITY_MEDIUM;
644 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
645 if (!Post::exists($condition) && !Post\Delayed::exists($item['uri'], $item['uid'])) {
647 Post\Delayed::publish($item, $notify, $taglist, $attachments);
650 'item' => $item, 'notify' => $notify,
651 'taglist' => $taglist, 'attachments' => $attachments
655 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]);
659 if (!empty($postings)) {
660 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
661 $total = count($postings);
663 // Posts shouldn't be delayed more than a day
664 $interval = min(1440, self::getPollInterval($contact));
665 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
666 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
673 foreach ($postings as $posting) {
675 $publish_time = time() + $post_delay;
676 $post_delay += $delay;
678 $publish_time = time();
681 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
682 $next_publish = max($last_publish + (60 * $min_posting), time());
683 if ($publish_time < $next_publish) {
684 $publish_time = $next_publish;
686 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
688 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
689 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
694 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
695 self::adjustPollFrequency($contact, $creation_dates);
698 return ['header' => $author, 'items' => $items];
702 * Automatically adjust the poll frequency according to the post frequency
704 * @param array $contact Contact array
705 * @param array $creation_dates
708 private static function adjustPollFrequency(array $contact, array $creation_dates)
710 if ($contact['network'] != Protocol::FEED) {
711 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
715 if (!empty($creation_dates)) {
716 // Count the post frequency and the earliest and latest post date
720 $oldest_date = $newest_date = '';
722 foreach ($creation_dates as $date) {
723 $timestamp = strtotime($date);
724 $day = intdiv($timestamp, 86400);
725 $hour = $timestamp % 86400;
727 // Only have a look at values from the last seven days
728 if (((time() / 86400) - $day) < 7) {
729 if (empty($frequency[$day])) {
730 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
732 ++$frequency[$day]['count'];
733 if ($frequency[$day]['low'] > $hour) {
734 $frequency[$day]['low'] = $hour;
736 if ($frequency[$day]['high'] < $hour) {
737 $frequency[$day]['high'] = $hour;
741 if ($oldest > $day) {
743 $oldest_date = $date;
746 if ($newest < $day) {
748 $newest_date = $date;
752 if (count($creation_dates) == 1) {
753 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
754 $priority = 8; // Poll once a day
757 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
758 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']]);
759 $priority = 10; // Poll every month
762 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
763 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']]);
764 $priority = 9; // Poll every week
767 if (empty($priority) && empty($frequency)) {
768 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']]);
769 $priority = 8; // Poll once a day
772 if (empty($priority)) {
773 // Calculate the highest "posts per day" value
775 foreach ($frequency as $entry) {
776 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
780 // We take the earliest and latest post day and interpolate the number of post per day
781 // that would had been created with this post frequency
783 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
784 $duration = max($entry['high'] - $entry['low'], 14400);
785 $ppd = (86400 / $duration) * $entry['count'];
791 $priority = 1; // Poll every quarter hour
792 } elseif ($max > 24) {
793 $priority = 2; // Poll half an hour
794 } elseif ($max > 12) {
795 $priority = 3; // Poll hourly
796 } elseif ($max > 8) {
797 $priority = 4; // Poll every two hours
798 } elseif ($max > 4) {
799 $priority = 5; // Poll every three hours
800 } elseif ($max > 2) {
801 $priority = 6; // Poll every six hours
803 $priority = 7; // Poll twice a day
805 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
808 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
809 $priority = 8; // Poll once a day
812 if ($contact['rating'] != $priority) {
813 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
814 Contact::update(['rating' => $priority], ['id' => $contact['id']]);
819 * Get the poll interval for the given contact array
821 * @param array $contact
822 * @return int Poll interval in minutes
824 public static function getPollInterval(array $contact): int
826 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
827 $ratings = [0, 3, 7, 8, 9, 10];
828 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
829 $rating = $contact['rating'];
830 } elseif (array_key_exists($contact['priority'], $ratings)) {
831 $rating = $ratings[$contact['priority']];
836 // Check once a week per default for all other networks
840 // Friendica and OStatus are checked once a day
841 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
845 // Check archived contacts or contacts with unsupported protocols once a month
846 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
854 * Based on $contact['priority'], should we poll this site now? Or later?
857 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
859 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720, 1440, 10080, 43200];
861 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
862 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
864 return $poll_intervals[$rating];
868 * Convert a tag array to a tag string
871 * @return string tag string
873 private static function tagToString(array $tags): string
877 foreach ($tags as $tag) {
882 $tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
888 private static function titleIsBody(string $title, string $body): bool
890 $title = strip_tags($title);
891 $title = trim($title);
892 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
893 $title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
895 $body = strip_tags($body);
897 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
898 $body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
900 if (strlen($title) < strlen($body)) {
901 $body = substr($body, 0, strlen($title));
904 if (($title != $body) && (substr($title, -3) == '...')) {
905 $pos = strrpos($title, '...');
907 $title = substr($title, 0, $pos);
908 $body = substr($body, 0, $pos);
911 return ($title == $body);
915 * Creates the Atom feed for a given nickname
918 * - activity (default): all the public posts
919 * - posts: all the public top-level posts
920 * - comments: all the public replies
922 * Updates the provided last_update parameter if the result comes from the
923 * cache or it is empty
925 * @param array $owner owner-view record of the feed owner
926 * @param string $last_update Date of the last update
927 * @param integer $max_items Number of maximum items to fetch
928 * @param string $filter Feed items filter (activity, posts or comments)
929 * @param boolean $nocache Wether to bypass caching
931 * @return string Atom feed
932 * @throws HTTPException\InternalServerErrorException
933 * @throws \ImagickException
935 public static function atom(array $owner, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
937 $stamp = microtime(true);
939 $cachekey = 'feed:feed:' . $owner['nickname'] . ':' . $filter . ':' . $last_update;
941 // Display events in the user's timezone
942 if (strlen($owner['timezone'])) {
943 DI::app()->setTimeZone($owner['timezone']);
946 $previous_created = $last_update;
948 // Don't cache when the last item was posted less than 15 minutes ago (Cache duration)
949 if ((time() - strtotime($owner['last-item'])) < 15 * 60) {
950 $result = DI::cache()->get($cachekey);
951 if (!$nocache && !is_null($result)) {
952 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
953 return $result['feed'];
957 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
958 $authorid = Contact::getIdForURL($owner['url']);
961 "`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
962 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
963 $owner['uid'], $check_date, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT,
964 Item::PRIVATE, Protocol::ACTIVITYPUB,
965 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA
968 if ($filter === 'comments') {
969 $condition[0] .= " AND `gravity` = ? ";
970 $condition[] = Item::GRAVITY_COMMENT;
973 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
974 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
975 $condition[] = $owner['id'];
976 $condition[] = $authorid;
979 $params = ['order' => ['received' => true], 'limit' => $max_items];
981 if ($filter === 'posts') {
982 $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
984 $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
987 $items = Post::toArray($ret);
989 $doc = new DOMDocument('1.0', 'utf-8');
990 $doc->formatOutput = true;
992 $root = self::addHeader($doc, $owner, $filter);
994 foreach ($items as $item) {
995 $entry = self::noteEntry($doc, $item, $owner);
996 $root->appendChild($entry);
998 if ($last_update < $item['created']) {
999 $last_update = $item['created'];
1003 $feeddata = trim($doc->saveXML());
1005 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
1006 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1008 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
1014 * Adds the header elements to the XML document
1016 * @param DOMDocument $doc XML document
1017 * @param array $owner Contact data of the poster
1018 * @param string $filter The related feed filter (activity, posts or comments)
1020 * @return DOMElement Header root element
1021 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1023 private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1025 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1026 $doc->appendChild($root);
1029 $selfUri = '/feed/' . $owner['nick'] . '/';
1032 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1033 $selfUri .= $filter;
1036 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1039 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1040 $selfUri .= $filter;
1044 $attributes = ['uri' => 'https://friendi.ca', 'version' => App::VERSION . '-' . DB_UPDATE_VERSION];
1045 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1046 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1047 XML::addElement($doc, $root, 'title', $title);
1048 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1049 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1050 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1052 $author = self::addAuthor($doc, $owner);
1053 $root->appendChild($author);
1055 $attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
1056 XML::addElement($doc, $root, 'link', '', $attributes);
1058 OStatus::addHubLink($doc, $root, $owner['nick']);
1060 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1061 XML::addElement($doc, $root, 'link', '', $attributes);
1067 * Adds the author element to the XML document
1069 * @param DOMDocument $doc XML document
1070 * @param array $owner Contact data of the poster
1071 * @return DOMElement author element
1072 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1074 private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
1076 $author = $doc->createElement('author');
1077 XML::addElement($doc, $author, 'uri', $owner['url']);
1078 XML::addElement($doc, $author, 'name', $owner['nick']);
1079 XML::addElement($doc, $author, 'email', $owner['addr']);
1085 * Adds a regular entry element
1087 * @param DOMDocument $doc XML document
1088 * @param array $item Data of the item that is to be posted
1089 * @param array $owner Contact data of the poster
1090 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1091 * @return DOMElement Entry element
1092 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1093 * @throws \ImagickException
1095 private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
1097 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1098 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
1101 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1103 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1105 self::entryFooter($doc, $entry, $item, $owner);
1111 * Adds elements to the XML document
1113 * @param DOMDocument $doc XML document
1114 * @param \DOMElement $entry Entry element where the content is added
1115 * @param array $item Data of the item that is to be posted
1116 * @param array $owner Contact data of the poster
1117 * @param string $title Title for the post
1118 * @param string $verb The activity verb
1119 * @param bool $complete Add the "status_net" element?
1121 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1123 private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
1126 $verb = OStatus::constructVerb($item);
1129 XML::addElement($doc, $entry, 'id', $item['uri']);
1130 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1132 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
1133 $body = Post\Media::addHTMLLinkToBody($item['uri-id'], $body);
1135 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1137 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1145 'rel' => 'alternate', 'type' => 'text/html',
1146 'href' => DI::baseUrl() . '/display/' . $item['guid']
1150 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1151 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1155 * Adds the elements at the foot of an entry to the XML document
1157 * @param DOMDocument $doc XML document
1158 * @param object $entry The entry element where the elements are added
1159 * @param array $item Data of the item that is to be posted
1160 * @param array $owner Contact data of the poster
1161 * @param bool $complete default true
1163 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1165 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1169 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1170 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1172 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1174 if (DBA::isResult($thrparent)) {
1175 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1176 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1177 $parent_plink = $thrparent['plink'];
1178 } elseif (DBA::isResult($parent)) {
1179 $mentioned[$parent['author-link']] = $parent['author-link'];
1180 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1181 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1183 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1186 if (isset($parent_plink)) {
1188 'ref' => $item['thr-parent'],
1189 'href' => $parent_plink
1191 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1195 'href' => $parent_plink
1197 XML::addElement($doc, $entry, 'link', '', $attributes);
1201 // uri-id isn't present for follow entry pseudo-items
1202 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1203 foreach ($tags as $tag) {
1204 $mentioned[$tag['url']] = $tag['url'];
1207 foreach ($tags as $tag) {
1208 if ($tag['type'] == Tag::HASHTAG) {
1209 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1213 OStatus::getAttachment($doc, $entry, $item);
1217 * Fetch or create title for feed entry
1219 * @param array $item
1220 * @return string title
1222 private static function getTitle(array $item): string
1224 if ($item['title'] != '') {
1225 return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1228 // Fetch information about the post
1229 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1230 if (!empty($media) && !empty($media[0]['name']) && ($media[0]['name'] != $media[0]['url'])) {
1231 return $media[0]['name'];
1234 // If no bookmark is found then take the first line
1235 // Remove the share element before fetching the first line
1236 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
1238 $title = BBCode::toPlaintext($title) . "\n";
1239 $pos = strpos($title, "\n");
1241 if (($pos == 0) || ($pos > 100)) {
1246 return substr($title, 0, $pos) . $trailer;