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;
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\Util\DateTimeFormat;
44 use Friendica\Util\Network;
45 use Friendica\Util\ParseUrl;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
48 use Friendica\Util\XML;
49 use GuzzleHttp\Exception\TransferException;
52 * This class contain functions to import feeds (RSS/RDF/Atom)
57 * Read a RSS/RDF/Atom feed and create an item entry for it
59 * @param string $xml The feed data
60 * @param array $importer The user record of the importer
61 * @param array $contact The contact record of the feed
63 * @return array Returns the header and the first item in dry run mode
64 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
66 public static function import(string $xml, array $importer = [], array $contact = []): array
68 $dryRun = empty($importer) && empty($contact);
71 Logger::info("Test Atom/RSS feed");
73 Logger::info('Import Atom/RSS feed "' . $contact['name'] . '" (Contact ' . $contact['id'] . ') for user ' . $importer['uid']);
79 Logger::info('XML is empty.');
83 if (!empty($contact['poll'])) {
84 $basepath = $contact['poll'];
85 } elseif (!empty($contact['url'])) {
86 $basepath = $contact['url'];
91 $doc = new DOMDocument();
93 $xpath = new DOMXPath($doc);
94 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
95 $xpath->registerNamespace('dc', 'http://purl.org/dc/elements/1.1/');
96 $xpath->registerNamespace('content', 'http://purl.org/rss/1.0/modules/content/');
97 $xpath->registerNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
98 $xpath->registerNamespace('rss', 'http://purl.org/rss/1.0/');
99 $xpath->registerNamespace('media', 'http://search.yahoo.com/mrss/');
100 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
104 $protocol = Conversation::PARCEL_UNKNOWN;
107 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
108 $protocol = Conversation::PARCEL_RDF;
109 $author['author-link'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
110 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
112 if (empty($author['author-name'])) {
113 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
115 $entries = $xpath->query('/rdf:RDF/rss:item');
119 if ($xpath->query('/atom:feed')->length > 0) {
120 $protocol = Conversation::PARCEL_ATOM;
121 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
122 if (is_object($alternate)) {
123 foreach ($alternate as $attribute) {
124 if ($attribute->name == 'href') {
125 $author['author-link'] = $attribute->textContent;
130 if (empty($author['author-link'])) {
131 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
132 if (is_object($self)) {
133 foreach ($self as $attribute) {
134 if ($attribute->name == 'href') {
135 $author['author-link'] = $attribute->textContent;
141 if (empty($author['author-link'])) {
142 $author['author-link'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
144 $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
146 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
148 if (empty($author['author-name'])) {
149 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
152 if (empty($author['author-name'])) {
153 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
156 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
158 $author['author-name'] = $value;
162 $author['author-id'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
164 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
165 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
167 $author['author-link'] = $value;
170 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
172 $author['author-nick'] = $value;
175 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
177 $author['author-location'] = $value;
180 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
182 $author['author-about'] = $value;
185 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
186 if (is_object($avatar)) {
187 foreach ($avatar as $attribute) {
188 if ($attribute->name == 'href') {
189 $author['author-avatar'] = $attribute->textContent;
195 $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
197 $author['app'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
199 $entries = $xpath->query('/atom:feed/atom:entry');
203 if ($xpath->query('/rss/channel')->length > 0) {
204 $protocol = Conversation::PARCEL_RSS;
205 $author['author-link'] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
207 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
209 if (empty($author['author-name'])) {
210 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
213 if (empty($author['author-name'])) {
214 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
217 $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
219 if (empty($author['author-avatar'])) {
220 $avatar = XML::getFirstAttributes($xpath, '/rss/channel/itunes:image');
221 if (is_object($avatar)) {
222 foreach ($avatar as $attribute) {
223 if ($attribute->name == 'href') {
224 $author['author-avatar'] = $attribute->textContent;
230 $author['author-about'] = HTML::toBBCode(XML::getFirstNodeValue($xpath, '/rss/channel/description/text()'), $basepath);
232 if (empty($author['author-about'])) {
233 $author['author-about'] = XML::getFirstNodeValue($xpath, '/rss/channel/itunes:summary/text()');
236 $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
238 $author['app'] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
240 $entries = $xpath->query('/rss/channel/item');
244 $author['author-link'] = $contact['url'];
246 if (empty($author['author-name'])) {
247 $author['author-name'] = $contact['name'];
250 $author['author-avatar'] = $contact['thumb'];
252 $author['owner-link'] = $contact['url'];
253 $author['owner-name'] = $contact['name'];
254 $author['owner-avatar'] = $contact['thumb'];
258 'uid' => $importer['uid'] ?? 0,
259 'network' => Protocol::FEED,
262 'gravity' => Item::GRAVITY_PARENT,
263 'private' => Item::PUBLIC,
264 'verb' => Activity::POST,
265 'object-type' => Activity\ObjectType::NOTE,
266 'post-type' => Item::PT_ARTICLE,
267 'contact-id' => $contact['id'] ?? 0,
270 $datarray['protocol'] = $protocol;
271 $datarray['direction'] = Conversation::PULL;
273 if (!is_object($entries)) {
274 Logger::info("There are no entries in this feed.");
279 $creation_dates = [];
281 // Limit the number of items that are about to be fetched
282 $total_items = ($entries->length - 1);
283 $max_items = DI::config()->get('system', 'max_feed_items');
284 if (($max_items > 0) && ($total_items > $max_items)) {
285 $total_items = $max_items;
290 // Importing older entries first
291 for ($i = $total_items; $i >= 0; --$i) {
292 $entry = $entries->item($i);
294 $item = array_merge($header, $author);
296 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
297 if (!is_object($alternate)) {
298 $alternate = XML::getFirstAttributes($xpath, 'atom:link', $entry);
300 if (is_object($alternate)) {
301 foreach ($alternate as $attribute) {
302 if ($attribute->name == 'href') {
303 $item['plink'] = $attribute->textContent;
308 if (empty($item['plink'])) {
309 $item['plink'] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
312 if (empty($item['plink'])) {
313 $item['plink'] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
316 // Add the base path if missing
317 $item['plink'] = Network::addBasePath($item['plink'], $basepath);
319 $item['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
321 $guid = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
323 $item['uri'] = $guid;
325 // Don't use the GUID value directly but instead use it as a basis for the GUID
326 $item['guid'] = Item::guidFromUri($guid, parse_url($guid, PHP_URL_HOST) ?? parse_url($item['plink'], PHP_URL_HOST));
329 if (empty($item['uri'])) {
330 $item['uri'] = $item['plink'];
333 $orig_plink = $item['plink'];
336 $item['plink'] = DI::httpClient()->finalUrl($item['plink']);
337 } catch (TransferException $exception) {
338 Logger::notice('Item URL couldn\'t get expanded', ['url' => $item['plink'], 'exception' => $exception]);
341 $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
343 if (empty($item['title'])) {
344 $item['title'] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
347 if (empty($item['title'])) {
348 $item['title'] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
351 if (empty($item['title'])) {
352 $item['title'] = XML::getFirstNodeValue($xpath, 'itunes:title/text()', $entry);
355 $item['title'] = html_entity_decode($item['title'], ENT_QUOTES, 'UTF-8');
357 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
359 if (empty($published)) {
360 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
363 if (empty($published)) {
364 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
367 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
369 if (empty($updated) && !empty($published)) {
370 $updated = $published;
373 if (empty($published) && !empty($updated)) {
374 $published = $updated;
377 if ($published != '') {
378 $item['created'] = $published;
381 if ($updated != '') {
382 $item['edited'] = $updated;
386 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
387 $importer['uid'], $item['uri'], Protocol::FEED, Protocol::DFRN];
388 $previous = Post::selectFirst(['id', 'created'], $condition);
389 if (DBA::isResult($previous)) {
390 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
391 $creation_dates[] = $previous['created'];
392 Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']);
395 $creation_dates[] = DateTimeFormat::utc($item['created']);
398 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
400 if (empty($creator)) {
401 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
404 if (empty($creator)) {
405 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
408 if ($creator != '') {
409 $item['author-name'] = $creator;
412 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
414 if ($creator != '') {
415 $item['author-name'] = $creator;
419 // <category>Ausland</category>
420 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
424 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
425 foreach ($enclosures as $enclosure) {
430 foreach ($enclosure->attributes as $attribute) {
431 if (in_array($attribute->name, ['url', 'href'])) {
432 $href = $attribute->textContent;
433 } elseif ($attribute->name == 'length') {
434 $length = (int)$attribute->textContent;
435 } elseif ($attribute->name == 'type') {
436 $type = $attribute->textContent;
441 $attachment = ['uri-id' => -1, 'type' => Post\Media::UNKNOWN, 'url' => $href, 'mimetype' => $type, 'size' => $length];
443 $attachment = Post\Media::fetchAdditionalData($attachment);
445 // By now we separate the visible media types (audio, video, image) from the rest
446 // In the future we should try to avoid the DOCUMENT type and only use the real one - but not in the RC phase.
447 if (!in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO])) {
448 $attachment['type'] = Post\Media::DOCUMENT;
450 $attachments[] = $attachment;
455 $categories = $xpath->query('category', $entry);
456 foreach ($categories as $category) {
457 $taglist[] = $category->nodeValue;
460 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
463 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
466 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
468 if (empty($summary)) {
469 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
477 if ($body == $summary) {
481 // remove the content of the title if it is identically to the body
482 // This helps with auto generated titles e.g. from tumblr
483 if (self::titleIsBody($item['title'], $body)) {
486 $item['body'] = HTML::toBBCode($body, $basepath);
488 // Remove tracking pixels
489 $item['body'] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item['body']);
491 if (($item['body'] == '') && ($item['title'] != '')) {
492 $item['body'] = $item['title'];
497 $item['attachments'] = $attachments;
500 } elseif (!Item::isValid($item)) {
501 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
503 } elseif (Item::isTooOld($item)) {
504 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
509 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] < 3)) {
510 // Handle enclosures and treat them as preview picture
511 foreach ($attachments as $attachment) {
512 if ($attachment['mimetype'] == 'image/jpeg') {
513 $preview = $attachment['url'];
517 // Remove a possible link to the item itself
518 $item['body'] = str_replace($item['plink'], '', $item['body']);
519 $item['body'] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item['body']));
521 // Replace the content when the title is longer than the body
522 $replace = (strlen($item['title']) > strlen($item['body']));
524 // Replace it, when there is an image in the body
525 if (strstr($item['body'], '[/img]')) {
529 // Replace it, when there is a link in the body
530 if (strstr($item['body'], '[/url]')) {
534 $saved_body = $item['body'];
535 $saved_title = $item['title'];
538 $item['body'] = trim($item['title']);
541 $data = ParseUrl::getSiteinfoCached($item['plink']);
542 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
543 // When the fetched page info text is longer than the body, we do try to enhance the body
544 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
545 // The body is not part of the fetched page info title or page info text. So we add the text to the body
546 $item['body'] .= "\n\n" . $data['text'];
548 // Else we replace the body with the page info text
549 $item['body'] = $data['text'];
553 $data = PageInfo::queryUrl($item['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_denylist'] ?? '');
556 // Take the data that was provided by the feed if the query is empty
557 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
558 $data['title'] = $saved_title;
559 $item['body'] = $saved_body;
562 $data_text = strip_tags(trim($data['text'] ?? ''));
563 $item_body = strip_tags(trim($item['body'] ?? ''));
565 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
569 // We always strip the title since it will be added in the page information
571 $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false);
572 $taglist = $contact['fetch_further_information'] == 2 ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : [];
573 $item['object-type'] = Activity\ObjectType::BOOKMARK;
576 foreach (['audio', 'video'] as $elementname) {
577 if (!empty($data[$elementname])) {
578 foreach ($data[$elementname] as $element) {
579 if (!empty($element['src'])) {
580 $src = $element['src'];
581 } elseif (!empty($element['content'])) {
582 $src = $element['content'];
588 'type' => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
590 'preview' => $element['image'] ?? null,
591 'mimetype' => $element['contenttype'] ?? null,
592 'name' => $element['name'] ?? null,
593 'description' => $element['description'] ?? null,
600 if (!empty($summary)) {
601 $item['body'] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item['body'];
604 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] == 3)) {
605 if (empty($taglist)) {
606 $taglist = PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '');
608 $item['body'] .= "\n" . self::tagToString($taglist);
613 // Add the link to the original feed entry if not present in feed
614 if (($item['plink'] != '') && !strstr($item['body'], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
615 $item['body'] .= '[hr][url]' . $item['plink'] . '[/url]';
619 if (empty($item['title'])) {
620 $item['post-type'] = Item::PT_NOTE;
623 Logger::info('Stored feed', ['item' => $item]);
625 $notify = Item::isRemoteSelf($contact, $item);
627 // Distributed items should have a well formatted URI.
628 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
630 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
631 $item['uri'] = Item::newURI($item['guid']);
632 unset($item['thr-parent']);
633 unset($item['parent-uri']);
635 // Set the delivery priority for "remote self" to "medium"
636 $notify = Worker::PRIORITY_MEDIUM;
639 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
640 if (!Post::exists($condition) && !Post\Delayed::exists($item['uri'], $item['uid'])) {
642 Post\Delayed::publish($item, $notify, $taglist, $attachments);
644 $postings[] = ['item' => $item, 'notify' => $notify,
645 'taglist' => $taglist, 'attachments' => $attachments];
648 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]);
652 if (!empty($postings)) {
653 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
654 $total = count($postings);
656 // Posts shouldn't be delayed more than a day
657 $interval = min(1440, self::getPollInterval($contact));
658 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
659 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
666 foreach ($postings as $posting) {
668 $publish_time = time() + $post_delay;
669 $post_delay += $delay;
671 $publish_time = time();
674 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
675 $next_publish = max($last_publish + (60 * $min_posting), time());
676 if ($publish_time < $next_publish) {
677 $publish_time = $next_publish;
679 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
681 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
682 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
687 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
688 self::adjustPollFrequency($contact, $creation_dates);
691 return ['header' => $author, 'items' => $items];
695 * Automatically adjust the poll frequency according to the post frequency
697 * @param array $contact Contact array
698 * @param array $creation_dates
701 private static function adjustPollFrequency(array $contact, array $creation_dates)
703 if ($contact['network'] != Protocol::FEED) {
704 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
708 if (!empty($creation_dates)) {
709 // Count the post frequency and the earliest and latest post date
713 $oldest_date = $newest_date = '';
715 foreach ($creation_dates as $date) {
716 $timestamp = strtotime($date);
717 $day = intdiv($timestamp, 86400);
718 $hour = $timestamp % 86400;
720 // Only have a look at values from the last seven days
721 if (((time() / 86400) - $day) < 7) {
722 if (empty($frequency[$day])) {
723 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
725 ++$frequency[$day]['count'];
726 if ($frequency[$day]['low'] > $hour) {
727 $frequency[$day]['low'] = $hour;
729 if ($frequency[$day]['high'] < $hour) {
730 $frequency[$day]['high'] = $hour;
734 if ($oldest > $day) {
736 $oldest_date = $date;
739 if ($newest < $day) {
741 $newest_date = $date;
745 if (count($creation_dates) == 1) {
746 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
747 $priority = 8; // Poll once a day
750 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
751 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']]);
752 $priority = 10; // Poll every month
755 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
756 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']]);
757 $priority = 9; // Poll every week
760 if (empty($priority) && empty($frequency)) {
761 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']]);
762 $priority = 8; // Poll once a day
765 if (empty($priority)) {
766 // Calculate the highest "posts per day" value
768 foreach ($frequency as $entry) {
769 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
773 // We take the earliest and latest post day and interpolate the number of post per day
774 // that would had been created with this post frequency
776 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
777 $duration = max($entry['high'] - $entry['low'], 14400);
778 $ppd = (86400 / $duration) * $entry['count'];
784 $priority = 1; // Poll every quarter hour
785 } elseif ($max > 24) {
786 $priority = 2; // Poll half an hour
787 } elseif ($max > 12) {
788 $priority = 3; // Poll hourly
789 } elseif ($max > 8) {
790 $priority = 4; // Poll every two hours
791 } elseif ($max > 4) {
792 $priority = 5; // Poll every three hours
793 } elseif ($max > 2) {
794 $priority = 6; // Poll every six hours
796 $priority = 7; // Poll twice a day
798 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
801 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
802 $priority = 8; // Poll once a day
805 if ($contact['rating'] != $priority) {
806 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
807 Contact::update(['rating' => $priority], ['id' => $contact['id']]);
812 * Get the poll interval for the given contact array
814 * @param array $contact
815 * @return int Poll interval in minutes
817 public static function getPollInterval(array $contact): int
819 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
820 $ratings = [0, 3, 7, 8, 9, 10];
821 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
822 $rating = $contact['rating'];
823 } elseif (array_key_exists($contact['priority'], $ratings)) {
824 $rating = $ratings[$contact['priority']];
829 // Check once a week per default for all other networks
833 // Friendica and OStatus are checked once a day
834 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
838 // Check archived contacts or contacts with unsupported protocols once a month
839 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
847 * Based on $contact['priority'], should we poll this site now? Or later?
850 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
852 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
854 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
855 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
857 return $poll_intervals[$rating];
861 * Convert a tag array to a tag string
864 * @return string tag string
866 private static function tagToString(array $tags): string
870 foreach ($tags as $tag) {
875 $tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
881 private static function titleIsBody(string $title, string $body): bool
883 $title = strip_tags($title);
884 $title = trim($title);
885 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
886 $title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
888 $body = strip_tags($body);
890 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
891 $body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
893 if (strlen($title) < strlen($body)) {
894 $body = substr($body, 0, strlen($title));
897 if (($title != $body) && (substr($title, -3) == '...')) {
898 $pos = strrpos($title, '...');
900 $title = substr($title, 0, $pos);
901 $body = substr($body, 0, $pos);
904 return ($title == $body);
908 * Creates the Atom feed for a given nickname
911 * - activity (default): all the public posts
912 * - posts: all the public top-level posts
913 * - comments: all the public replies
915 * Updates the provided last_update parameter if the result comes from the
916 * cache or it is empty
918 * @param string $owner_nick Nickname of the feed owner
919 * @param string $last_update Date of the last update
920 * @param integer $max_items Number of maximum items to fetch
921 * @param string $filter Feed items filter (activity, posts or comments)
922 * @param boolean $nocache Wether to bypass caching
924 * @return string Atom feed
925 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
926 * @throws \ImagickException
928 public static function atom(string $owner_nick, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
930 $stamp = microtime(true);
932 $owner = User::getOwnerDataByNick($owner_nick);
937 $cachekey = 'feed:feed:' . $owner_nick . ':' . $filter . ':' . $last_update;
939 // Display events in the users's timezone
940 if (strlen($owner['timezone'])) {
941 DI::app()->setTimeZone($owner['timezone']);
944 $previous_created = $last_update;
946 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
947 if ((time() - strtotime($owner['last-item'])) < 15*60) {
948 $result = DI::cache()->get($cachekey);
949 if (!$nocache && !is_null($result)) {
950 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
951 return $result['feed'];
955 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
956 $authorid = Contact::getIdForURL($owner['url']);
958 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
959 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
960 $owner['uid'], $check_date, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT,
961 Item::PRIVATE, Protocol::ACTIVITYPUB,
962 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
964 if ($filter === 'comments') {
965 $condition[0] .= " AND `gravity` = ? ";
966 $condition[] = Item::GRAVITY_COMMENT;
969 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
970 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
971 $condition[] = $owner['id'];
972 $condition[] = $authorid;
975 $params = ['order' => ['received' => true], 'limit' => $max_items];
977 if ($filter === 'posts') {
978 $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
980 $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
983 $items = Post::toArray($ret);
985 $doc = new DOMDocument('1.0', 'utf-8');
986 $doc->formatOutput = true;
988 $root = self::addHeader($doc, $owner, $filter);
990 foreach ($items as $item) {
991 $entry = self::noteEntry($doc, $item, $owner);
992 $root->appendChild($entry);
994 if ($last_update < $item['created']) {
995 $last_update = $item['created'];
999 $feeddata = trim($doc->saveXML());
1001 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
1002 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1004 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
1010 * Adds the header elements to the XML document
1012 * @param DOMDocument $doc XML document
1013 * @param array $owner Contact data of the poster
1014 * @param string $filter The related feed filter (activity, posts or comments)
1016 * @return DOMElement Header root element
1017 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1019 private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1021 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1022 $doc->appendChild($root);
1025 $selfUri = '/feed/' . $owner['nick'] . '/';
1028 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1029 $selfUri .= $filter;
1032 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1035 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1036 $selfUri .= $filter;
1040 $attributes = ['uri' => 'https://friendi.ca', 'version' => App::VERSION . '-' . DB_UPDATE_VERSION];
1041 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1042 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1043 XML::addElement($doc, $root, 'title', $title);
1044 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1045 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1046 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1048 $author = self::addAuthor($doc, $owner);
1049 $root->appendChild($author);
1051 $attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
1052 XML::addElement($doc, $root, 'link', '', $attributes);
1054 OStatus::addHubLink($doc, $root, $owner['nick']);
1056 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1057 XML::addElement($doc, $root, 'link', '', $attributes);
1063 * Adds the author element to the XML document
1065 * @param DOMDocument $doc XML document
1066 * @param array $owner Contact data of the poster
1067 * @return DOMElement author element
1068 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1070 private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
1072 $author = $doc->createElement('author');
1073 XML::addElement($doc, $author, 'uri', $owner['url']);
1074 XML::addElement($doc, $author, 'name', $owner['nick']);
1075 XML::addElement($doc, $author, 'email', $owner['addr']);
1081 * Adds a regular entry element
1083 * @param DOMDocument $doc XML document
1084 * @param array $item Data of the item that is to be posted
1085 * @param array $owner Contact data of the poster
1086 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1087 * @return DOMElement Entry element
1088 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1089 * @throws \ImagickException
1091 private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
1093 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1094 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
1097 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1099 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1101 self::entryFooter($doc, $entry, $item, $owner);
1107 * Adds elements to the XML document
1109 * @param DOMDocument $doc XML document
1110 * @param \DOMElement $entry Entry element where the content is added
1111 * @param array $item Data of the item that is to be posted
1112 * @param array $owner Contact data of the poster
1113 * @param string $title Title for the post
1114 * @param string $verb The activity verb
1115 * @param bool $complete Add the "status_net" element?
1117 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1119 private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
1122 $verb = OStatus::constructVerb($item);
1125 XML::addElement($doc, $entry, 'id', $item['uri']);
1126 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1128 $body = OStatus::formatPicturePost($item['body'], $item['uri-id']);
1130 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1132 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1134 XML::addElement($doc, $entry, 'link', '', ['rel' => 'alternate', 'type' => 'text/html',
1135 'href' => DI::baseUrl() . '/display/' . $item['guid']]
1138 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1139 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1143 * Adds the elements at the foot of an entry to the XML document
1145 * @param DOMDocument $doc XML document
1146 * @param object $entry The entry element where the elements are added
1147 * @param array $item Data of the item that is to be posted
1148 * @param array $owner Contact data of the poster
1149 * @param bool $complete default true
1151 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1153 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1157 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1158 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1160 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1162 if (DBA::isResult($thrparent)) {
1163 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1164 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1165 $parent_plink = $thrparent['plink'];
1166 } elseif (DBA::isResult($parent)) {
1167 $mentioned[$parent['author-link']] = $parent['author-link'];
1168 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1169 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1171 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1174 if (isset($parent_plink)) {
1176 'ref' => $item['thr-parent'],
1177 'href' => $parent_plink];
1178 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1182 'href' => $parent_plink];
1183 XML::addElement($doc, $entry, 'link', '', $attributes);
1187 // uri-id isn't present for follow entry pseudo-items
1188 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1189 foreach ($tags as $tag) {
1190 $mentioned[$tag['url']] = $tag['url'];
1193 foreach ($tags as $tag) {
1194 if ($tag['type'] == Tag::HASHTAG) {
1195 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1199 OStatus::getAttachment($doc, $entry, $item);
1203 * Fetch or create title for feed entry
1205 * @param array $item
1206 * @return string title
1208 private static function getTitle(array $item): string
1210 if ($item['title'] != '') {
1211 return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1214 // Fetch information about the post
1215 $siteinfo = BBCode::getAttachedData($item['body']);
1216 if (isset($siteinfo['title'])) {
1217 return $siteinfo['title'];
1220 // If no bookmark is found then take the first line
1221 // Remove the share element before fetching the first line
1222 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
1224 $title = BBCode::toPlaintext($title)."\n";
1225 $pos = strpos($title, "\n");
1227 if (($pos == 0) || ($pos > 100)) {
1232 return substr($title, 0, $pos) . $trailer;