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 $header['uid'] = $importer['uid'] ?? 0;
259 $header['network'] = Protocol::FEED;
260 $datarray['protocol'] = $protocol;
261 $datarray['direction'] = Conversation::PULL;
263 $header['origin'] = 0;
264 $header['gravity'] = GRAVITY_PARENT;
265 $header['private'] = Item::PUBLIC;
266 $header['verb'] = Activity::POST;
267 $header['object-type'] = Activity\ObjectType::NOTE;
268 $header['post-type'] = Item::PT_ARTICLE;
270 $header['contact-id'] = $contact['id'] ?? 0;
272 if (!is_object($entries)) {
273 Logger::info("There are no entries in this feed.");
278 $creation_dates = [];
280 // Limit the number of items that are about to be fetched
281 $total_items = ($entries->length - 1);
282 $max_items = DI::config()->get('system', 'max_feed_items');
283 if (($max_items > 0) && ($total_items > $max_items)) {
284 $total_items = $max_items;
289 // Importing older entries first
290 for ($i = $total_items; $i >= 0; --$i) {
291 $entry = $entries->item($i);
293 $item = array_merge($header, $author);
295 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
296 if (!is_object($alternate)) {
297 $alternate = XML::getFirstAttributes($xpath, 'atom:link', $entry);
299 if (is_object($alternate)) {
300 foreach ($alternate as $attribute) {
301 if ($attribute->name == 'href') {
302 $item['plink'] = $attribute->textContent;
307 if (empty($item['plink'])) {
308 $item['plink'] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
311 if (empty($item['plink'])) {
312 $item['plink'] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
315 // Add the base path if missing
316 $item['plink'] = Network::addBasePath($item['plink'], $basepath);
318 $item['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
320 $guid = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
322 $item['uri'] = $guid;
324 // Don't use the GUID value directly but instead use it as a basis for the GUID
325 $item['guid'] = Item::guidFromUri($guid, parse_url($guid, PHP_URL_HOST) ?? parse_url($item['plink'], PHP_URL_HOST));
328 if (empty($item['uri'])) {
329 $item['uri'] = $item['plink'];
332 $orig_plink = $item['plink'];
335 $item['plink'] = DI::httpClient()->finalUrl($item['plink']);
336 } catch (TransferException $exception) {
337 Logger::notice('Item URL couldn\'t get expanded', ['url' => $item['plink'], 'exception' => $exception]);
340 $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
342 if (empty($item['title'])) {
343 $item['title'] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
346 if (empty($item['title'])) {
347 $item['title'] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
350 if (empty($item['title'])) {
351 $item['title'] = XML::getFirstNodeValue($xpath, 'itunes:title/text()', $entry);
354 $item['title'] = html_entity_decode($item['title'], ENT_QUOTES, 'UTF-8');
356 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
358 if (empty($published)) {
359 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
362 if (empty($published)) {
363 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
366 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
368 if (empty($updated) && !empty($published)) {
369 $updated = $published;
372 if (empty($published) && !empty($updated)) {
373 $published = $updated;
376 if ($published != '') {
377 $item['created'] = $published;
380 if ($updated != '') {
381 $item['edited'] = $updated;
385 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
386 $importer['uid'], $item['uri'], Protocol::FEED, Protocol::DFRN];
387 $previous = Post::selectFirst(['id', 'created'], $condition);
388 if (DBA::isResult($previous)) {
389 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
390 $creation_dates[] = $previous['created'];
391 Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']);
394 $creation_dates[] = DateTimeFormat::utc($item['created']);
397 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
399 if (empty($creator)) {
400 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
403 if (empty($creator)) {
404 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
407 if ($creator != '') {
408 $item['author-name'] = $creator;
411 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
413 if ($creator != '') {
414 $item['author-name'] = $creator;
418 // <category>Ausland</category>
419 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
423 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
424 foreach ($enclosures as $enclosure) {
429 foreach ($enclosure->attributes as $attribute) {
430 if (in_array($attribute->name, ['url', 'href'])) {
431 $href = $attribute->textContent;
432 } elseif ($attribute->name == 'length') {
433 $length = (int)$attribute->textContent;
434 } elseif ($attribute->name == 'type') {
435 $type = $attribute->textContent;
440 $attachment = ['type' => Post\Media::UNKNOWN, 'url' => $href, 'mimetype' => $type, 'size' => $length];
442 $attachment = Post\Media::fetchAdditionalData($attachment);
444 // By now we separate the visible media types (audio, video, image) from the rest
445 // In the future we should try to avoid the DOCUMENT type and only use the real one - but not in the RC phase.
446 if (!in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO])) {
447 $attachment['type'] = Post\Media::DOCUMENT;
449 $attachments[] = $attachment;
454 $categories = $xpath->query('category', $entry);
455 foreach ($categories as $category) {
456 $taglist[] = $category->nodeValue;
459 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
462 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
465 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
467 if (empty($summary)) {
468 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
476 if ($body == $summary) {
480 // remove the content of the title if it is identically to the body
481 // This helps with auto generated titles e.g. from tumblr
482 if (self::titleIsBody($item['title'], $body)) {
485 $item['body'] = HTML::toBBCode($body, $basepath);
487 // Remove tracking pixels
488 $item['body'] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item['body']);
490 if (($item['body'] == '') && ($item['title'] != '')) {
491 $item['body'] = $item['title'];
496 $item['attachments'] = $attachments;
499 } elseif (!Item::isValid($item)) {
500 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
502 } elseif (Item::isTooOld($item)) {
503 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
508 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] < 3)) {
509 // Handle enclosures and treat them as preview picture
510 foreach ($attachments as $attachment) {
511 if ($attachment['mimetype'] == 'image/jpeg') {
512 $preview = $attachment['url'];
516 // Remove a possible link to the item itself
517 $item['body'] = str_replace($item['plink'], '', $item['body']);
518 $item['body'] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item['body']));
520 // Replace the content when the title is longer than the body
521 $replace = (strlen($item['title']) > strlen($item['body']));
523 // Replace it, when there is an image in the body
524 if (strstr($item['body'], '[/img]')) {
528 // Replace it, when there is a link in the body
529 if (strstr($item['body'], '[/url]')) {
533 $saved_body = $item['body'];
534 $saved_title = $item['title'];
537 $item['body'] = trim($item['title']);
540 $data = ParseUrl::getSiteinfoCached($item['plink']);
541 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
542 // When the fetched page info text is longer than the body, we do try to enhance the body
543 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
544 // The body is not part of the fetched page info title or page info text. So we add the text to the body
545 $item['body'] .= "\n\n" . $data['text'];
547 // Else we replace the body with the page info text
548 $item['body'] = $data['text'];
552 $data = PageInfo::queryUrl($item['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_denylist'] ?? '');
555 // Take the data that was provided by the feed if the query is empty
556 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
557 $data['title'] = $saved_title;
558 $item['body'] = $saved_body;
561 $data_text = strip_tags(trim($data['text'] ?? ''));
562 $item_body = strip_tags(trim($item['body'] ?? ''));
564 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
568 // We always strip the title since it will be added in the page information
570 $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false);
571 $taglist = $contact['fetch_further_information'] == 2 ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : [];
572 $item['object-type'] = Activity\ObjectType::BOOKMARK;
575 foreach (['audio', 'video'] as $elementname) {
576 if (!empty($data[$elementname])) {
577 foreach ($data[$elementname] as $element) {
578 if (!empty($element['src'])) {
579 $src = $element['src'];
580 } elseif (!empty($element['content'])) {
581 $src = $element['content'];
587 'type' => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
589 'preview' => $element['image'] ?? null,
590 'mimetype' => $element['contenttype'] ?? null,
591 'name' => $element['name'] ?? null,
592 'description' => $element['description'] ?? null,
599 if (!empty($summary)) {
600 $item['body'] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item['body'];
603 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] == 3)) {
604 if (empty($taglist)) {
605 $taglist = PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '');
607 $item['body'] .= "\n" . self::tagToString($taglist);
612 // Add the link to the original feed entry if not present in feed
613 if (($item['plink'] != '') && !strstr($item['body'], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
614 $item['body'] .= '[hr][url]' . $item['plink'] . '[/url]';
618 if (empty($item['title'])) {
619 $item['post-type'] = Item::PT_NOTE;
622 Logger::info('Stored feed', ['item' => $item]);
624 $notify = Item::isRemoteSelf($contact, $item);
626 // Distributed items should have a well formatted URI.
627 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
629 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
630 $item['uri'] = Item::newURI($item['guid']);
631 unset($item['thr-parent']);
632 unset($item['parent-uri']);
634 // Set the delivery priority for "remote self" to "medium"
635 $notify = Worker::PRIORITY_MEDIUM;
638 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
639 if (!Post::exists($condition) && !Post\Delayed::exists($item['uri'], $item['uid'])) {
641 Post\Delayed::publish($item, $notify, $taglist, $attachments);
643 $postings[] = ['item' => $item, 'notify' => $notify,
644 'taglist' => $taglist, 'attachments' => $attachments];
647 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]);
651 if (!empty($postings)) {
652 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
653 $total = count($postings);
655 // Posts shouldn't be delayed more than a day
656 $interval = min(1440, self::getPollInterval($contact));
657 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
658 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
665 foreach ($postings as $posting) {
667 $publish_time = time() + $post_delay;
668 $post_delay += $delay;
670 $publish_time = time();
673 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
674 $next_publish = max($last_publish + (60 * $min_posting), time());
675 if ($publish_time < $next_publish) {
676 $publish_time = $next_publish;
678 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
680 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
681 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
686 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
687 self::adjustPollFrequency($contact, $creation_dates);
690 return ['header' => $author, 'items' => $items];
694 * Automatically adjust the poll frequency according to the post frequency
696 * @param array $contact Contact array
697 * @param array $creation_dates
700 private static function adjustPollFrequency(array $contact, array $creation_dates)
702 if ($contact['network'] != Protocol::FEED) {
703 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
707 if (!empty($creation_dates)) {
708 // Count the post frequency and the earliest and latest post date
712 $oldest_date = $newest_date = '';
714 foreach ($creation_dates as $date) {
715 $timestamp = strtotime($date);
716 $day = intdiv($timestamp, 86400);
717 $hour = $timestamp % 86400;
719 // Only have a look at values from the last seven days
720 if (((time() / 86400) - $day) < 7) {
721 if (empty($frequency[$day])) {
722 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
724 ++$frequency[$day]['count'];
725 if ($frequency[$day]['low'] > $hour) {
726 $frequency[$day]['low'] = $hour;
728 if ($frequency[$day]['high'] < $hour) {
729 $frequency[$day]['high'] = $hour;
733 if ($oldest > $day) {
735 $oldest_date = $date;
738 if ($newest < $day) {
740 $newest_date = $date;
744 if (count($creation_dates) == 1) {
745 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
746 $priority = 8; // Poll once a day
749 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
750 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']]);
751 $priority = 10; // Poll every month
754 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
755 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']]);
756 $priority = 9; // Poll every week
759 if (empty($priority) && empty($frequency)) {
760 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']]);
761 $priority = 8; // Poll once a day
764 if (empty($priority)) {
765 // Calculate the highest "posts per day" value
767 foreach ($frequency as $entry) {
768 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
772 // We take the earliest and latest post day and interpolate the number of post per day
773 // that would had been created with this post frequency
775 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
776 $duration = max($entry['high'] - $entry['low'], 14400);
777 $ppd = (86400 / $duration) * $entry['count'];
783 $priority = 1; // Poll every quarter hour
784 } elseif ($max > 24) {
785 $priority = 2; // Poll half an hour
786 } elseif ($max > 12) {
787 $priority = 3; // Poll hourly
788 } elseif ($max > 8) {
789 $priority = 4; // Poll every two hours
790 } elseif ($max > 4) {
791 $priority = 5; // Poll every three hours
792 } elseif ($max > 2) {
793 $priority = 6; // Poll every six hours
795 $priority = 7; // Poll twice a day
797 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
800 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
801 $priority = 8; // Poll once a day
804 if ($contact['rating'] != $priority) {
805 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
806 Contact::update(['rating' => $priority], ['id' => $contact['id']]);
811 * Get the poll interval for the given contact array
813 * @param array $contact
814 * @return int Poll interval in minutes
816 public static function getPollInterval(array $contact): int
818 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
819 $ratings = [0, 3, 7, 8, 9, 10];
820 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
821 $rating = $contact['rating'];
822 } elseif (array_key_exists($contact['priority'], $ratings)) {
823 $rating = $ratings[$contact['priority']];
828 // Check once a week per default for all other networks
832 // Friendica and OStatus are checked once a day
833 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
837 // Check archived contacts or contacts with unsupported protocols once a month
838 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
846 * Based on $contact['priority'], should we poll this site now? Or later?
849 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
851 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
853 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
854 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
856 return $poll_intervals[$rating];
860 * Convert a tag array to a tag string
863 * @return string tag string
865 private static function tagToString(array $tags): string
869 foreach ($tags as $tag) {
874 $tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
880 private static function titleIsBody(string $title, string $body): bool
882 $title = strip_tags($title);
883 $title = trim($title);
884 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
885 $title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
887 $body = strip_tags($body);
889 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
890 $body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
892 if (strlen($title) < strlen($body)) {
893 $body = substr($body, 0, strlen($title));
896 if (($title != $body) && (substr($title, -3) == '...')) {
897 $pos = strrpos($title, '...');
899 $title = substr($title, 0, $pos);
900 $body = substr($body, 0, $pos);
903 return ($title == $body);
907 * Creates the Atom feed for a given nickname
910 * - activity (default): all the public posts
911 * - posts: all the public top-level posts
912 * - comments: all the public replies
914 * Updates the provided last_update parameter if the result comes from the
915 * cache or it is empty
917 * @param string $owner_nick Nickname of the feed owner
918 * @param string $last_update Date of the last update
919 * @param integer $max_items Number of maximum items to fetch
920 * @param string $filter Feed items filter (activity, posts or comments)
921 * @param boolean $nocache Wether to bypass caching
923 * @return string Atom feed
924 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
925 * @throws \ImagickException
927 public static function atom(string $owner_nick, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
929 $stamp = microtime(true);
931 $owner = User::getOwnerDataByNick($owner_nick);
936 $cachekey = 'feed:feed:' . $owner_nick . ':' . $filter . ':' . $last_update;
938 // Display events in the users's timezone
939 if (strlen($owner['timezone'])) {
940 DI::app()->setTimeZone($owner['timezone']);
943 $previous_created = $last_update;
945 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
946 if ((time() - strtotime($owner['last-item'])) < 15*60) {
947 $result = DI::cache()->get($cachekey);
948 if (!$nocache && !is_null($result)) {
949 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
950 return $result['feed'];
954 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
955 $authorid = Contact::getIdForURL($owner['url']);
957 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
958 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
959 $owner['uid'], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
960 Item::PRIVATE, Protocol::ACTIVITYPUB,
961 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
963 if ($filter === 'comments') {
964 $condition[0] .= " AND `gravity` = ? ";
965 $condition[] = GRAVITY_COMMENT;
968 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
969 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
970 $condition[] = $owner['id'];
971 $condition[] = $authorid;
974 $params = ['order' => ['received' => true], 'limit' => $max_items];
976 if ($filter === 'posts') {
977 $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
979 $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
982 $items = Post::toArray($ret);
984 $doc = new DOMDocument('1.0', 'utf-8');
985 $doc->formatOutput = true;
987 $root = self::addHeader($doc, $owner, $filter);
989 foreach ($items as $item) {
990 $entry = self::noteEntry($doc, $item, $owner);
991 $root->appendChild($entry);
993 if ($last_update < $item['created']) {
994 $last_update = $item['created'];
998 $feeddata = trim($doc->saveXML());
1000 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
1001 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1003 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
1009 * Adds the header elements to the XML document
1011 * @param DOMDocument $doc XML document
1012 * @param array $owner Contact data of the poster
1013 * @param string $filter The related feed filter (activity, posts or comments)
1015 * @return DOMElement Header root element
1016 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1018 private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1020 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1021 $doc->appendChild($root);
1024 $selfUri = '/feed/' . $owner['nick'] . '/';
1027 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1028 $selfUri .= $filter;
1031 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1034 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1035 $selfUri .= $filter;
1039 $attributes = ['uri' => 'https://friendi.ca', 'version' => App::VERSION . '-' . DB_UPDATE_VERSION];
1040 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1041 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1042 XML::addElement($doc, $root, 'title', $title);
1043 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1044 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1045 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1047 $author = self::addAuthor($doc, $owner);
1048 $root->appendChild($author);
1050 $attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
1051 XML::addElement($doc, $root, 'link', '', $attributes);
1053 OStatus::addHubLink($doc, $root, $owner['nick']);
1055 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1056 XML::addElement($doc, $root, 'link', '', $attributes);
1062 * Adds the author element to the XML document
1064 * @param DOMDocument $doc XML document
1065 * @param array $owner Contact data of the poster
1066 * @return DOMElement author element
1067 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1069 private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
1071 $author = $doc->createElement('author');
1072 XML::addElement($doc, $author, 'uri', $owner['url']);
1073 XML::addElement($doc, $author, 'name', $owner['nick']);
1074 XML::addElement($doc, $author, 'email', $owner['addr']);
1080 * Adds a regular entry element
1082 * @param DOMDocument $doc XML document
1083 * @param array $item Data of the item that is to be posted
1084 * @param array $owner Contact data of the poster
1085 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1086 * @return DOMElement Entry element
1087 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1088 * @throws \ImagickException
1090 private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
1092 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1093 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
1096 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1098 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1100 self::entryFooter($doc, $entry, $item, $owner);
1106 * Adds elements to the XML document
1108 * @param DOMDocument $doc XML document
1109 * @param \DOMElement $entry Entry element where the content is added
1110 * @param array $item Data of the item that is to be posted
1111 * @param array $owner Contact data of the poster
1112 * @param string $title Title for the post
1113 * @param string $verb The activity verb
1114 * @param bool $complete Add the "status_net" element?
1116 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1118 private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
1121 $verb = OStatus::constructVerb($item);
1124 XML::addElement($doc, $entry, 'id', $item['uri']);
1125 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1127 $body = OStatus::formatPicturePost($item['body'], $item['uri-id']);
1129 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1131 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1133 XML::addElement($doc, $entry, 'link', '', ['rel' => 'alternate', 'type' => 'text/html',
1134 'href' => DI::baseUrl() . '/display/' . $item['guid']]
1137 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1138 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1142 * Adds the elements at the foot of an entry to the XML document
1144 * @param DOMDocument $doc XML document
1145 * @param object $entry The entry element where the elements are added
1146 * @param array $item Data of the item that is to be posted
1147 * @param array $owner Contact data of the poster
1148 * @param bool $complete default true
1150 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1152 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1156 if ($item['gravity'] != GRAVITY_PARENT) {
1157 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1159 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1161 if (DBA::isResult($thrparent)) {
1162 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1163 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1164 $parent_plink = $thrparent['plink'];
1165 } elseif (DBA::isResult($parent)) {
1166 $mentioned[$parent['author-link']] = $parent['author-link'];
1167 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1168 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1170 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1173 if (isset($parent_plink)) {
1175 'ref' => $item['thr-parent'],
1176 'href' => $parent_plink];
1177 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1181 'href' => $parent_plink];
1182 XML::addElement($doc, $entry, 'link', '', $attributes);
1186 // uri-id isn't present for follow entry pseudo-items
1187 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1188 foreach ($tags as $tag) {
1189 $mentioned[$tag['url']] = $tag['url'];
1192 foreach ($tags as $tag) {
1193 if ($tag['type'] == Tag::HASHTAG) {
1194 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1198 OStatus::getAttachment($doc, $entry, $item);
1202 * Fetch or create title for feed entry
1204 * @param array $item
1205 * @return string title
1207 private static function getTitle(array $item): string
1209 if ($item['title'] != '') {
1210 return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1213 // Fetch information about the post
1214 $siteinfo = BBCode::getAttachedData($item['body']);
1215 if (isset($siteinfo['title'])) {
1216 return $siteinfo['title'];
1219 // If no bookmark is found then take the first line
1220 // Remove the share element before fetching the first line
1221 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
1223 $title = BBCode::toPlaintext($title)."\n";
1224 $pos = strpos($title, "\n");
1226 if (($pos == 0) || ($pos > 100)) {
1231 return substr($title, 0, $pos) . $trailer;