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 if (strpos($xml, ActivityNamespace::ATOM03) && !strpos($xml, ActivityNamespace::ATOM1)) {
97 $xpath->registerNamespace('atom', ActivityNamespace::ATOM03);
99 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
101 $xpath->registerNamespace('dc', 'http://purl.org/dc/elements/1.1/');
102 $xpath->registerNamespace('content', 'http://purl.org/rss/1.0/modules/content/');
103 $xpath->registerNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
104 $xpath->registerNamespace('rss', 'http://purl.org/rss/1.0/');
105 $xpath->registerNamespace('media', 'http://search.yahoo.com/mrss/');
106 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
110 $protocol = Conversation::PARCEL_UNKNOWN;
113 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
114 $protocol = Conversation::PARCEL_RDF;
115 $author['author-link'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
116 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
118 if (empty($author['author-name'])) {
119 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
121 $entries = $xpath->query('/rdf:RDF/rss:item');
125 if ($xpath->query('/atom:feed')->length > 0) {
126 $protocol = Conversation::PARCEL_ATOM;
127 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
128 if (is_object($alternate)) {
129 foreach ($alternate as $attribute) {
130 if ($attribute->name == 'href') {
131 $author['author-link'] = $attribute->textContent;
136 if (empty($author['author-link'])) {
137 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
138 if (is_object($self)) {
139 foreach ($self as $attribute) {
140 if ($attribute->name == 'href') {
141 $author['author-link'] = $attribute->textContent;
147 if (empty($author['author-link'])) {
148 $author['author-link'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
150 $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
152 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
154 if (empty($author['author-name'])) {
155 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
158 if (empty($author['author-name'])) {
159 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
162 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
164 $author['author-name'] = $value;
168 $author['author-id'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
170 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
171 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
173 $author['author-link'] = $value;
176 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
178 $author['author-nick'] = $value;
181 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
183 $author['author-location'] = $value;
186 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
188 $author['author-about'] = $value;
191 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
192 if (is_object($avatar)) {
193 foreach ($avatar as $attribute) {
194 if ($attribute->name == 'href') {
195 $author['author-avatar'] = $attribute->textContent;
201 $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
203 $author['app'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
205 $entries = $xpath->query('/atom:feed/atom:entry');
209 if ($xpath->query('/rss/channel')->length > 0) {
210 $protocol = Conversation::PARCEL_RSS;
211 $author['author-link'] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
213 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
215 if (empty($author['author-name'])) {
216 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
219 if (empty($author['author-name'])) {
220 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
223 $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
225 if (empty($author['author-avatar'])) {
226 $avatar = XML::getFirstAttributes($xpath, '/rss/channel/itunes:image');
227 if (is_object($avatar)) {
228 foreach ($avatar as $attribute) {
229 if ($attribute->name == 'href') {
230 $author['author-avatar'] = $attribute->textContent;
236 $author['author-about'] = HTML::toBBCode(XML::getFirstNodeValue($xpath, '/rss/channel/description/text()'), $basepath);
238 if (empty($author['author-about'])) {
239 $author['author-about'] = XML::getFirstNodeValue($xpath, '/rss/channel/itunes:summary/text()');
242 $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
244 $author['app'] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
246 $entries = $xpath->query('/rss/channel/item');
250 $author['author-link'] = $contact['url'];
252 if (empty($author['author-name'])) {
253 $author['author-name'] = $contact['name'];
256 $author['author-avatar'] = $contact['thumb'];
258 $author['owner-link'] = $contact['url'];
259 $author['owner-name'] = $contact['name'];
260 $author['owner-avatar'] = $contact['thumb'];
264 'uid' => $importer['uid'] ?? 0,
265 'network' => Protocol::FEED,
268 'gravity' => Item::GRAVITY_PARENT,
269 'private' => Item::PUBLIC,
270 'verb' => Activity::POST,
271 'object-type' => Activity\ObjectType::NOTE,
272 'post-type' => Item::PT_ARTICLE,
273 'contact-id' => $contact['id'] ?? 0,
276 $datarray['protocol'] = $protocol;
277 $datarray['direction'] = Conversation::PULL;
279 if (!is_object($entries)) {
280 Logger::info("There are no entries in this feed.");
285 $creation_dates = [];
287 // Limit the number of items that are about to be fetched
288 $total_items = ($entries->length - 1);
289 $max_items = DI::config()->get('system', 'max_feed_items');
290 if (($max_items > 0) && ($total_items > $max_items)) {
291 $total_items = $max_items;
296 // Importing older entries first
297 for ($i = $total_items; $i >= 0; --$i) {
298 $entry = $entries->item($i);
300 $item = array_merge($header, $author);
302 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
303 if (!is_object($alternate)) {
304 $alternate = XML::getFirstAttributes($xpath, 'atom:link', $entry);
306 if (is_object($alternate)) {
307 foreach ($alternate as $attribute) {
308 if ($attribute->name == 'href') {
309 $item['plink'] = $attribute->textContent;
314 if (empty($item['plink'])) {
315 $item['plink'] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
318 if (empty($item['plink'])) {
319 $item['plink'] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
322 // Add the base path if missing
323 $item['plink'] = Network::addBasePath($item['plink'], $basepath);
325 $item['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
327 $guid = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
329 $item['uri'] = $guid;
331 // Don't use the GUID value directly but instead use it as a basis for the GUID
332 $item['guid'] = Item::guidFromUri($guid, parse_url($guid, PHP_URL_HOST) ?? parse_url($item['plink'], PHP_URL_HOST));
335 if (empty($item['uri'])) {
336 $item['uri'] = $item['plink'];
339 $orig_plink = $item['plink'];
342 $item['plink'] = DI::httpClient()->finalUrl($item['plink']);
343 } catch (TransferException $exception) {
344 Logger::notice('Item URL couldn\'t get expanded', ['url' => $item['plink'], 'exception' => $exception]);
347 $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
349 if (empty($item['title'])) {
350 $item['title'] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
353 if (empty($item['title'])) {
354 $item['title'] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
357 if (empty($item['title'])) {
358 $item['title'] = XML::getFirstNodeValue($xpath, 'itunes:title/text()', $entry);
361 $item['title'] = html_entity_decode($item['title'], ENT_QUOTES, 'UTF-8');
363 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
365 if (empty($published)) {
366 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
369 if (empty($published)) {
370 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
373 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
375 if (empty($updated) && !empty($published)) {
376 $updated = $published;
379 if (empty($published) && !empty($updated)) {
380 $published = $updated;
383 if ($published != '') {
384 $item['created'] = trim($published);
387 if ($updated != '') {
388 $item['edited'] = trim($updated);
393 "`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
394 $importer['uid'], $item['uri'], Protocol::FEED, Protocol::DFRN
396 $previous = Post::selectFirst(['id', 'created'], $condition);
397 if (DBA::isResult($previous)) {
398 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
399 $creation_dates[] = $previous['created'];
400 Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']);
403 $creation_dates[] = DateTimeFormat::utc($item['created']);
406 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
408 if (empty($creator)) {
409 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
412 if (empty($creator)) {
413 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
416 if ($creator != '') {
417 $item['author-name'] = $creator;
420 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
422 if ($creator != '') {
423 $item['author-name'] = $creator;
427 // <category>Ausland</category>
428 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
432 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
433 foreach ($enclosures as $enclosure) {
438 foreach ($enclosure->attributes as $attribute) {
439 if (in_array($attribute->name, ['url', 'href'])) {
440 $href = $attribute->textContent;
441 } elseif ($attribute->name == 'length') {
442 $length = (int)$attribute->textContent;
443 } elseif ($attribute->name == 'type') {
444 $type = $attribute->textContent;
449 $attachment = ['uri-id' => -1, 'type' => Post\Media::UNKNOWN, 'url' => $href, 'mimetype' => $type, 'size' => $length];
451 $attachment = Post\Media::fetchAdditionalData($attachment);
453 // By now we separate the visible media types (audio, video, image) from the rest
454 // In the future we should try to avoid the DOCUMENT type and only use the real one - but not in the RC phase.
455 if (!in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO])) {
456 $attachment['type'] = Post\Media::DOCUMENT;
458 $attachments[] = $attachment;
463 $categories = $xpath->query('category', $entry);
464 foreach ($categories as $category) {
465 $taglist[] = $category->nodeValue;
468 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
471 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
474 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
476 if (empty($summary)) {
477 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
485 if ($body == $summary) {
489 // remove the content of the title if it is identically to the body
490 // This helps with auto generated titles e.g. from tumblr
491 if (self::titleIsBody($item['title'], $body)) {
494 $item['body'] = HTML::toBBCode($body, $basepath);
496 // Remove tracking pixels
497 $item['body'] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item['body']);
499 if (($item['body'] == '') && ($item['title'] != '')) {
500 $item['body'] = $item['title'];
505 $item['attachments'] = $attachments;
508 } elseif (!Item::isValid($item)) {
509 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
511 } elseif (Item::isTooOld($item)) {
512 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
517 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] < 3)) {
518 // Handle enclosures and treat them as preview picture
519 foreach ($attachments as $attachment) {
520 if ($attachment['mimetype'] == 'image/jpeg') {
521 $preview = $attachment['url'];
525 // Remove a possible link to the item itself
526 $item['body'] = str_replace($item['plink'], '', $item['body']);
527 $item['body'] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item['body']));
529 // Replace the content when the title is longer than the body
530 $replace = (strlen($item['title']) > strlen($item['body']));
532 // Replace it, when there is an image in the body
533 if (strstr($item['body'], '[/img]')) {
537 // Replace it, when there is a link in the body
538 if (strstr($item['body'], '[/url]')) {
542 $saved_body = $item['body'];
543 $saved_title = $item['title'];
546 $item['body'] = trim($item['title']);
549 $data = ParseUrl::getSiteinfoCached($item['plink']);
550 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
551 // When the fetched page info text is longer than the body, we do try to enhance the body
552 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
553 // The body is not part of the fetched page info title or page info text. So we add the text to the body
554 $item['body'] .= "\n\n" . $data['text'];
556 // Else we replace the body with the page info text
557 $item['body'] = $data['text'];
561 $data = PageInfo::queryUrl($item['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_denylist'] ?? '');
564 // Take the data that was provided by the feed if the query is empty
565 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
566 $data['title'] = $saved_title;
567 $item['body'] = $saved_body;
570 $data_text = strip_tags(trim($data['text'] ?? ''));
571 $item_body = strip_tags(trim($item['body'] ?? ''));
573 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
577 // We always strip the title since it will be added in the page information
579 $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false);
580 $taglist = $contact['fetch_further_information'] == 2 ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : [];
581 $item['object-type'] = Activity\ObjectType::BOOKMARK;
584 foreach (['audio', 'video'] as $elementname) {
585 if (!empty($data[$elementname])) {
586 foreach ($data[$elementname] as $element) {
587 if (!empty($element['src'])) {
588 $src = $element['src'];
589 } elseif (!empty($element['content'])) {
590 $src = $element['content'];
596 'type' => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
598 'preview' => $element['image'] ?? null,
599 'mimetype' => $element['contenttype'] ?? null,
600 'name' => $element['name'] ?? null,
601 'description' => $element['description'] ?? null,
608 if (!empty($summary)) {
609 $item['body'] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item['body'];
612 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] == 3)) {
613 if (empty($taglist)) {
614 $taglist = PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '');
616 $item['body'] .= "\n" . self::tagToString($taglist);
621 // Add the link to the original feed entry if not present in feed
622 if (($item['plink'] != '') && !strstr($item['body'], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
623 $item['body'] .= '[hr][url]' . $item['plink'] . '[/url]';
627 if (empty($item['title'])) {
628 $item['post-type'] = Item::PT_NOTE;
631 Logger::info('Stored feed', ['item' => $item]);
633 $notify = Item::isRemoteSelf($contact, $item);
634 $item['wall'] = (bool)$notify;
636 // Distributed items should have a well-formatted URI.
637 // Additionally, we have to avoid conflicts with identical URI between imported feeds and these items.
639 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHost());
640 $item['uri'] = Item::newURI($item['guid']);
641 unset($item['plink']);
642 unset($item['thr-parent']);
643 unset($item['parent-uri']);
645 // Set the delivery priority for "remote self" to "medium"
646 $notify = Worker::PRIORITY_MEDIUM;
649 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
650 if (!Post::exists($condition) && !Post\Delayed::exists($item['uri'], $item['uid'])) {
652 Post\Delayed::publish($item, $notify, $taglist, $attachments);
655 'item' => $item, 'notify' => $notify,
656 'taglist' => $taglist, 'attachments' => $attachments
660 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]);
664 if (!empty($postings)) {
665 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
666 $total = count($postings);
668 // Posts shouldn't be delayed more than a day
669 $interval = min(1440, self::getPollInterval($contact));
670 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
671 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
678 foreach ($postings as $posting) {
680 $publish_time = time() + $post_delay;
681 $post_delay += $delay;
683 $publish_time = time();
686 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
687 $next_publish = max($last_publish + (60 * $min_posting), time());
688 if ($publish_time < $next_publish) {
689 $publish_time = $next_publish;
691 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
693 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
694 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
699 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
700 self::adjustPollFrequency($contact, $creation_dates);
703 return ['header' => $author, 'items' => $items];
707 * Automatically adjust the poll frequency according to the post frequency
709 * @param array $contact Contact array
710 * @param array $creation_dates
713 private static function adjustPollFrequency(array $contact, array $creation_dates)
715 if ($contact['network'] != Protocol::FEED) {
716 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
720 if (!empty($creation_dates)) {
721 // Count the post frequency and the earliest and latest post date
725 $oldest_date = $newest_date = '';
727 foreach ($creation_dates as $date) {
728 $timestamp = strtotime($date);
729 $day = intdiv($timestamp, 86400);
730 $hour = $timestamp % 86400;
732 // Only have a look at values from the last seven days
733 if (((time() / 86400) - $day) < 7) {
734 if (empty($frequency[$day])) {
735 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
737 ++$frequency[$day]['count'];
738 if ($frequency[$day]['low'] > $hour) {
739 $frequency[$day]['low'] = $hour;
741 if ($frequency[$day]['high'] < $hour) {
742 $frequency[$day]['high'] = $hour;
746 if ($oldest > $day) {
748 $oldest_date = $date;
751 if ($newest < $day) {
753 $newest_date = $date;
757 if (count($creation_dates) == 1) {
758 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
759 $priority = 8; // Poll once a day
762 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
763 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']]);
764 $priority = 10; // Poll every month
767 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
768 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']]);
769 $priority = 9; // Poll every week
772 if (empty($priority) && empty($frequency)) {
773 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']]);
774 $priority = 8; // Poll once a day
777 if (empty($priority)) {
778 // Calculate the highest "posts per day" value
780 foreach ($frequency as $entry) {
781 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
785 // We take the earliest and latest post day and interpolate the number of post per day
786 // that would had been created with this post frequency
788 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
789 $duration = max($entry['high'] - $entry['low'], 14400);
790 $ppd = (86400 / $duration) * $entry['count'];
796 $priority = 1; // Poll every quarter hour
797 } elseif ($max > 24) {
798 $priority = 2; // Poll half an hour
799 } elseif ($max > 12) {
800 $priority = 3; // Poll hourly
801 } elseif ($max > 8) {
802 $priority = 4; // Poll every two hours
803 } elseif ($max > 4) {
804 $priority = 5; // Poll every three hours
805 } elseif ($max > 2) {
806 $priority = 6; // Poll every six hours
808 $priority = 7; // Poll twice a day
810 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
813 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
814 $priority = 8; // Poll once a day
817 if ($contact['rating'] != $priority) {
818 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
819 Contact::update(['rating' => $priority], ['id' => $contact['id']]);
824 * Get the poll interval for the given contact array
826 * @param array $contact
827 * @return int Poll interval in minutes
829 public static function getPollInterval(array $contact): int
831 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
832 $ratings = [0, 3, 7, 8, 9, 10];
833 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
834 $rating = $contact['rating'];
835 } elseif (array_key_exists($contact['priority'], $ratings)) {
836 $rating = $ratings[$contact['priority']];
841 // Check once a week per default for all other networks
845 // Friendica and OStatus are checked once a day
846 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
850 // Check archived contacts or contacts with unsupported protocols once a month
851 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
859 * Based on $contact['priority'], should we poll this site now? Or later?
862 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
864 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720, 1440, 10080, 43200];
866 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
867 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
869 return $poll_intervals[$rating];
873 * Convert a tag array to a tag string
876 * @return string tag string
878 private static function tagToString(array $tags): string
882 foreach ($tags as $tag) {
887 $tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
893 private static function titleIsBody(string $title, string $body): bool
895 $title = strip_tags($title);
896 $title = trim($title);
897 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
898 $title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
900 $body = strip_tags($body);
902 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
903 $body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
905 if (strlen($title) < strlen($body)) {
906 $body = substr($body, 0, strlen($title));
909 if (($title != $body) && (substr($title, -3) == '...')) {
910 $pos = strrpos($title, '...');
912 $title = substr($title, 0, $pos);
913 $body = substr($body, 0, $pos);
916 return ($title == $body);
920 * Creates the Atom feed for a given nickname
923 * - activity (default): all the public posts
924 * - posts: all the public top-level posts
925 * - comments: all the public replies
927 * Updates the provided last_update parameter if the result comes from the
928 * cache or it is empty
930 * @param array $owner owner-view record of the feed owner
931 * @param string $last_update Date of the last update
932 * @param integer $max_items Number of maximum items to fetch
933 * @param string $filter Feed items filter (activity, posts or comments)
934 * @param boolean $nocache Wether to bypass caching
936 * @return string Atom feed
937 * @throws HTTPException\InternalServerErrorException
938 * @throws \ImagickException
940 public static function atom(array $owner, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
942 $stamp = microtime(true);
944 $cachekey = 'feed:feed:' . $owner['nickname'] . ':' . $filter . ':' . $last_update;
946 // Display events in the user's timezone
947 if (strlen($owner['timezone'])) {
948 DI::app()->setTimeZone($owner['timezone']);
951 $previous_created = $last_update;
953 // Don't cache when the last item was posted less than 15 minutes ago (Cache duration)
954 if ((time() - strtotime($owner['last-item'])) < 15 * 60) {
955 $result = DI::cache()->get($cachekey);
956 if (!$nocache && !is_null($result)) {
957 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
958 return $result['feed'];
962 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
963 $authorid = Contact::getIdForURL($owner['url']);
966 "`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
967 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
968 $owner['uid'], $check_date, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT,
969 Item::PRIVATE, Protocol::ACTIVITYPUB,
970 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA
973 if ($filter === 'comments') {
974 $condition[0] .= " AND `gravity` = ? ";
975 $condition[] = Item::GRAVITY_COMMENT;
978 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
979 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
980 $condition[] = $owner['id'];
981 $condition[] = $authorid;
984 $params = ['order' => ['received' => true], 'limit' => $max_items];
986 if ($filter === 'posts') {
987 $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
989 $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
992 $items = Post::toArray($ret);
994 $doc = new DOMDocument('1.0', 'utf-8');
995 $doc->formatOutput = true;
997 $root = self::addHeader($doc, $owner, $filter);
999 foreach ($items as $item) {
1000 $entry = self::noteEntry($doc, $item, $owner);
1001 $root->appendChild($entry);
1003 if ($last_update < $item['created']) {
1004 $last_update = $item['created'];
1008 $feeddata = trim($doc->saveXML());
1010 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
1011 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1013 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
1019 * Adds the header elements to the XML document
1021 * @param DOMDocument $doc XML document
1022 * @param array $owner Contact data of the poster
1023 * @param string $filter The related feed filter (activity, posts or comments)
1025 * @return DOMElement Header root element
1026 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1028 private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1030 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1031 $doc->appendChild($root);
1034 $selfUri = '/feed/' . $owner['nick'] . '/';
1037 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1038 $selfUri .= $filter;
1041 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1044 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1045 $selfUri .= $filter;
1049 $attributes = ['uri' => 'https://friendi.ca', 'version' => App::VERSION . '-' . DB_UPDATE_VERSION];
1050 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1051 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1052 XML::addElement($doc, $root, 'title', $title);
1053 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1054 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1055 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1057 $author = self::addAuthor($doc, $owner);
1058 $root->appendChild($author);
1060 $attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
1061 XML::addElement($doc, $root, 'link', '', $attributes);
1063 OStatus::addHubLink($doc, $root, $owner['nick']);
1065 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1066 XML::addElement($doc, $root, 'link', '', $attributes);
1072 * Adds the author element to the XML document
1074 * @param DOMDocument $doc XML document
1075 * @param array $owner Contact data of the poster
1076 * @return DOMElement author element
1077 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1079 private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
1081 $author = $doc->createElement('author');
1082 XML::addElement($doc, $author, 'uri', $owner['url']);
1083 XML::addElement($doc, $author, 'name', $owner['nick']);
1084 XML::addElement($doc, $author, 'email', $owner['addr']);
1090 * Adds a regular entry element
1092 * @param DOMDocument $doc XML document
1093 * @param array $item Data of the item that is to be posted
1094 * @param array $owner Contact data of the poster
1095 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1096 * @return DOMElement Entry element
1097 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1098 * @throws \ImagickException
1100 private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
1102 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1103 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
1106 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1108 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1110 self::entryFooter($doc, $entry, $item, $owner);
1116 * Adds elements to the XML document
1118 * @param DOMDocument $doc XML document
1119 * @param \DOMElement $entry Entry element where the content is added
1120 * @param array $item Data of the item that is to be posted
1121 * @param array $owner Contact data of the poster
1122 * @param string $title Title for the post
1123 * @param string $verb The activity verb
1124 * @param bool $complete Add the "status_net" element?
1126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1128 private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
1131 $verb = OStatus::constructVerb($item);
1134 XML::addElement($doc, $entry, 'id', $item['uri']);
1135 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1137 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
1138 $body = Post\Media::addHTMLLinkToBody($item['uri-id'], $body);
1140 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1142 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1150 'rel' => 'alternate', 'type' => 'text/html',
1151 'href' => DI::baseUrl() . '/display/' . $item['guid']
1155 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1156 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1160 * Adds the elements at the foot of an entry to the XML document
1162 * @param DOMDocument $doc XML document
1163 * @param object $entry The entry element where the elements are added
1164 * @param array $item Data of the item that is to be posted
1165 * @param array $owner Contact data of the poster
1166 * @param bool $complete default true
1168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1170 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1174 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1175 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1177 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1179 if (DBA::isResult($thrparent)) {
1180 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1181 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1182 $parent_plink = $thrparent['plink'];
1183 } elseif (DBA::isResult($parent)) {
1184 $mentioned[$parent['author-link']] = $parent['author-link'];
1185 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1186 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1188 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1191 if (isset($parent_plink)) {
1193 'ref' => $item['thr-parent'],
1194 'href' => $parent_plink
1196 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1200 'href' => $parent_plink
1202 XML::addElement($doc, $entry, 'link', '', $attributes);
1206 // uri-id isn't present for follow entry pseudo-items
1207 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1208 foreach ($tags as $tag) {
1209 $mentioned[$tag['url']] = $tag['url'];
1212 foreach ($tags as $tag) {
1213 if ($tag['type'] == Tag::HASHTAG) {
1214 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1218 OStatus::getAttachment($doc, $entry, $item);
1222 * Fetch or create title for feed entry
1224 * @param array $item
1225 * @return string title
1227 private static function getTitle(array $item): string
1229 if ($item['title'] != '') {
1230 return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1233 // Fetch information about the post
1234 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1235 if (!empty($media) && !empty($media[0]['name']) && ($media[0]['name'] != $media[0]['url'])) {
1236 return $media[0]['name'];
1239 // If no bookmark is found then take the first line
1240 // Remove the share element before fetching the first line
1241 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
1243 $title = BBCode::toPlaintext($title) . "\n";
1244 $pos = strpos($title, "\n");
1246 if (($pos == 0) || ($pos > 100)) {
1251 return substr($title, 0, $pos) . $trailer;