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;
26 use Friendica\Content\PageInfo;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Cache\Enum\Duration;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Post;
37 use Friendica\Model\Tag;
38 use Friendica\Model\User;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Network;
41 use Friendica\Util\ParseUrl;
42 use Friendica\Util\Proxy;
43 use Friendica\Util\Strings;
44 use Friendica\Util\XML;
45 use GuzzleHttp\Exception\TransferException;
48 * This class contain functions to import feeds (RSS/RDF/Atom)
53 * Read a RSS/RDF/Atom feed and create an item entry for it
55 * @param string $xml The feed data
56 * @param array $importer The user record of the importer
57 * @param array $contact The contact record of the feed
59 * @return array Returns the header and the first item in dry run mode
60 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
62 public static function import($xml, array $importer = [], array $contact = [])
64 $dryRun = empty($importer) && empty($contact);
67 Logger::info("Test Atom/RSS feed");
69 Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
75 Logger::info('XML is empty.');
79 if (!empty($contact['poll'])) {
80 $basepath = $contact['poll'];
81 } elseif (!empty($contact['url'])) {
82 $basepath = $contact['url'];
87 $doc = new DOMDocument();
89 $xpath = new DOMXPath($doc);
90 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
91 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
92 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
93 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
94 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
95 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
96 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
102 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
103 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
104 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
106 if (empty($author["author-name"])) {
107 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
109 $entries = $xpath->query('/rdf:RDF/rss:item');
113 if ($xpath->query('/atom:feed')->length > 0) {
114 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
115 if (is_object($alternate)) {
116 foreach ($alternate as $attribute) {
117 if ($attribute->name == "href") {
118 $author["author-link"] = $attribute->textContent;
123 if (empty($author["author-link"])) {
124 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
125 if (is_object($self)) {
126 foreach ($self as $attribute) {
127 if ($attribute->name == "href") {
128 $author["author-link"] = $attribute->textContent;
134 if (empty($author["author-link"])) {
135 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
137 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
139 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
141 if (empty($author["author-name"])) {
142 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
145 if (empty($author["author-name"])) {
146 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
149 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
151 $author["author-name"] = $value;
155 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
157 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
158 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
160 $author["author-link"] = $value;
163 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
165 $author["author-nick"] = $value;
168 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
170 $author["author-location"] = $value;
173 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
175 $author["author-about"] = $value;
178 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
179 if (is_object($avatar)) {
180 foreach ($avatar as $attribute) {
181 if ($attribute->name == "href") {
182 $author["author-avatar"] = $attribute->textContent;
188 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
190 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
192 $entries = $xpath->query('/atom:feed/atom:entry');
196 if ($xpath->query('/rss/channel')->length > 0) {
197 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
199 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
201 if (empty($author["author-name"])) {
202 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
205 if (empty($author["author-name"])) {
206 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
209 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
211 if (empty($author["author-avatar"])) {
212 $avatar = XML::getFirstAttributes($xpath, "/rss/channel/itunes:image");
213 if (is_object($avatar)) {
214 foreach ($avatar as $attribute) {
215 if ($attribute->name == "href") {
216 $author["author-avatar"] = $attribute->textContent;
222 $author["author-about"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, '/rss/channel/description/text()'), $basepath);
224 if (empty($author["author-about"])) {
225 $author["author-about"] = XML::getFirstNodeValue($xpath, '/rss/channel/itunes:summary/text()');
228 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
230 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
232 $entries = $xpath->query('/rss/channel/item');
236 $author["author-link"] = $contact["url"];
238 if (empty($author["author-name"])) {
239 $author["author-name"] = $contact["name"];
242 $author["author-avatar"] = $contact["thumb"];
244 $author["owner-link"] = $contact["url"];
245 $author["owner-name"] = $contact["name"];
246 $author["owner-avatar"] = $contact["thumb"];
250 $header["uid"] = $importer["uid"] ?? 0;
251 $header["network"] = Protocol::FEED;
253 $header["origin"] = 0;
254 $header["gravity"] = GRAVITY_PARENT;
255 $header["private"] = Item::PUBLIC;
256 $header["verb"] = Activity::POST;
257 $header["object-type"] = Activity\ObjectType::NOTE;
258 $header["post-type"] = Item::PT_ARTICLE;
260 $header["contact-id"] = $contact["id"] ?? 0;
262 if (!is_object($entries)) {
263 Logger::info("There are no entries in this feed.");
268 $creation_dates = [];
270 // Limit the number of items that are about to be fetched
271 $total_items = ($entries->length - 1);
272 $max_items = DI::config()->get('system', 'max_feed_items');
273 if (($max_items > 0) && ($total_items > $max_items)) {
274 $total_items = $max_items;
279 // Importing older entries first
280 for ($i = $total_items; $i >= 0; --$i) {
281 $entry = $entries->item($i);
283 $item = array_merge($header, $author);
285 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
286 if (!is_object($alternate)) {
287 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
289 if (is_object($alternate)) {
290 foreach ($alternate as $attribute) {
291 if ($attribute->name == "href") {
292 $item["plink"] = $attribute->textContent;
297 if (empty($item["plink"])) {
298 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
301 if (empty($item["plink"])) {
302 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
305 // Add the base path if missing
306 $item["plink"] = Network::addBasePath($item["plink"], $basepath);
308 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
310 $guid = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
312 $item["uri"] = $guid;
314 // Don't use the GUID value directly but instead use it as a basis for the GUID
315 $item["guid"] = Item::guidFromUri($guid, parse_url($guid, PHP_URL_HOST) ?? parse_url($item["plink"], PHP_URL_HOST));
318 if (empty($item["uri"])) {
319 $item["uri"] = $item["plink"];
322 $orig_plink = $item["plink"];
325 $item["plink"] = DI::httpClient()->finalUrl($item["plink"]);
326 } catch (TransferException $exception) {
327 Logger::notice('Item URL couldn\'t get expanded', ['url' => $item["plink"], 'exception' => $exception]);
330 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
332 if (empty($item["title"])) {
333 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
336 if (empty($item["title"])) {
337 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
340 if (empty($item["title"])) {
341 $item["title"] = XML::getFirstNodeValue($xpath, 'itunes:title/text()', $entry);
344 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
346 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
348 if (empty($published)) {
349 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
352 if (empty($published)) {
353 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
356 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
358 if (empty($updated) && !empty($published)) {
359 $updated = $published;
362 if (empty($published) && !empty($updated)) {
363 $published = $updated;
366 if ($published != "") {
367 $item["created"] = $published;
370 if ($updated != "") {
371 $item["edited"] = $updated;
375 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
376 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
377 $previous = Post::selectFirst(['id', 'created'], $condition);
378 if (DBA::isResult($previous)) {
379 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
380 $creation_dates[] = $previous['created'];
381 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
384 $creation_dates[] = DateTimeFormat::utc($item['created']);
387 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
389 if (empty($creator)) {
390 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
393 if (empty($creator)) {
394 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
397 if ($creator != "") {
398 $item["author-name"] = $creator;
401 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
403 if ($creator != "") {
404 $item["author-name"] = $creator;
408 // <category>Ausland</category>
409 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
413 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
414 foreach ($enclosures as $enclosure) {
419 foreach ($enclosure->attributes as $attribute) {
420 if (in_array($attribute->name, ["url", "href"])) {
421 $href = $attribute->textContent;
422 } elseif ($attribute->name == "length") {
423 $length = (int)$attribute->textContent;
424 } elseif ($attribute->name == "type") {
425 $type = $attribute->textContent;
430 $attachment = ['type' => Post\Media::UNKNOWN, 'url' => $href, 'mimetype' => $type, 'size' => $length];
432 $attachment = Post\Media::fetchAdditionalData($attachment);
434 // By now we separate the visible media types (audio, video, image) from the rest
435 // In the future we should try to avoid the DOCUMENT type and only use the real one - but not in the RC phase.
436 if (!in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO])) {
437 $attachment['type'] = Post\Media::DOCUMENT;
439 $attachments[] = $attachment;
444 $categories = $xpath->query("category", $entry);
445 foreach ($categories as $category) {
446 $taglist[] = $category->nodeValue;
449 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
452 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
455 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
457 if (empty($summary)) {
458 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
466 if ($body == $summary) {
470 // remove the content of the title if it is identically to the body
471 // This helps with auto generated titles e.g. from tumblr
472 if (self::titleIsBody($item["title"], $body)) {
475 $item["body"] = HTML::toBBCode($body, $basepath);
477 // Remove tracking pixels
478 $item["body"] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item["body"]);
480 if (($item["body"] == '') && ($item["title"] != '')) {
481 $item["body"] = $item["title"];
486 $item['attachments'] = $attachments;
489 } elseif (!Item::isValid($item)) {
490 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
492 } elseif (Item::isTooOld($item)) {
493 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
498 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
499 // Handle enclosures and treat them as preview picture
500 foreach ($attachments as $attachment) {
501 if ($attachment["mimetype"] == "image/jpeg") {
502 $preview = $attachment["url"];
506 // Remove a possible link to the item itself
507 $item["body"] = str_replace($item["plink"], '', $item["body"]);
508 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
510 // Replace the content when the title is longer than the body
511 $replace = (strlen($item["title"]) > strlen($item["body"]));
513 // Replace it, when there is an image in the body
514 if (strstr($item["body"], '[/img]')) {
518 // Replace it, when there is a link in the body
519 if (strstr($item["body"], '[/url]')) {
523 $saved_body = $item["body"];
524 $saved_title = $item["title"];
527 $item["body"] = trim($item["title"]);
530 $data = ParseUrl::getSiteinfoCached($item['plink']);
531 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
532 // When the fetched page info text is longer than the body, we do try to enhance the body
533 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
534 // The body is not part of the fetched page info title or page info text. So we add the text to the body
535 $item['body'] .= "\n\n" . $data['text'];
537 // Else we replace the body with the page info text
538 $item['body'] = $data['text'];
542 $data = PageInfo::queryUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
545 // Take the data that was provided by the feed if the query is empty
546 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
547 $data['title'] = $saved_title;
548 $item["body"] = $saved_body;
551 $data_text = strip_tags(trim($data['text'] ?? ''));
552 $item_body = strip_tags(trim($item['body'] ?? ''));
554 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
558 // We always strip the title since it will be added in the page information
560 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromData($data, false);
561 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
562 $item["object-type"] = Activity\ObjectType::BOOKMARK;
565 foreach (['audio', 'video'] as $elementname) {
566 if (!empty($data[$elementname])) {
567 foreach ($data[$elementname] as $element) {
568 if (!empty($element['src'])) {
569 $src = $element['src'];
570 } elseif (!empty($element['content'])) {
571 $src = $element['content'];
577 'type' => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
579 'preview' => $element['image'] ?? null,
580 'mimetype' => $element['contenttype'] ?? null,
581 'name' => $element['name'] ?? null,
582 'description' => $element['description'] ?? null,
589 if (!empty($summary)) {
590 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
593 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
594 if (empty($taglist)) {
595 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
597 $item["body"] .= "\n" . self::tagToString($taglist);
602 // Add the link to the original feed entry if not present in feed
603 if (($item['plink'] != '') && !strstr($item["body"], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
604 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
608 if (empty($item['title'])) {
609 $item['post-type'] = Item::PT_NOTE;
612 Logger::info('Stored feed', ['item' => $item]);
614 $notify = Item::isRemoteSelf($contact, $item);
616 // Distributed items should have a well formatted URI.
617 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
619 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
620 $item['uri'] = Item::newURI($item['uid'], $item['guid']);
621 unset($item['thr-parent']);
622 unset($item['parent-uri']);
624 // Set the delivery priority for "remote self" to "medium"
625 $notify = PRIORITY_MEDIUM;
628 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
629 if (!Post::exists($condition) && !Post\Delayed::exists($item["uri"], $item['uid'])) {
631 Post\Delayed::publish($item, $notify, $taglist, $attachments);
633 $postings[] = ['item' => $item, 'notify' => $notify,
634 'taglist' => $taglist, 'attachments' => $attachments];
637 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item["uri"]]);
641 if (!empty($postings)) {
642 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
643 $total = count($postings);
645 // Posts shouldn't be delayed more than a day
646 $interval = min(1440, self::getPollInterval($contact));
647 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
648 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
655 foreach ($postings as $posting) {
657 $publish_time = time() + $post_delay;
658 $post_delay += $delay;
660 $publish_time = time();
663 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
664 $next_publish = max($last_publish + (60 * $min_posting), time());
665 if ($publish_time < $next_publish) {
666 $publish_time = $next_publish;
668 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
670 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
671 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
676 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
677 self::adjustPollFrequency($contact, $creation_dates);
680 return ["header" => $author, "items" => $items];
684 * Automatically adjust the poll frequency according to the post frequency
686 * @param array $contact
687 * @param array $creation_dates
690 private static function adjustPollFrequency(array $contact, array $creation_dates)
692 if ($contact['network'] != Protocol::FEED) {
693 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
697 if (!empty($creation_dates)) {
698 // Count the post frequency and the earliest and latest post date
702 $oldest_date = $newest_date = '';
704 foreach ($creation_dates as $date) {
705 $timestamp = strtotime($date);
706 $day = intdiv($timestamp, 86400);
707 $hour = $timestamp % 86400;
709 // Only have a look at values from the last seven days
710 if (((time() / 86400) - $day) < 7) {
711 if (empty($frequency[$day])) {
712 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
714 ++$frequency[$day]['count'];
715 if ($frequency[$day]['low'] > $hour) {
716 $frequency[$day]['low'] = $hour;
718 if ($frequency[$day]['high'] < $hour) {
719 $frequency[$day]['high'] = $hour;
723 if ($oldest > $day) {
725 $oldest_date = $date;
728 if ($newest < $day) {
730 $newest_date = $date;
734 if (count($creation_dates) == 1) {
735 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
736 $priority = 8; // Poll once a day
739 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
740 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']]);
741 $priority = 10; // Poll every month
744 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
745 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']]);
746 $priority = 9; // Poll every week
749 if (empty($priority) && empty($frequency)) {
750 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']]);
751 $priority = 8; // Poll once a day
754 if (empty($priority)) {
755 // Calculate the highest "posts per day" value
757 foreach ($frequency as $entry) {
758 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
762 // We take the earliest and latest post day and interpolate the number of post per day
763 // that would had been created with this post frequency
765 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
766 $duration = max($entry['high'] - $entry['low'], 14400);
767 $ppd = (86400 / $duration) * $entry['count'];
773 $priority = 1; // Poll every quarter hour
774 } elseif ($max > 24) {
775 $priority = 2; // Poll half an hour
776 } elseif ($max > 12) {
777 $priority = 3; // Poll hourly
778 } elseif ($max > 8) {
779 $priority = 4; // Poll every two hours
780 } elseif ($max > 4) {
781 $priority = 5; // Poll every three hours
782 } elseif ($max > 2) {
783 $priority = 6; // Poll every six hours
785 $priority = 7; // Poll twice a day
787 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
790 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
791 $priority = 8; // Poll once a day
794 if ($contact['rating'] != $priority) {
795 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
796 Contact::update(['rating' => $priority], ['id' => $contact['id']]);
801 * Get the poll interval for the given contact array
803 * @param array $contact
804 * @return int Poll interval in minutes
806 public static function getPollInterval(array $contact)
808 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
809 $ratings = [0, 3, 7, 8, 9, 10];
810 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
811 $rating = $contact['rating'];
812 } elseif (array_key_exists($contact['priority'], $ratings)) {
813 $rating = $ratings[$contact['priority']];
818 // Check once a week per default for all other networks
822 // Friendica and OStatus are checked once a day
823 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
827 // Check archived contacts or contacts with unsupported protocols once a month
828 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
836 * Based on $contact['priority'], should we poll this site now? Or later?
839 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
841 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
843 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
844 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
846 return $poll_intervals[$rating];
850 * Convert a tag array to a tag string
853 * @return string tag string
855 private static function tagToString(array $tags)
859 foreach ($tags as $tag) {
864 $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
870 private static function titleIsBody($title, $body)
872 $title = strip_tags($title);
873 $title = trim($title);
874 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
875 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
877 $body = strip_tags($body);
879 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
880 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
882 if (strlen($title) < strlen($body)) {
883 $body = substr($body, 0, strlen($title));
886 if (($title != $body) && (substr($title, -3) == "...")) {
887 $pos = strrpos($title, "...");
889 $title = substr($title, 0, $pos);
890 $body = substr($body, 0, $pos);
893 return ($title == $body);
897 * Creates the Atom feed for a given nickname
900 * - activity (default): all the public posts
901 * - posts: all the public top-level posts
902 * - comments: all the public replies
904 * Updates the provided last_update parameter if the result comes from the
905 * cache or it is empty
907 * @param string $owner_nick Nickname of the feed owner
908 * @param string $last_update Date of the last update
909 * @param integer $max_items Number of maximum items to fetch
910 * @param string $filter Feed items filter (activity, posts or comments)
911 * @param boolean $nocache Wether to bypass caching
913 * @return string Atom feed
914 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
915 * @throws \ImagickException
917 public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
919 $stamp = microtime(true);
921 $owner = User::getOwnerDataByNick($owner_nick);
926 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
928 // Display events in the users's timezone
929 if (strlen($owner['timezone'])) {
930 DI::app()->setTimeZone($owner['timezone']);
933 $previous_created = $last_update;
935 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
936 if ((time() - strtotime($owner['last-item'])) < 15*60) {
937 $result = DI::cache()->get($cachekey);
938 if (!$nocache && !is_null($result)) {
939 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
940 return $result['feed'];
944 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
945 $authorid = Contact::getIdForURL($owner["url"]);
947 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
948 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
949 $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
950 Item::PRIVATE, Protocol::ACTIVITYPUB,
951 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
953 if ($filter === 'comments') {
954 $condition[0] .= " AND `gravity` = ? ";
955 $condition[] = GRAVITY_COMMENT;
958 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
959 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
960 $condition[] = $owner["id"];
961 $condition[] = $authorid;
964 $params = ['order' => ['received' => true], 'limit' => $max_items];
966 if ($filter === 'posts') {
967 $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
969 $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
972 $items = Post::toArray($ret);
974 $doc = new DOMDocument('1.0', 'utf-8');
975 $doc->formatOutput = true;
977 $root = self::addHeader($doc, $owner, $filter);
979 foreach ($items as $item) {
980 $entry = self::noteEntry($doc, $item, $owner);
981 $root->appendChild($entry);
983 if ($last_update < $item['created']) {
984 $last_update = $item['created'];
988 $feeddata = trim($doc->saveXML());
990 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
991 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
993 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
999 * Adds the header elements to the XML document
1001 * @param DOMDocument $doc XML document
1002 * @param array $owner Contact data of the poster
1003 * @param string $filter The related feed filter (activity, posts or comments)
1005 * @return object header root element
1006 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1008 private static function addHeader(DOMDocument $doc, array $owner, $filter)
1010 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1011 $doc->appendChild($root);
1014 $selfUri = '/feed/' . $owner["nick"] . '/';
1017 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1018 $selfUri .= $filter;
1021 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1024 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1025 $selfUri .= $filter;
1029 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1030 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1031 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1032 XML::addElement($doc, $root, "title", $title);
1033 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1034 XML::addElement($doc, $root, "logo", User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1035 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1037 $author = self::addAuthor($doc, $owner);
1038 $root->appendChild($author);
1040 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1041 XML::addElement($doc, $root, "link", "", $attributes);
1043 OStatus::hublinks($doc, $root, $owner["nick"]);
1045 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1046 XML::addElement($doc, $root, "link", "", $attributes);
1052 * Adds the author element to the XML document
1054 * @param DOMDocument $doc XML document
1055 * @param array $owner Contact data of the poster
1057 * @return \DOMElement author element
1058 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1060 private static function addAuthor(DOMDocument $doc, array $owner)
1062 $author = $doc->createElement("author");
1063 XML::addElement($doc, $author, "uri", $owner["url"]);
1064 XML::addElement($doc, $author, "name", $owner["nick"]);
1065 XML::addElement($doc, $author, "email", $owner["addr"]);
1071 * Adds a regular entry element
1073 * @param DOMDocument $doc XML document
1074 * @param array $item Data of the item that is to be posted
1075 * @param array $owner Contact data of the poster
1076 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1078 * @return \DOMElement Entry element
1079 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1080 * @throws \ImagickException
1082 private static function noteEntry(DOMDocument $doc, array $item, array $owner)
1084 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1085 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1088 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1090 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1092 self::entryFooter($doc, $entry, $item, $owner);
1098 * Adds elements to the XML document
1100 * @param DOMDocument $doc XML document
1101 * @param \DOMElement $entry Entry element where the content is added
1102 * @param array $item Data of the item that is to be posted
1103 * @param array $owner Contact data of the poster
1104 * @param string $title Title for the post
1105 * @param string $verb The activity verb
1106 * @param bool $complete Add the "status_net" element?
1107 * @param bool $feed_mode Behave like a regular feed for users if true
1109 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1111 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
1114 $verb = OStatus::constructVerb($item);
1117 XML::addElement($doc, $entry, "id", $item["uri"]);
1118 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1120 $body = OStatus::formatPicturePost($item['body'], $item['uri-id']);
1122 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1124 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1126 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1127 "href" => DI::baseUrl()."/display/".$item["guid"]]
1130 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1131 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1135 * Adds the elements at the foot of an entry to the XML document
1137 * @param DOMDocument $doc XML document
1138 * @param object $entry The entry element where the elements are added
1139 * @param array $item Data of the item that is to be posted
1140 * @param array $owner Contact data of the poster
1141 * @param bool $complete default true
1143 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1145 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1149 if ($item['gravity'] != GRAVITY_PARENT) {
1150 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1152 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1154 if (DBA::isResult($thrparent)) {
1155 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1156 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1157 $parent_plink = $thrparent['plink'];
1158 } elseif (DBA::isResult($parent)) {
1159 $mentioned[$parent['author-link']] = $parent['author-link'];
1160 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1161 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1163 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1166 if (isset($parent_plink)) {
1168 'ref' => $item['thr-parent'],
1169 'href' => $parent_plink];
1170 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1174 'href' => $parent_plink];
1175 XML::addElement($doc, $entry, 'link', '', $attributes);
1179 // uri-id isn't present for follow entry pseudo-items
1180 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1181 foreach ($tags as $tag) {
1182 $mentioned[$tag['url']] = $tag['url'];
1185 foreach ($tags as $tag) {
1186 if ($tag['type'] == Tag::HASHTAG) {
1187 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1191 OStatus::getAttachment($doc, $entry, $item);
1195 * Fetch or create title for feed entry
1197 * @param array $item
1198 * @return string title
1200 private static function getTitle(array $item)
1202 if ($item['title'] != '') {
1203 return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1206 // Fetch information about the post
1207 $siteinfo = BBCode::getAttachedData($item["body"]);
1208 if (isset($siteinfo["title"])) {
1209 return $siteinfo["title"];
1212 // If no bookmark is found then take the first line
1213 // Remove the share element before fetching the first line
1214 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1216 $title = BBCode::toPlaintext($title)."\n";
1217 $pos = strpos($title, "\n");
1219 if (($pos == 0) || ($pos > 100)) {
1224 return substr($title, 0, $pos) . $trailer;