3 * @copyright Copyright (C) 2010-2022, 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;
27 use Friendica\Content\PageInfo;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Cache\Enum\Duration;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Item;
37 use Friendica\Model\Post;
38 use Friendica\Model\Tag;
39 use Friendica\Model\User;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Network;
42 use Friendica\Util\ParseUrl;
43 use Friendica\Util\Proxy;
44 use Friendica\Util\Strings;
45 use Friendica\Util\XML;
46 use GuzzleHttp\Exception\TransferException;
49 * This class contain functions to import feeds (RSS/RDF/Atom)
54 * Read a RSS/RDF/Atom feed and create an item entry for it
56 * @param string $xml The feed data
57 * @param array $importer The user record of the importer
58 * @param array $contact The contact record of the feed
60 * @return array Returns the header and the first item in dry run mode
61 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
63 public static function import(string $xml, array $importer = [], array $contact = []): array
65 $dryRun = empty($importer) && empty($contact);
68 Logger::info("Test Atom/RSS feed");
70 Logger::info('Import Atom/RSS feed "' . $contact['name'] . '" (Contact ' . $contact['id'] . ') for user ' . $importer['uid']);
76 Logger::info('XML is empty.');
80 if (!empty($contact['poll'])) {
81 $basepath = $contact['poll'];
82 } elseif (!empty($contact['url'])) {
83 $basepath = $contact['url'];
88 $doc = new DOMDocument();
90 $xpath = new DOMXPath($doc);
91 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
92 $xpath->registerNamespace('dc', 'http://purl.org/dc/elements/1.1/');
93 $xpath->registerNamespace('content', 'http://purl.org/rss/1.0/modules/content/');
94 $xpath->registerNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
95 $xpath->registerNamespace('rss', 'http://purl.org/rss/1.0/');
96 $xpath->registerNamespace('media', 'http://search.yahoo.com/mrss/');
97 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
103 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
104 $author['author-link'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
105 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
107 if (empty($author['author-name'])) {
108 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
110 $entries = $xpath->query('/rdf:RDF/rss:item');
114 if ($xpath->query('/atom:feed')->length > 0) {
115 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
116 if (is_object($alternate)) {
117 foreach ($alternate as $attribute) {
118 if ($attribute->name == 'href') {
119 $author['author-link'] = $attribute->textContent;
124 if (empty($author['author-link'])) {
125 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
126 if (is_object($self)) {
127 foreach ($self as $attribute) {
128 if ($attribute->name == 'href') {
129 $author['author-link'] = $attribute->textContent;
135 if (empty($author['author-link'])) {
136 $author['author-link'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
138 $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
140 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
142 if (empty($author['author-name'])) {
143 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
146 if (empty($author['author-name'])) {
147 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
150 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
152 $author['author-name'] = $value;
156 $author['author-id'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
158 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
159 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
161 $author['author-link'] = $value;
164 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
166 $author['author-nick'] = $value;
169 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
171 $author['author-location'] = $value;
174 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
176 $author['author-about'] = $value;
179 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
180 if (is_object($avatar)) {
181 foreach ($avatar as $attribute) {
182 if ($attribute->name == 'href') {
183 $author['author-avatar'] = $attribute->textContent;
189 $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
191 $author['app'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
193 $entries = $xpath->query('/atom:feed/atom:entry');
197 if ($xpath->query('/rss/channel')->length > 0) {
198 $author['author-link'] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
200 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
202 if (empty($author['author-name'])) {
203 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
206 if (empty($author['author-name'])) {
207 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
210 $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
212 if (empty($author['author-avatar'])) {
213 $avatar = XML::getFirstAttributes($xpath, '/rss/channel/itunes:image');
214 if (is_object($avatar)) {
215 foreach ($avatar as $attribute) {
216 if ($attribute->name == 'href') {
217 $author['author-avatar'] = $attribute->textContent;
223 $author['author-about'] = HTML::toBBCode(XML::getFirstNodeValue($xpath, '/rss/channel/description/text()'), $basepath);
225 if (empty($author['author-about'])) {
226 $author['author-about'] = XML::getFirstNodeValue($xpath, '/rss/channel/itunes:summary/text()');
229 $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
231 $author['app'] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
233 $entries = $xpath->query('/rss/channel/item');
237 $author['author-link'] = $contact['url'];
239 if (empty($author['author-name'])) {
240 $author['author-name'] = $contact['name'];
243 $author['author-avatar'] = $contact['thumb'];
245 $author['owner-link'] = $contact['url'];
246 $author['owner-name'] = $contact['name'];
247 $author['owner-avatar'] = $contact['thumb'];
251 $header['uid'] = $importer['uid'] ?? 0;
252 $header['network'] = Protocol::FEED;
254 $header['origin'] = 0;
255 $header['gravity'] = GRAVITY_PARENT;
256 $header['private'] = Item::PUBLIC;
257 $header['verb'] = Activity::POST;
258 $header['object-type'] = Activity\ObjectType::NOTE;
259 $header['post-type'] = Item::PT_ARTICLE;
261 $header['contact-id'] = $contact['id'] ?? 0;
263 if (!is_object($entries)) {
264 Logger::info("There are no entries in this feed.");
269 $creation_dates = [];
271 // Limit the number of items that are about to be fetched
272 $total_items = ($entries->length - 1);
273 $max_items = DI::config()->get('system', 'max_feed_items');
274 if (($max_items > 0) && ($total_items > $max_items)) {
275 $total_items = $max_items;
280 // Importing older entries first
281 for ($i = $total_items; $i >= 0; --$i) {
282 $entry = $entries->item($i);
284 $item = array_merge($header, $author);
286 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
287 if (!is_object($alternate)) {
288 $alternate = XML::getFirstAttributes($xpath, 'atom:link', $entry);
290 if (is_object($alternate)) {
291 foreach ($alternate as $attribute) {
292 if ($attribute->name == 'href') {
293 $item['plink'] = $attribute->textContent;
298 if (empty($item['plink'])) {
299 $item['plink'] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
302 if (empty($item['plink'])) {
303 $item['plink'] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
306 // Add the base path if missing
307 $item['plink'] = Network::addBasePath($item['plink'], $basepath);
309 $item['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
311 $guid = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
313 $item['uri'] = $guid;
315 // Don't use the GUID value directly but instead use it as a basis for the GUID
316 $item['guid'] = Item::guidFromUri($guid, parse_url($guid, PHP_URL_HOST) ?? parse_url($item['plink'], PHP_URL_HOST) ?? '');
319 if (empty($item['uri'])) {
320 $item['uri'] = $item['plink'];
323 $orig_plink = $item['plink'];
326 $item['plink'] = DI::httpClient()->finalUrl($item['plink']);
327 } catch (TransferException $exception) {
328 Logger::notice('Item URL couldn\'t get expanded', ['url' => $item['plink'], 'exception' => $exception]);
331 $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
333 if (empty($item['title'])) {
334 $item['title'] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
337 if (empty($item['title'])) {
338 $item['title'] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
341 if (empty($item['title'])) {
342 $item['title'] = XML::getFirstNodeValue($xpath, 'itunes:title/text()', $entry);
345 $item['title'] = html_entity_decode($item['title'], ENT_QUOTES, 'UTF-8');
347 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
349 if (empty($published)) {
350 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
353 if (empty($published)) {
354 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
357 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
359 if (empty($updated) && !empty($published)) {
360 $updated = $published;
363 if (empty($published) && !empty($updated)) {
364 $published = $updated;
367 if ($published != '') {
368 $item['created'] = $published;
371 if ($updated != '') {
372 $item['edited'] = $updated;
376 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
377 $importer['uid'], $item['uri'], Protocol::FEED, Protocol::DFRN];
378 $previous = Post::selectFirst(['id', 'created'], $condition);
379 if (DBA::isResult($previous)) {
380 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
381 $creation_dates[] = $previous['created'];
382 Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']);
385 $creation_dates[] = DateTimeFormat::utc($item['created']);
388 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
390 if (empty($creator)) {
391 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
394 if (empty($creator)) {
395 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
398 if ($creator != '') {
399 $item['author-name'] = $creator;
402 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
404 if ($creator != '') {
405 $item['author-name'] = $creator;
409 // <category>Ausland</category>
410 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
414 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
415 foreach ($enclosures as $enclosure) {
420 foreach ($enclosure->attributes as $attribute) {
421 if (in_array($attribute->name, ['url', 'href'])) {
422 $href = $attribute->textContent;
423 } elseif ($attribute->name == 'length') {
424 $length = (int)$attribute->textContent;
425 } elseif ($attribute->name == 'type') {
426 $type = $attribute->textContent;
431 $attachment = ['type' => Post\Media::UNKNOWN, 'url' => $href, 'mimetype' => $type, 'size' => $length];
433 $attachment = Post\Media::fetchAdditionalData($attachment);
435 // By now we separate the visible media types (audio, video, image) from the rest
436 // In the future we should try to avoid the DOCUMENT type and only use the real one - but not in the RC phase.
437 if (!in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO])) {
438 $attachment['type'] = Post\Media::DOCUMENT;
440 $attachments[] = $attachment;
445 $categories = $xpath->query('category', $entry);
446 foreach ($categories as $category) {
447 $taglist[] = $category->nodeValue;
450 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
453 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
456 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
458 if (empty($summary)) {
459 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
467 if ($body == $summary) {
471 // remove the content of the title if it is identically to the body
472 // This helps with auto generated titles e.g. from tumblr
473 if (self::titleIsBody($item['title'], $body)) {
476 $item['body'] = HTML::toBBCode($body, $basepath);
478 // Remove tracking pixels
479 $item['body'] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item['body']);
481 if (($item['body'] == '') && ($item['title'] != '')) {
482 $item['body'] = $item['title'];
487 $item['attachments'] = $attachments;
490 } elseif (!Item::isValid($item)) {
491 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
493 } elseif (Item::isTooOld($item)) {
494 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
499 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] < 3)) {
500 // Handle enclosures and treat them as preview picture
501 foreach ($attachments as $attachment) {
502 if ($attachment['mimetype'] == 'image/jpeg') {
503 $preview = $attachment['url'];
507 // Remove a possible link to the item itself
508 $item['body'] = str_replace($item['plink'], '', $item['body']);
509 $item['body'] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item['body']));
511 // Replace the content when the title is longer than the body
512 $replace = (strlen($item['title']) > strlen($item['body']));
514 // Replace it, when there is an image in the body
515 if (strstr($item['body'], '[/img]')) {
519 // Replace it, when there is a link in the body
520 if (strstr($item['body'], '[/url]')) {
524 $saved_body = $item['body'];
525 $saved_title = $item['title'];
528 $item['body'] = trim($item['title']);
531 $data = ParseUrl::getSiteinfoCached($item['plink']);
532 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
533 // When the fetched page info text is longer than the body, we do try to enhance the body
534 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
535 // The body is not part of the fetched page info title or page info text. So we add the text to the body
536 $item['body'] .= "\n\n" . $data['text'];
538 // Else we replace the body with the page info text
539 $item['body'] = $data['text'];
543 $data = PageInfo::queryUrl($item['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_denylist'] ?? '');
546 // Take the data that was provided by the feed if the query is empty
547 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
548 $data['title'] = $saved_title;
549 $item['body'] = $saved_body;
552 $data_text = strip_tags(trim($data['text'] ?? ''));
553 $item_body = strip_tags(trim($item['body'] ?? ''));
555 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
559 // We always strip the title since it will be added in the page information
561 $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false);
562 $taglist = $contact['fetch_further_information'] == 2 ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : [];
563 $item['object-type'] = Activity\ObjectType::BOOKMARK;
566 foreach (['audio', 'video'] as $elementname) {
567 if (!empty($data[$elementname])) {
568 foreach ($data[$elementname] as $element) {
569 if (!empty($element['src'])) {
570 $src = $element['src'];
571 } elseif (!empty($element['content'])) {
572 $src = $element['content'];
578 'type' => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
580 'preview' => $element['image'] ?? null,
581 'mimetype' => $element['contenttype'] ?? null,
582 'name' => $element['name'] ?? null,
583 'description' => $element['description'] ?? null,
590 if (!empty($summary)) {
591 $item['body'] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item['body'];
594 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] == 3)) {
595 if (empty($taglist)) {
596 $taglist = PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '');
598 $item['body'] .= "\n" . self::tagToString($taglist);
603 // Add the link to the original feed entry if not present in feed
604 if (($item['plink'] != '') && !strstr($item['body'], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
605 $item['body'] .= '[hr][url]' . $item['plink'] . '[/url]';
609 if (empty($item['title'])) {
610 $item['post-type'] = Item::PT_NOTE;
613 Logger::info('Stored feed', ['item' => $item]);
615 $notify = Item::isRemoteSelf($contact, $item);
617 // Distributed items should have a well formatted URI.
618 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
620 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
621 $item['uri'] = Item::newURI($item['uid'], $item['guid']);
622 unset($item['thr-parent']);
623 unset($item['parent-uri']);
625 // Set the delivery priority for "remote self" to "medium"
626 $notify = PRIORITY_MEDIUM;
629 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
630 if (!Post::exists($condition) && !Post\Delayed::exists($item['uri'], $item['uid'])) {
632 Post\Delayed::publish($item, $notify, $taglist, $attachments);
634 $postings[] = ['item' => $item, 'notify' => $notify,
635 'taglist' => $taglist, 'attachments' => $attachments];
638 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]);
642 if (!empty($postings)) {
643 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
644 $total = count($postings);
646 // Posts shouldn't be delayed more than a day
647 $interval = min(1440, self::getPollInterval($contact));
648 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
649 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
656 foreach ($postings as $posting) {
658 $publish_time = time() + $post_delay;
659 $post_delay += $delay;
661 $publish_time = time();
664 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
665 $next_publish = max($last_publish + (60 * $min_posting), time());
666 if ($publish_time < $next_publish) {
667 $publish_time = $next_publish;
669 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
671 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
672 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
677 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
678 self::adjustPollFrequency($contact, $creation_dates);
681 return ['header' => $author, 'items' => $items];
685 * Automatically adjust the poll frequency according to the post frequency
687 * @param array $contact Contact array
688 * @param array $creation_dates
691 private static function adjustPollFrequency(array $contact, array $creation_dates)
693 if ($contact['network'] != Protocol::FEED) {
694 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
698 if (!empty($creation_dates)) {
699 // Count the post frequency and the earliest and latest post date
703 $oldest_date = $newest_date = '';
705 foreach ($creation_dates as $date) {
706 $timestamp = strtotime($date);
707 $day = intdiv($timestamp, 86400);
708 $hour = $timestamp % 86400;
710 // Only have a look at values from the last seven days
711 if (((time() / 86400) - $day) < 7) {
712 if (empty($frequency[$day])) {
713 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
715 ++$frequency[$day]['count'];
716 if ($frequency[$day]['low'] > $hour) {
717 $frequency[$day]['low'] = $hour;
719 if ($frequency[$day]['high'] < $hour) {
720 $frequency[$day]['high'] = $hour;
724 if ($oldest > $day) {
726 $oldest_date = $date;
729 if ($newest < $day) {
731 $newest_date = $date;
735 if (count($creation_dates) == 1) {
736 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
737 $priority = 8; // Poll once a day
740 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
741 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']]);
742 $priority = 10; // Poll every month
745 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
746 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']]);
747 $priority = 9; // Poll every week
750 if (empty($priority) && empty($frequency)) {
751 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']]);
752 $priority = 8; // Poll once a day
755 if (empty($priority)) {
756 // Calculate the highest "posts per day" value
758 foreach ($frequency as $entry) {
759 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
763 // We take the earliest and latest post day and interpolate the number of post per day
764 // that would had been created with this post frequency
766 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
767 $duration = max($entry['high'] - $entry['low'], 14400);
768 $ppd = (86400 / $duration) * $entry['count'];
774 $priority = 1; // Poll every quarter hour
775 } elseif ($max > 24) {
776 $priority = 2; // Poll half an hour
777 } elseif ($max > 12) {
778 $priority = 3; // Poll hourly
779 } elseif ($max > 8) {
780 $priority = 4; // Poll every two hours
781 } elseif ($max > 4) {
782 $priority = 5; // Poll every three hours
783 } elseif ($max > 2) {
784 $priority = 6; // Poll every six hours
786 $priority = 7; // Poll twice a day
788 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
791 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
792 $priority = 8; // Poll once a day
795 if ($contact['rating'] != $priority) {
796 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
797 Contact::update(['rating' => $priority], ['id' => $contact['id']]);
802 * Get the poll interval for the given contact array
804 * @param array $contact
805 * @return int Poll interval in minutes
807 public static function getPollInterval(array $contact): int
809 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
810 $ratings = [0, 3, 7, 8, 9, 10];
811 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
812 $rating = $contact['rating'];
813 } elseif (array_key_exists($contact['priority'], $ratings)) {
814 $rating = $ratings[$contact['priority']];
819 // Check once a week per default for all other networks
823 // Friendica and OStatus are checked once a day
824 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
828 // Check archived contacts or contacts with unsupported protocols once a month
829 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
837 * Based on $contact['priority'], should we poll this site now? Or later?
840 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
842 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
844 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
845 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
847 return $poll_intervals[$rating];
851 * Convert a tag array to a tag string
854 * @return string tag string
856 private static function tagToString(array $tags): string
860 foreach ($tags as $tag) {
865 $tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
871 private static function titleIsBody(string $title, string $body): bool
873 $title = strip_tags($title);
874 $title = trim($title);
875 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
876 $title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
878 $body = strip_tags($body);
880 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
881 $body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
883 if (strlen($title) < strlen($body)) {
884 $body = substr($body, 0, strlen($title));
887 if (($title != $body) && (substr($title, -3) == '...')) {
888 $pos = strrpos($title, '...');
890 $title = substr($title, 0, $pos);
891 $body = substr($body, 0, $pos);
894 return ($title == $body);
898 * Creates the Atom feed for a given nickname
901 * - activity (default): all the public posts
902 * - posts: all the public top-level posts
903 * - comments: all the public replies
905 * Updates the provided last_update parameter if the result comes from the
906 * cache or it is empty
908 * @param string $owner_nick Nickname of the feed owner
909 * @param string $last_update Date of the last update
910 * @param integer $max_items Number of maximum items to fetch
911 * @param string $filter Feed items filter (activity, posts or comments)
912 * @param boolean $nocache Wether to bypass caching
914 * @return string Atom feed
915 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
916 * @throws \ImagickException
918 public static function atom(string $owner_nick, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
920 $stamp = microtime(true);
922 $owner = User::getOwnerDataByNick($owner_nick);
927 $cachekey = 'feed:feed:' . $owner_nick . ':' . $filter . ':' . $last_update;
929 // Display events in the users's timezone
930 if (strlen($owner['timezone'])) {
931 DI::app()->setTimeZone($owner['timezone']);
934 $previous_created = $last_update;
936 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
937 if ((time() - strtotime($owner['last-item'])) < 15*60) {
938 $result = DI::cache()->get($cachekey);
939 if (!$nocache && !is_null($result)) {
940 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
941 return $result['feed'];
945 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
946 $authorid = Contact::getIdForURL($owner['url']);
948 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
949 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
950 $owner['uid'], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
951 Item::PRIVATE, Protocol::ACTIVITYPUB,
952 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
954 if ($filter === 'comments') {
955 $condition[0] .= " AND `gravity` = ? ";
956 $condition[] = GRAVITY_COMMENT;
959 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
960 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
961 $condition[] = $owner['id'];
962 $condition[] = $authorid;
965 $params = ['order' => ['received' => true], 'limit' => $max_items];
967 if ($filter === 'posts') {
968 $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
970 $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
973 $items = Post::toArray($ret);
975 $doc = new DOMDocument('1.0', 'utf-8');
976 $doc->formatOutput = true;
978 $root = self::addHeader($doc, $owner, $filter);
980 foreach ($items as $item) {
981 $entry = self::noteEntry($doc, $item, $owner);
982 $root->appendChild($entry);
984 if ($last_update < $item['created']) {
985 $last_update = $item['created'];
989 $feeddata = trim($doc->saveXML());
991 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
992 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
994 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
1000 * Adds the header elements to the XML document
1002 * @param DOMDocument $doc XML document
1003 * @param array $owner Contact data of the poster
1004 * @param string $filter The related feed filter (activity, posts or comments)
1006 * @return DOMElement Header root element
1007 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1009 private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1011 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1012 $doc->appendChild($root);
1015 $selfUri = '/feed/' . $owner['nick'] . '/';
1018 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1019 $selfUri .= $filter;
1022 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1025 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1026 $selfUri .= $filter;
1030 $attributes = ['uri' => 'https://friendi.ca', 'version' => FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION];
1031 XML::addElement($doc, $root, 'generator', FRIENDICA_PLATFORM, $attributes);
1032 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1033 XML::addElement($doc, $root, 'title', $title);
1034 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1035 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1036 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1038 $author = self::addAuthor($doc, $owner);
1039 $root->appendChild($author);
1041 $attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
1042 XML::addElement($doc, $root, 'link', '', $attributes);
1044 OStatus::addHubLink($doc, $root, $owner['nick']);
1046 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1047 XML::addElement($doc, $root, 'link', '', $attributes);
1053 * Adds the author element to the XML document
1055 * @param DOMDocument $doc XML document
1056 * @param array $owner Contact data of the poster
1057 * @return DOMElement author element
1058 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1060 private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
1062 $author = $doc->createElement('author');
1063 XML::addElement($doc, $author, 'uri', $owner['url']);
1064 XML::addElement($doc, $author, 'name', $owner['nick']);
1065 XML::addElement($doc, $author, 'email', $owner['addr']);
1071 * Adds a regular entry element
1073 * @param DOMDocument $doc XML document
1074 * @param array $item Data of the item that is to be posted
1075 * @param array $owner Contact data of the poster
1076 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1077 * @return DOMElement Entry element
1078 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1079 * @throws \ImagickException
1081 private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
1083 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1084 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
1087 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1089 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1091 self::entryFooter($doc, $entry, $item, $owner);
1097 * Adds elements to the XML document
1099 * @param DOMDocument $doc XML document
1100 * @param \DOMElement $entry Entry element where the content is added
1101 * @param array $item Data of the item that is to be posted
1102 * @param array $owner Contact data of the poster
1103 * @param string $title Title for the post
1104 * @param string $verb The activity verb
1105 * @param bool $complete Add the "status_net" element?
1107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1109 private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
1112 $verb = OStatus::constructVerb($item);
1115 XML::addElement($doc, $entry, 'id', $item['uri']);
1116 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1118 $body = OStatus::formatPicturePost($item['body'], $item['uri-id']);
1120 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1122 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1124 XML::addElement($doc, $entry, 'link', '', ['rel' => 'alternate', 'type' => 'text/html',
1125 'href' => DI::baseUrl() . '/display/' . $item['guid']]
1128 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1129 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1133 * Adds the elements at the foot of an entry to the XML document
1135 * @param DOMDocument $doc XML document
1136 * @param object $entry The entry element where the elements are added
1137 * @param array $item Data of the item that is to be posted
1138 * @param array $owner Contact data of the poster
1139 * @param bool $complete default true
1141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1143 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1147 if ($item['gravity'] != GRAVITY_PARENT) {
1148 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1150 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1152 if (DBA::isResult($thrparent)) {
1153 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1154 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1155 $parent_plink = $thrparent['plink'];
1156 } elseif (DBA::isResult($parent)) {
1157 $mentioned[$parent['author-link']] = $parent['author-link'];
1158 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1159 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1161 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1164 if (isset($parent_plink)) {
1166 'ref' => $item['thr-parent'],
1167 'href' => $parent_plink];
1168 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1172 'href' => $parent_plink];
1173 XML::addElement($doc, $entry, 'link', '', $attributes);
1177 // uri-id isn't present for follow entry pseudo-items
1178 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1179 foreach ($tags as $tag) {
1180 $mentioned[$tag['url']] = $tag['url'];
1183 foreach ($tags as $tag) {
1184 if ($tag['type'] == Tag::HASHTAG) {
1185 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1189 OStatus::getAttachment($doc, $entry, $item);
1193 * Fetch or create title for feed entry
1195 * @param array $item
1196 * @return string title
1198 private static function getTitle(array $item): string
1200 if ($item['title'] != '') {
1201 return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1204 // Fetch information about the post
1205 $siteinfo = BBCode::getAttachedData($item['body']);
1206 if (isset($siteinfo['title'])) {
1207 return $siteinfo['title'];
1210 // If no bookmark is found then take the first line
1211 // Remove the share element before fetching the first line
1212 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
1214 $title = BBCode::toPlaintext($title)."\n";
1215 $pos = strpos($title, "\n");
1217 if (($pos == 0) || ($pos > 100)) {
1222 return substr($title, 0, $pos) . $trailer;