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\Contact\LocalRelationship\Entity\LocalRelationship;
29 use Friendica\Content\PageInfo;
30 use Friendica\Content\Text\BBCode;
31 use Friendica\Content\Text\HTML;
32 use Friendica\Core\Cache\Enum\Duration;
33 use Friendica\Core\Logger;
34 use Friendica\Core\Protocol;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Conversation;
40 use Friendica\Model\Item;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Network\HTTPException;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Network;
47 use Friendica\Util\ParseUrl;
48 use Friendica\Util\Proxy;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
51 use GuzzleHttp\Exception\TransferException;
54 * This class contain functions to import feeds (RSS/RDF/Atom)
59 * Read a RSS/RDF/Atom feed and create an item entry for it
61 * @param string $xml The feed data
62 * @param array $importer The user record of the importer
63 * @param array $contact The contact record of the feed
65 * @return array Returns the header and the first item in dry run mode
66 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
68 public static function import(string $xml, array $importer = [], array $contact = []): array
70 $dryRun = empty($importer) && empty($contact);
73 Logger::info("Test Atom/RSS feed");
75 Logger::info('Import Atom/RSS feed "' . $contact['name'] . '" (Contact ' . $contact['id'] . ') for user ' . $importer['uid']);
81 Logger::info('XML is empty.');
85 if (!empty($contact['poll'])) {
86 $basepath = $contact['poll'];
87 } elseif (!empty($contact['url'])) {
88 $basepath = $contact['url'];
93 $doc = new DOMDocument();
95 $xpath = new DOMXPath($doc);
97 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
98 $xpath->registerNamespace('atom03', ActivityNamespace::ATOM03);
99 $xpath->registerNamespace('dc', 'http://purl.org/dc/elements/1.1/');
100 $xpath->registerNamespace('content', 'http://purl.org/rss/1.0/modules/content/');
101 $xpath->registerNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
102 $xpath->registerNamespace('rss', 'http://purl.org/rss/1.0/');
103 $xpath->registerNamespace('media', 'http://search.yahoo.com/mrss/');
104 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
109 $protocol = Conversation::PARCEL_UNKNOWN;
112 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
113 $protocol = Conversation::PARCEL_RDF;
114 $author['author-link'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
115 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
117 if (empty($author['author-name'])) {
118 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
120 $entries = $xpath->query('/rdf:RDF/rss:item');
123 if ($xpath->query('/opml')->length > 0) {
124 $protocol = Conversation::PARCEL_OPML;
125 $author['author-name'] = XML::getFirstNodeValue($xpath, '/opml/head/title/text()');
126 $entries = $xpath->query('/opml/body/outline');
130 if ($xpath->query('/atom:feed')->length > 0) {
131 $protocol = Conversation::PARCEL_ATOM;
132 } elseif ($xpath->query('/atom03:feed')->length > 0) {
133 $protocol = Conversation::PARCEL_ATOM03;
137 if (in_array($protocol, [Conversation::PARCEL_ATOM, Conversation::PARCEL_ATOM03])) {
138 $alternate = XML::getFirstAttributes($xpath, $atomns . ":link[@rel='alternate']");
139 if (is_object($alternate)) {
140 foreach ($alternate as $attribute) {
141 if ($attribute->name == 'href') {
142 $author['author-link'] = $attribute->textContent;
147 if (empty($author['author-link'])) {
148 $self = XML::getFirstAttributes($xpath, $atomns . ":link[@rel='self']");
149 if (is_object($self)) {
150 foreach ($self as $attribute) {
151 if ($attribute->name == 'href') {
152 $author['author-link'] = $attribute->textContent;
158 if (empty($author['author-link'])) {
159 $author['author-link'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':id/text()');
161 $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':logo/text()');
163 $author['author-name'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':title/text()');
165 if (empty($author['author-name'])) {
166 $author['author-name'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':subtitle/text()');
169 if (empty($author['author-name'])) {
170 $author['author-name'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':author/' . $atomns . ':name/text()');
173 $value = XML::getFirstNodeValue($xpath, '' . $atomns . ':author/poco:displayName/text()');
175 $author['author-name'] = $value;
179 $author['author-id'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':author/' . $atomns . ':id/text()');
181 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
182 $value = XML::getFirstNodeValue($xpath, $atomns . ':author/' . $atomns . ':uri/text()');
184 $author['author-link'] = $value;
187 $value = XML::getFirstNodeValue($xpath, $atomns . ':author/poco:preferredUsername/text()');
189 $author['author-nick'] = $value;
192 $value = XML::getFirstNodeValue($xpath, $atomns . ':author/poco:address/poco:formatted/text()');
194 $author['author-location'] = $value;
197 $value = XML::getFirstNodeValue($xpath, $atomns . ':author/poco:note/text()');
199 $author['author-about'] = $value;
202 $avatar = XML::getFirstAttributes($xpath, $atomns . ":author/' . $atomns . ':link[@rel='avatar']");
203 if (is_object($avatar)) {
204 foreach ($avatar as $attribute) {
205 if ($attribute->name == 'href') {
206 $author['author-avatar'] = $attribute->textContent;
212 $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':updated/text()');
214 $author['app'] = XML::getFirstNodeValue($xpath, '/' . $atomns . ':feed/' . $atomns . ':generator/text()');
216 $entries = $xpath->query('/' . $atomns . ':feed/' . $atomns . ':entry');
220 if ($xpath->query('/rss/channel')->length > 0) {
221 $protocol = Conversation::PARCEL_RSS;
222 $author['author-link'] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
224 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
226 if (empty($author['author-name'])) {
227 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
230 if (empty($author['author-name'])) {
231 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
234 $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
236 if (empty($author['author-avatar'])) {
237 $avatar = XML::getFirstAttributes($xpath, '/rss/channel/itunes:image');
238 if (is_object($avatar)) {
239 foreach ($avatar as $attribute) {
240 if ($attribute->name == 'href') {
241 $author['author-avatar'] = $attribute->textContent;
247 $author['author-about'] = HTML::toBBCode(XML::getFirstNodeValue($xpath, '/rss/channel/description/text()'), $basepath);
249 if (empty($author['author-about'])) {
250 $author['author-about'] = XML::getFirstNodeValue($xpath, '/rss/channel/itunes:summary/text()');
253 $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
255 $author['app'] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
257 $entries = $xpath->query('/rss/channel/item');
261 $author['author-link'] = $contact['url'];
263 if (empty($author['author-name'])) {
264 $author['author-name'] = $contact['name'];
267 $author['author-avatar'] = $contact['thumb'];
269 $author['owner-link'] = $contact['url'];
270 $author['owner-name'] = $contact['name'];
271 $author['owner-avatar'] = $contact['thumb'];
275 'uid' => $importer['uid'] ?? 0,
276 'network' => Protocol::FEED,
279 'gravity' => Item::GRAVITY_PARENT,
280 'private' => Item::PUBLIC,
281 'verb' => Activity::POST,
282 'object-type' => Activity\ObjectType::NOTE,
283 'post-type' => Item::PT_ARTICLE,
284 'contact-id' => $contact['id'] ?? 0,
287 $datarray['protocol'] = $protocol;
288 $datarray['direction'] = Conversation::PULL;
290 if (!is_object($entries)) {
291 Logger::info("There are no entries in this feed.");
296 $creation_dates = [];
298 // Limit the number of items that are about to be fetched
299 $total_items = ($entries->length - 1);
300 $max_items = DI::config()->get('system', 'max_feed_items');
301 if (($max_items > 0) && ($total_items > $max_items)) {
302 $total_items = $max_items;
307 // Importing older entries first
308 for ($i = $total_items; $i >= 0; --$i) {
309 $entry = $entries->item($i);
311 $item = array_merge($header, $author);
314 $alternate = XML::getFirstAttributes($xpath, $atomns . ":link[@rel='alternate']", $entry);
315 if (!is_object($alternate)) {
316 $alternate = XML::getFirstAttributes($xpath, $atomns . ':link', $entry);
318 if (is_object($alternate)) {
319 foreach ($alternate as $attribute) {
320 if ($attribute->name == 'href') {
321 $item['plink'] = $attribute->textContent;
326 if ($entry->nodeName == 'outline') {
330 foreach ($entry->attributes as $attribute) {
331 switch ($attribute->nodeName) {
333 $item['title'] = $attribute->nodeValue;
337 $body = $attribute->nodeValue;
341 $plink = $attribute->nodeValue;
345 $uri = $attribute->nodeValue;
349 $isrss = $attribute->nodeValue == 'rss';
353 $item['plink'] = $plink ?: $uri;
354 $item['uri'] = $uri ?: $plink;
355 if (!$isrss || empty($item['uri'])) {
360 if (empty($item['plink'])) {
361 $item['plink'] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
364 if (empty($item['plink'])) {
365 $item['plink'] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
368 // Add the base path if missing
369 $item['plink'] = Network::addBasePath($item['plink'], $basepath);
371 if (empty($item['uri'])) {
372 $item['uri'] = XML::getFirstNodeValue($xpath, $atomns . ':id/text()', $entry);
375 $guid = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
377 $item['uri'] = $guid;
379 // Don't use the GUID value directly but instead use it as a basis for the GUID
380 $item['guid'] = Item::guidFromUri($guid, parse_url($guid, PHP_URL_HOST) ?? parse_url($item['plink'], PHP_URL_HOST));
383 if (empty($item['uri'])) {
384 $item['uri'] = $item['plink'];
387 $orig_plink = $item['plink'];
390 $item['plink'] = DI::httpClient()->finalUrl($item['plink']);
391 } catch (TransferException $exception) {
392 Logger::notice('Item URL couldn\'t get expanded', ['url' => $item['plink'], 'exception' => $exception]);
395 if (empty($item['title'])) {
396 $item['title'] = XML::getFirstNodeValue($xpath, $atomns . ':title/text()', $entry);
399 if (empty($item['title'])) {
400 $item['title'] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
403 if (empty($item['title'])) {
404 $item['title'] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
407 if (empty($item['title'])) {
408 $item['title'] = XML::getFirstNodeValue($xpath, 'itunes:title/text()', $entry);
411 $item['title'] = html_entity_decode($item['title'], ENT_QUOTES, 'UTF-8');
413 $published = XML::getFirstNodeValue($xpath, $atomns . ':published/text()', $entry);
415 if (empty($published)) {
416 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
419 if (empty($published)) {
420 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
423 $updated = XML::getFirstNodeValue($xpath, $atomns . ':updated/text()', $entry);
425 if (empty($updated) && !empty($published)) {
426 $updated = $published;
429 if (empty($published) && !empty($updated)) {
430 $published = $updated;
433 if ($published != '') {
434 $item['created'] = trim($published);
437 if ($updated != '') {
438 $item['edited'] = trim($updated);
443 "`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
444 $importer['uid'], $item['uri'], Protocol::FEED, Protocol::DFRN
446 $previous = Post::selectFirst(['id', 'created'], $condition);
447 if (DBA::isResult($previous)) {
448 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
449 $creation_dates[] = $previous['created'];
450 Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']);
453 $creation_dates[] = DateTimeFormat::utc($item['created']);
456 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
458 if (empty($creator)) {
459 $creator = XML::getFirstNodeValue($xpath, $atomns . ':author/' . $atomns . ':name/text()', $entry);
462 if (empty($creator)) {
463 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
466 if ($creator != '') {
467 $item['author-name'] = $creator;
470 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
472 if ($creator != '') {
473 $item['author-name'] = $creator;
477 // <category>Ausland</category>
478 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
482 $enclosures = $xpath->query("enclosure|$atomns:link[@rel='enclosure']", $entry);
483 if (!empty($enclosures)) {
484 foreach ($enclosures as $enclosure) {
489 foreach ($enclosure->attributes as $attribute) {
490 if (in_array($attribute->name, ['url', 'href'])) {
491 $href = $attribute->textContent;
492 } elseif ($attribute->name == 'length') {
493 $length = (int)$attribute->textContent;
494 } elseif ($attribute->name == 'type') {
495 $type = $attribute->textContent;
500 $attachment = ['uri-id' => -1, 'type' => Post\Media::UNKNOWN, 'url' => $href, 'mimetype' => $type, 'size' => $length];
502 $attachment = Post\Media::fetchAdditionalData($attachment);
504 // By now we separate the visible media types (audio, video, image) from the rest
505 // In the future we should try to avoid the DOCUMENT type and only use the real one - but not in the RC phase.
506 if (!in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO])) {
507 $attachment['type'] = Post\Media::DOCUMENT;
509 $attachments[] = $attachment;
515 $categories = $xpath->query('category', $entry);
516 foreach ($categories as $category) {
517 $taglist[] = $category->nodeValue;
521 $body = trim(XML::getFirstNodeValue($xpath, $atomns . ':content/text()', $entry));
525 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
528 $summary = trim(XML::getFirstNodeValue($xpath, $atomns . ':summary/text()', $entry));
530 if (empty($summary)) {
531 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
539 if ($body == $summary) {
543 // remove the content of the title if it is identically to the body
544 // This helps with auto generated titles e.g. from tumblr
545 if (self::titleIsBody($item['title'], $body)) {
548 $item['body'] = HTML::toBBCode($body, $basepath);
550 // Remove tracking pixels
551 $item['body'] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item['body']);
553 if (($item['body'] == '') && ($item['title'] != '')) {
554 $item['body'] = $item['title'];
559 $item['attachments'] = $attachments;
562 } elseif (!Item::isValid($item)) {
563 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
565 } elseif (Item::isTooOld($item)) {
566 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
570 $fetch_further_information = $contact['fetch_further_information'] ?? LocalRelationship::FFI_NONE;
573 if (in_array($fetch_further_information, [LocalRelationship::FFI_INFORMATION, LocalRelationship::FFI_BOTH])) {
574 // Handle enclosures and treat them as preview picture
575 foreach ($attachments as $attachment) {
576 if ($attachment['mimetype'] == 'image/jpeg') {
577 $preview = $attachment['url'];
581 // Remove a possible link to the item itself
582 $item['body'] = str_replace($item['plink'], '', $item['body']);
583 $item['body'] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item['body']));
585 // Replace the content when the title is longer than the body
586 $replace = (strlen($item['title']) > strlen($item['body']));
588 // Replace it, when there is an image in the body
589 if (strstr($item['body'], '[/img]')) {
593 // Replace it, when there is a link in the body
594 if (strstr($item['body'], '[/url]')) {
598 $saved_body = $item['body'];
599 $saved_title = $item['title'];
602 $item['body'] = trim($item['title']);
605 $data = ParseUrl::getSiteinfoCached($item['plink']);
606 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
607 // When the fetched page info text is longer than the body, we do try to enhance the body
608 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
609 // The body is not part of the fetched page info title or page info text. So we add the text to the body
610 $item['body'] .= "\n\n" . $data['text'];
612 // Else we replace the body with the page info text
613 $item['body'] = $data['text'];
617 $data = PageInfo::queryUrl(
620 $fetch_further_information == LocalRelationship::FFI_BOTH,
621 $contact['ffi_keyword_denylist'] ?? ''
625 // Take the data that was provided by the feed if the query is empty
626 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
627 $data['title'] = $saved_title;
628 $item['body'] = $saved_body;
631 $data_text = strip_tags(trim($data['text'] ?? ''));
632 $item_body = strip_tags(trim($item['body'] ?? ''));
634 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
638 // We always strip the title since it will be added in the page information
640 $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false);
641 $taglist = $fetch_further_information == LocalRelationship::FFI_BOTH ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : [];
642 $item['object-type'] = Activity\ObjectType::BOOKMARK;
645 foreach (['audio', 'video'] as $elementname) {
646 if (!empty($data[$elementname])) {
647 foreach ($data[$elementname] as $element) {
648 if (!empty($element['src'])) {
649 $src = $element['src'];
650 } elseif (!empty($element['content'])) {
651 $src = $element['content'];
657 'type' => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
659 'preview' => $element['image'] ?? null,
660 'mimetype' => $element['contenttype'] ?? null,
661 'name' => $element['name'] ?? null,
662 'description' => $element['description'] ?? null,
669 if (!empty($summary)) {
670 $item['body'] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item['body'];
673 if ($fetch_further_information == LocalRelationship::FFI_KEYWORD) {
674 if (empty($taglist)) {
675 $taglist = PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '');
677 $item['body'] .= "\n" . self::tagToString($taglist);
682 // Add the link to the original feed entry if not present in feed
683 if (($item['plink'] != '') && !strstr($item['body'], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
684 $item['body'] .= '[hr][url]' . $item['plink'] . '[/url]';
688 if (empty($item['title'])) {
689 $item['post-type'] = Item::PT_NOTE;
692 Logger::info('Stored feed', ['item' => $item]);
694 $notify = Item::isRemoteSelf($contact, $item);
695 $item['wall'] = (bool)$notify;
697 // Distributed items should have a well-formatted URI.
698 // Additionally, we have to avoid conflicts with identical URI between imported feeds and these items.
700 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHost());
701 $item['uri'] = Item::newURI($item['guid']);
702 unset($item['plink']);
703 unset($item['thr-parent']);
704 unset($item['parent-uri']);
706 // Set the delivery priority for "remote self" to "medium"
707 $notify = Worker::PRIORITY_MEDIUM;
710 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
711 if (!Post::exists($condition) && !Post\Delayed::exists($item['uri'], $item['uid'])) {
713 Post\Delayed::publish($item, $notify, $taglist, $attachments);
716 'item' => $item, 'notify' => $notify,
717 'taglist' => $taglist, 'attachments' => $attachments
721 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]);
725 if (!empty($postings)) {
726 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
727 $total = count($postings);
729 // Posts shouldn't be delayed more than a day
730 $interval = min(1440, self::getPollInterval($contact));
731 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
732 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
739 foreach ($postings as $posting) {
741 $publish_time = time() + $post_delay;
742 $post_delay += $delay;
744 $publish_time = time();
747 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
748 $next_publish = max($last_publish + (60 * $min_posting), time());
749 if ($publish_time < $next_publish) {
750 $publish_time = $next_publish;
752 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
754 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
755 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
760 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
761 self::adjustPollFrequency($contact, $creation_dates);
764 return ['header' => $author, 'items' => $items];
768 * Automatically adjust the poll frequency according to the post frequency
770 * @param array $contact Contact array
771 * @param array $creation_dates
774 private static function adjustPollFrequency(array $contact, array $creation_dates)
776 if ($contact['network'] != Protocol::FEED) {
777 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
781 if (!empty($creation_dates)) {
782 // Count the post frequency and the earliest and latest post date
786 $oldest_date = $newest_date = '';
788 foreach ($creation_dates as $date) {
789 $timestamp = strtotime($date);
790 $day = intdiv($timestamp, 86400);
791 $hour = $timestamp % 86400;
793 // Only have a look at values from the last seven days
794 if (((time() / 86400) - $day) < 7) {
795 if (empty($frequency[$day])) {
796 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
798 ++$frequency[$day]['count'];
799 if ($frequency[$day]['low'] > $hour) {
800 $frequency[$day]['low'] = $hour;
802 if ($frequency[$day]['high'] < $hour) {
803 $frequency[$day]['high'] = $hour;
807 if ($oldest > $day) {
809 $oldest_date = $date;
812 if ($newest < $day) {
814 $newest_date = $date;
818 if (count($creation_dates) == 1) {
819 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
820 $priority = 8; // Poll once a day
823 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
824 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']]);
825 $priority = 10; // Poll every month
828 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
829 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']]);
830 $priority = 9; // Poll every week
833 if (empty($priority) && empty($frequency)) {
834 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']]);
835 $priority = 8; // Poll once a day
838 if (empty($priority)) {
839 // Calculate the highest "posts per day" value
841 foreach ($frequency as $entry) {
842 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
846 // We take the earliest and latest post day and interpolate the number of post per day
847 // that would had been created with this post frequency
849 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
850 $duration = max($entry['high'] - $entry['low'], 14400);
851 $ppd = (86400 / $duration) * $entry['count'];
857 $priority = 1; // Poll every quarter hour
858 } elseif ($max > 24) {
859 $priority = 2; // Poll half an hour
860 } elseif ($max > 12) {
861 $priority = 3; // Poll hourly
862 } elseif ($max > 8) {
863 $priority = 4; // Poll every two hours
864 } elseif ($max > 4) {
865 $priority = 5; // Poll every three hours
866 } elseif ($max > 2) {
867 $priority = 6; // Poll every six hours
869 $priority = 7; // Poll twice a day
871 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
874 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
875 $priority = 8; // Poll once a day
878 if ($contact['rating'] != $priority) {
879 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
880 Contact::update(['rating' => $priority], ['id' => $contact['id']]);
885 * Get the poll interval for the given contact array
887 * @param array $contact
888 * @return int Poll interval in minutes
890 public static function getPollInterval(array $contact): int
892 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
893 $ratings = [0, 3, 7, 8, 9, 10];
894 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
895 $rating = $contact['rating'];
896 } elseif (array_key_exists($contact['priority'], $ratings)) {
897 $rating = $ratings[$contact['priority']];
902 // Check once a week per default for all other networks
906 // Friendica and OStatus are checked once a day
907 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
911 // Check archived contacts or contacts with unsupported protocols once a month
912 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
920 * Based on $contact['priority'], should we poll this site now? Or later?
923 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
925 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720, 1440, 10080, 43200];
927 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
928 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
930 return $poll_intervals[$rating];
934 * Convert a tag array to a tag string
937 * @return string tag string
939 private static function tagToString(array $tags): string
943 foreach ($tags as $tag) {
948 $tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
954 private static function titleIsBody(string $title, string $body): bool
956 $title = strip_tags($title);
957 $title = trim($title);
958 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
959 $title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
961 $body = strip_tags($body);
963 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
964 $body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
966 if (strlen($title) < strlen($body)) {
967 $body = substr($body, 0, strlen($title));
970 if (($title != $body) && (substr($title, -3) == '...')) {
971 $pos = strrpos($title, '...');
973 $title = substr($title, 0, $pos);
974 $body = substr($body, 0, $pos);
977 return ($title == $body);
981 * Creates the Atom feed for a given nickname
984 * - activity (default): all the public posts
985 * - posts: all the public top-level posts
986 * - comments: all the public replies
988 * Updates the provided last_update parameter if the result comes from the
989 * cache or it is empty
991 * @param array $owner owner-view record of the feed owner
992 * @param string $last_update Date of the last update
993 * @param integer $max_items Number of maximum items to fetch
994 * @param string $filter Feed items filter (activity, posts or comments)
995 * @param boolean $nocache Wether to bypass caching
997 * @return string Atom feed
998 * @throws HTTPException\InternalServerErrorException
999 * @throws \ImagickException
1001 public static function atom(array $owner, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
1003 $stamp = microtime(true);
1005 $cachekey = 'feed:feed:' . $owner['nickname'] . ':' . $filter . ':' . $last_update;
1007 // Display events in the user's timezone
1008 if (strlen($owner['timezone'])) {
1009 DI::app()->setTimeZone($owner['timezone']);
1012 $previous_created = $last_update;
1014 // Don't cache when the last item was posted less than 15 minutes ago (Cache duration)
1015 if ((time() - strtotime($owner['last-item'])) < 15 * 60) {
1016 $result = DI::cache()->get($cachekey);
1017 if (!$nocache && !is_null($result)) {
1018 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
1019 return $result['feed'];
1023 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
1024 $authorid = Contact::getIdForURL($owner['url']);
1027 "`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
1028 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
1029 $owner['uid'], $check_date, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT,
1030 Item::PRIVATE, Protocol::ACTIVITYPUB,
1031 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA
1034 if ($filter === 'comments') {
1035 $condition[0] .= " AND `gravity` = ? ";
1036 $condition[] = Item::GRAVITY_COMMENT;
1039 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1040 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
1041 $condition[] = $owner['id'];
1042 $condition[] = $authorid;
1045 $params = ['order' => ['received' => true], 'limit' => $max_items];
1047 if ($filter === 'posts') {
1048 $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
1050 $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
1053 $items = Post::toArray($ret);
1055 $doc = new DOMDocument('1.0', 'utf-8');
1056 $doc->formatOutput = true;
1058 $root = self::addHeader($doc, $owner, $filter);
1060 foreach ($items as $item) {
1061 $entry = self::noteEntry($doc, $item, $owner);
1062 $root->appendChild($entry);
1064 if ($last_update < $item['created']) {
1065 $last_update = $item['created'];
1069 $feeddata = trim($doc->saveXML());
1071 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
1072 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1074 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
1080 * Adds the header elements to the XML document
1082 * @param DOMDocument $doc XML document
1083 * @param array $owner Contact data of the poster
1084 * @param string $filter The related feed filter (activity, posts or comments)
1086 * @return DOMElement Header root element
1087 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1089 private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1091 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1092 $doc->appendChild($root);
1095 $selfUri = '/feed/' . $owner['nick'] . '/';
1098 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1099 $selfUri .= $filter;
1102 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1105 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1106 $selfUri .= $filter;
1110 $attributes = ['uri' => 'https://friendi.ca', 'version' => App::VERSION . '-' . DB_UPDATE_VERSION];
1111 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1112 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1113 XML::addElement($doc, $root, 'title', $title);
1114 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1115 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1116 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1118 $author = self::addAuthor($doc, $owner);
1119 $root->appendChild($author);
1121 $attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
1122 XML::addElement($doc, $root, 'link', '', $attributes);
1124 OStatus::addHubLink($doc, $root, $owner['nick']);
1126 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1127 XML::addElement($doc, $root, 'link', '', $attributes);
1133 * Adds the author element to the XML document
1135 * @param DOMDocument $doc XML document
1136 * @param array $owner Contact data of the poster
1137 * @return DOMElement author element
1138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1140 private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
1142 $author = $doc->createElement('author');
1143 XML::addElement($doc, $author, 'uri', $owner['url']);
1144 XML::addElement($doc, $author, 'name', $owner['nick']);
1145 XML::addElement($doc, $author, 'email', $owner['addr']);
1151 * Adds a regular entry element
1153 * @param DOMDocument $doc XML document
1154 * @param array $item Data of the item that is to be posted
1155 * @param array $owner Contact data of the poster
1156 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1157 * @return DOMElement Entry element
1158 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1159 * @throws \ImagickException
1161 private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
1163 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1164 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
1167 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1169 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1171 self::entryFooter($doc, $entry, $item, $owner);
1177 * Adds elements to the XML document
1179 * @param DOMDocument $doc XML document
1180 * @param \DOMElement $entry Entry element where the content is added
1181 * @param array $item Data of the item that is to be posted
1182 * @param array $owner Contact data of the poster
1183 * @param string $title Title for the post
1184 * @param string $verb The activity verb
1185 * @param bool $complete Add the "status_net" element?
1187 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1189 private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
1192 $verb = OStatus::constructVerb($item);
1195 XML::addElement($doc, $entry, 'id', $item['uri']);
1196 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1198 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
1199 $body = Post\Media::addHTMLLinkToBody($item['uri-id'], $body);
1201 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1203 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1211 'rel' => 'alternate', 'type' => 'text/html',
1212 'href' => DI::baseUrl() . '/display/' . $item['guid']
1216 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1217 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1221 * Adds the elements at the foot of an entry to the XML document
1223 * @param DOMDocument $doc XML document
1224 * @param object $entry The entry element where the elements are added
1225 * @param array $item Data of the item that is to be posted
1226 * @param array $owner Contact data of the poster
1227 * @param bool $complete default true
1229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1231 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1235 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1236 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1238 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1240 if (DBA::isResult($thrparent)) {
1241 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1242 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1243 $parent_plink = $thrparent['plink'];
1244 } elseif (DBA::isResult($parent)) {
1245 $mentioned[$parent['author-link']] = $parent['author-link'];
1246 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1247 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1249 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1252 if (isset($parent_plink)) {
1254 'ref' => $item['thr-parent'],
1255 'href' => $parent_plink
1257 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1261 'href' => $parent_plink
1263 XML::addElement($doc, $entry, 'link', '', $attributes);
1267 // uri-id isn't present for follow entry pseudo-items
1268 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1269 foreach ($tags as $tag) {
1270 $mentioned[$tag['url']] = $tag['url'];
1273 foreach ($tags as $tag) {
1274 if ($tag['type'] == Tag::HASHTAG) {
1275 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1279 OStatus::getAttachment($doc, $entry, $item);
1283 * Fetch or create title for feed entry
1285 * @param array $item
1286 * @return string title
1288 private static function getTitle(array $item): string
1290 if ($item['title'] != '') {
1291 return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1294 // Fetch information about the post
1295 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1296 if (!empty($media) && !empty($media[0]['name']) && ($media[0]['name'] != $media[0]['url'])) {
1297 return $media[0]['name'];
1300 // If no bookmark is found then take the first line
1301 // Remove the share element before fetching the first line
1302 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
1304 $title = BBCode::toPlaintext($title) . "\n";
1305 $pos = strpos($title, "\n");
1307 if (($pos == 0) || ($pos > 100)) {
1312 return substr($title, 0, $pos) . $trailer;