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;
313 $item["guid"] = $guid;
316 if (empty($item["uri"])) {
317 $item["uri"] = $item["plink"];
320 $orig_plink = $item["plink"];
323 $item["plink"] = DI::httpClient()->finalUrl($item["plink"]);
324 } catch (TransferException $exception) {
325 Logger::notice('Item URL couldn\'t get expanded', ['url' => $item["plink"], 'exception' => $exception]);
328 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
330 if (empty($item["title"])) {
331 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
334 if (empty($item["title"])) {
335 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
338 if (empty($item["title"])) {
339 $item["title"] = XML::getFirstNodeValue($xpath, 'itunes:title/text()', $entry);
342 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
344 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
346 if (empty($published)) {
347 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
350 if (empty($published)) {
351 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
354 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
356 if (empty($updated) && !empty($published)) {
357 $updated = $published;
360 if (empty($published) && !empty($updated)) {
361 $published = $updated;
364 if ($published != "") {
365 $item["created"] = $published;
368 if ($updated != "") {
369 $item["edited"] = $updated;
373 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
374 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
375 $previous = Post::selectFirst(['id', 'created'], $condition);
376 if (DBA::isResult($previous)) {
377 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
378 $creation_dates[] = $previous['created'];
379 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
382 $creation_dates[] = DateTimeFormat::utc($item['created']);
385 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
387 if (empty($creator)) {
388 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
391 if (empty($creator)) {
392 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
395 if ($creator != "") {
396 $item["author-name"] = $creator;
399 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
401 if ($creator != "") {
402 $item["author-name"] = $creator;
406 // <category>Ausland</category>
407 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
411 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
412 foreach ($enclosures as $enclosure) {
417 foreach ($enclosure->attributes as $attribute) {
418 if (in_array($attribute->name, ["url", "href"])) {
419 $href = $attribute->textContent;
420 } elseif ($attribute->name == "length") {
421 $length = (int)$attribute->textContent;
422 } elseif ($attribute->name == "type") {
423 $type = $attribute->textContent;
428 $attachment = ['type' => Post\Media::UNKNOWN, 'url' => $href, 'mimetype' => $type, 'size' => $length];
430 $attachment = Post\Media::fetchAdditionalData($attachment);
432 // By now we separate the visible media types (audio, video, image) from the rest
433 // In the future we should try to avoid the DOCUMENT type and only use the real one - but not in the RC phase.
434 if (!in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO])) {
435 $attachment['type'] = Post\Media::DOCUMENT;
437 $attachments[] = $attachment;
442 $categories = $xpath->query("category", $entry);
443 foreach ($categories as $category) {
444 $taglist[] = $category->nodeValue;
447 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
450 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
453 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
455 if (empty($summary)) {
456 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
464 if ($body == $summary) {
468 // remove the content of the title if it is identically to the body
469 // This helps with auto generated titles e.g. from tumblr
470 if (self::titleIsBody($item["title"], $body)) {
473 $item["body"] = HTML::toBBCode($body, $basepath);
475 // Remove tracking pixels
476 $item["body"] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item["body"]);
478 if (($item["body"] == '') && ($item["title"] != '')) {
479 $item["body"] = $item["title"];
484 $item['attachments'] = $attachments;
487 } elseif (!Item::isValid($item)) {
488 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
490 } elseif (Item::isTooOld($item)) {
491 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
496 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
497 // Handle enclosures and treat them as preview picture
498 foreach ($attachments as $attachment) {
499 if ($attachment["mimetype"] == "image/jpeg") {
500 $preview = $attachment["url"];
504 // Remove a possible link to the item itself
505 $item["body"] = str_replace($item["plink"], '', $item["body"]);
506 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
508 // Replace the content when the title is longer than the body
509 $replace = (strlen($item["title"]) > strlen($item["body"]));
511 // Replace it, when there is an image in the body
512 if (strstr($item["body"], '[/img]')) {
516 // Replace it, when there is a link in the body
517 if (strstr($item["body"], '[/url]')) {
521 $saved_body = $item["body"];
522 $saved_title = $item["title"];
525 $item["body"] = trim($item["title"]);
528 $data = ParseUrl::getSiteinfoCached($item['plink']);
529 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
530 // When the fetched page info text is longer than the body, we do try to enhance the body
531 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
532 // The body is not part of the fetched page info title or page info text. So we add the text to the body
533 $item['body'] .= "\n\n" . $data['text'];
535 // Else we replace the body with the page info text
536 $item['body'] = $data['text'];
540 $data = PageInfo::queryUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
543 // Take the data that was provided by the feed if the query is empty
544 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
545 $data['title'] = $saved_title;
546 $item["body"] = $saved_body;
549 $data_text = strip_tags(trim($data['text'] ?? ''));
550 $item_body = strip_tags(trim($item['body'] ?? ''));
552 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
556 // We always strip the title since it will be added in the page information
558 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromData($data, false);
559 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
560 $item["object-type"] = Activity\ObjectType::BOOKMARK;
563 foreach (['audio', 'video'] as $elementname) {
564 if (!empty($data[$elementname])) {
565 foreach ($data[$elementname] as $element) {
566 if (!empty($element['src'])) {
567 $src = $element['src'];
568 } elseif (!empty($element['content'])) {
569 $src = $element['content'];
575 'type' => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
577 'preview' => $element['image'] ?? null,
578 'mimetype' => $element['contenttype'] ?? null,
579 'name' => $element['name'] ?? null,
580 'description' => $element['description'] ?? null,
587 if (!empty($summary)) {
588 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
591 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
592 if (empty($taglist)) {
593 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
595 $item["body"] .= "\n" . self::tagToString($taglist);
600 // Add the link to the original feed entry if not present in feed
601 if (($item['plink'] != '') && !strstr($item["body"], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
602 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
606 if (empty($item['title'])) {
607 $item['post-type'] = Item::PT_NOTE;
610 Logger::info('Stored feed', ['item' => $item]);
612 $notify = Item::isRemoteSelf($contact, $item);
614 // Distributed items should have a well formatted URI.
615 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
617 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
618 $item['uri'] = Item::newURI($item['uid'], $item['guid']);
619 unset($item['thr-parent']);
620 unset($item['parent-uri']);
622 // Set the delivery priority for "remote self" to "medium"
623 $notify = PRIORITY_MEDIUM;
626 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
627 if (!Post::exists($condition) && !Post\Delayed::exists($item["uri"], $item['uid'])) {
629 Post\Delayed::publish($item, $notify, $taglist, $attachments);
631 $postings[] = ['item' => $item, 'notify' => $notify,
632 'taglist' => $taglist, 'attachments' => $attachments];
635 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item["uri"]]);
639 if (!empty($postings)) {
640 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
641 $total = count($postings);
643 // Posts shouldn't be delayed more than a day
644 $interval = min(1440, self::getPollInterval($contact));
645 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
646 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
653 foreach ($postings as $posting) {
655 $publish_time = time() + $post_delay;
656 $post_delay += $delay;
658 $publish_time = time();
661 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
662 $next_publish = max($last_publish + (60 * $min_posting), time());
663 if ($publish_time < $next_publish) {
664 $publish_time = $next_publish;
666 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
668 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
669 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
674 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
675 self::adjustPollFrequency($contact, $creation_dates);
678 return ["header" => $author, "items" => $items];
682 * Automatically adjust the poll frequency according to the post frequency
684 * @param array $contact
685 * @param array $creation_dates
688 private static function adjustPollFrequency(array $contact, array $creation_dates)
690 if ($contact['network'] != Protocol::FEED) {
691 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
695 if (!empty($creation_dates)) {
696 // Count the post frequency and the earliest and latest post date
700 $oldest_date = $newest_date = '';
702 foreach ($creation_dates as $date) {
703 $timestamp = strtotime($date);
704 $day = intdiv($timestamp, 86400);
705 $hour = $timestamp % 86400;
707 // Only have a look at values from the last seven days
708 if (((time() / 86400) - $day) < 7) {
709 if (empty($frequency[$day])) {
710 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
712 ++$frequency[$day]['count'];
713 if ($frequency[$day]['low'] > $hour) {
714 $frequency[$day]['low'] = $hour;
716 if ($frequency[$day]['high'] < $hour) {
717 $frequency[$day]['high'] = $hour;
721 if ($oldest > $day) {
723 $oldest_date = $date;
726 if ($newest < $day) {
728 $newest_date = $date;
732 if (count($creation_dates) == 1) {
733 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
734 $priority = 8; // Poll once a day
737 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
738 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']]);
739 $priority = 10; // Poll every month
742 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
743 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']]);
744 $priority = 9; // Poll every week
747 if (empty($priority) && empty($frequency)) {
748 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']]);
749 $priority = 8; // Poll once a day
752 if (empty($priority)) {
753 // Calculate the highest "posts per day" value
755 foreach ($frequency as $entry) {
756 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
760 // We take the earliest and latest post day and interpolate the number of post per day
761 // that would had been created with this post frequency
763 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
764 $duration = max($entry['high'] - $entry['low'], 14400);
765 $ppd = (86400 / $duration) * $entry['count'];
771 $priority = 1; // Poll every quarter hour
772 } elseif ($max > 24) {
773 $priority = 2; // Poll half an hour
774 } elseif ($max > 12) {
775 $priority = 3; // Poll hourly
776 } elseif ($max > 8) {
777 $priority = 4; // Poll every two hours
778 } elseif ($max > 4) {
779 $priority = 5; // Poll every three hours
780 } elseif ($max > 2) {
781 $priority = 6; // Poll every six hours
783 $priority = 7; // Poll twice a day
785 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
788 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
789 $priority = 8; // Poll once a day
792 if ($contact['rating'] != $priority) {
793 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
794 Contact::update(['rating' => $priority], ['id' => $contact['id']]);
799 * Get the poll interval for the given contact array
801 * @param array $contact
802 * @return int Poll interval in minutes
804 public static function getPollInterval(array $contact)
806 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
807 $ratings = [0, 3, 7, 8, 9, 10];
808 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
809 $rating = $contact['rating'];
810 } elseif (array_key_exists($contact['priority'], $ratings)) {
811 $rating = $ratings[$contact['priority']];
816 // Check once a week per default for all other networks
820 // Friendica and OStatus are checked once a day
821 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
825 // Check archived contacts or contacts with unsupported protocols once a month
826 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
834 * Based on $contact['priority'], should we poll this site now? Or later?
837 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
839 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
841 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
842 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
844 return $poll_intervals[$rating];
848 * Convert a tag array to a tag string
851 * @return string tag string
853 private static function tagToString(array $tags)
857 foreach ($tags as $tag) {
862 $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
868 private static function titleIsBody($title, $body)
870 $title = strip_tags($title);
871 $title = trim($title);
872 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
873 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
875 $body = strip_tags($body);
877 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
878 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
880 if (strlen($title) < strlen($body)) {
881 $body = substr($body, 0, strlen($title));
884 if (($title != $body) && (substr($title, -3) == "...")) {
885 $pos = strrpos($title, "...");
887 $title = substr($title, 0, $pos);
888 $body = substr($body, 0, $pos);
891 return ($title == $body);
895 * Creates the Atom feed for a given nickname
898 * - activity (default): all the public posts
899 * - posts: all the public top-level posts
900 * - comments: all the public replies
902 * Updates the provided last_update parameter if the result comes from the
903 * cache or it is empty
905 * @param string $owner_nick Nickname of the feed owner
906 * @param string $last_update Date of the last update
907 * @param integer $max_items Number of maximum items to fetch
908 * @param string $filter Feed items filter (activity, posts or comments)
909 * @param boolean $nocache Wether to bypass caching
911 * @return string Atom feed
912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
913 * @throws \ImagickException
915 public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
917 $stamp = microtime(true);
919 $owner = User::getOwnerDataByNick($owner_nick);
924 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
926 // Display events in the users's timezone
927 if (strlen($owner['timezone'])) {
928 DI::app()->setTimeZone($owner['timezone']);
931 $previous_created = $last_update;
933 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
934 if ((time() - strtotime($owner['last-item'])) < 15*60) {
935 $result = DI::cache()->get($cachekey);
936 if (!$nocache && !is_null($result)) {
937 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
938 return $result['feed'];
942 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
943 $authorid = Contact::getIdForURL($owner["url"]);
945 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
946 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
947 $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
948 Item::PRIVATE, Protocol::ACTIVITYPUB,
949 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
951 if ($filter === 'comments') {
952 $condition[0] .= " AND `gravity` = ? ";
953 $condition[] = GRAVITY_COMMENT;
956 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
957 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
958 $condition[] = $owner["id"];
959 $condition[] = $authorid;
962 $params = ['order' => ['received' => true], 'limit' => $max_items];
964 if ($filter === 'posts') {
965 $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
967 $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
970 $items = Post::toArray($ret);
972 $doc = new DOMDocument('1.0', 'utf-8');
973 $doc->formatOutput = true;
975 $root = self::addHeader($doc, $owner, $filter);
977 foreach ($items as $item) {
978 $entry = self::noteEntry($doc, $item, $owner);
979 $root->appendChild($entry);
981 if ($last_update < $item['created']) {
982 $last_update = $item['created'];
986 $feeddata = trim($doc->saveXML());
988 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
989 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
991 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
997 * Adds the header elements to the XML document
999 * @param DOMDocument $doc XML document
1000 * @param array $owner Contact data of the poster
1001 * @param string $filter The related feed filter (activity, posts or comments)
1003 * @return object header root element
1004 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1006 private static function addHeader(DOMDocument $doc, array $owner, $filter)
1008 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1009 $doc->appendChild($root);
1012 $selfUri = '/feed/' . $owner["nick"] . '/';
1015 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1016 $selfUri .= $filter;
1019 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1022 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1023 $selfUri .= $filter;
1027 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1028 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1029 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1030 XML::addElement($doc, $root, "title", $title);
1031 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1032 XML::addElement($doc, $root, "logo", User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1033 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1035 $author = self::addAuthor($doc, $owner);
1036 $root->appendChild($author);
1038 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1039 XML::addElement($doc, $root, "link", "", $attributes);
1041 OStatus::hublinks($doc, $root, $owner["nick"]);
1043 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1044 XML::addElement($doc, $root, "link", "", $attributes);
1050 * Adds the author element to the XML document
1052 * @param DOMDocument $doc XML document
1053 * @param array $owner Contact data of the poster
1055 * @return \DOMElement author element
1056 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1058 private static function addAuthor(DOMDocument $doc, array $owner)
1060 $author = $doc->createElement("author");
1061 XML::addElement($doc, $author, "uri", $owner["url"]);
1062 XML::addElement($doc, $author, "name", $owner["nick"]);
1063 XML::addElement($doc, $author, "email", $owner["addr"]);
1069 * Adds a regular entry element
1071 * @param DOMDocument $doc XML document
1072 * @param array $item Data of the item that is to be posted
1073 * @param array $owner Contact data of the poster
1074 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1076 * @return \DOMElement Entry element
1077 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1078 * @throws \ImagickException
1080 private static function noteEntry(DOMDocument $doc, array $item, array $owner)
1082 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1083 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1086 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1088 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1090 self::entryFooter($doc, $entry, $item, $owner);
1096 * Adds elements to the XML document
1098 * @param DOMDocument $doc XML document
1099 * @param \DOMElement $entry Entry element where the content is added
1100 * @param array $item Data of the item that is to be posted
1101 * @param array $owner Contact data of the poster
1102 * @param string $title Title for the post
1103 * @param string $verb The activity verb
1104 * @param bool $complete Add the "status_net" element?
1105 * @param bool $feed_mode Behave like a regular feed for users if true
1107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1109 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
1112 $verb = OStatus::constructVerb($item);
1115 XML::addElement($doc, $entry, "id", $item["uri"]);
1116 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1118 $body = OStatus::formatPicturePost($item['body'], $item['uri-id']);
1120 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1122 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1124 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1125 "href" => DI::baseUrl()."/display/".$item["guid"]]
1128 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1129 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1133 * Adds the elements at the foot of an entry to the XML document
1135 * @param DOMDocument $doc XML document
1136 * @param object $entry The entry element where the elements are added
1137 * @param array $item Data of the item that is to be posted
1138 * @param array $owner Contact data of the poster
1139 * @param bool $complete default true
1141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1143 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1147 if ($item['gravity'] != GRAVITY_PARENT) {
1148 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1150 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1152 if (DBA::isResult($thrparent)) {
1153 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1154 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1155 $parent_plink = $thrparent['plink'];
1156 } elseif (DBA::isResult($parent)) {
1157 $mentioned[$parent['author-link']] = $parent['author-link'];
1158 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1159 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1161 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1164 if (isset($parent_plink)) {
1166 'ref' => $item['thr-parent'],
1167 'href' => $parent_plink];
1168 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1172 'href' => $parent_plink];
1173 XML::addElement($doc, $entry, 'link', '', $attributes);
1177 // uri-id isn't present for follow entry pseudo-items
1178 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1179 foreach ($tags as $tag) {
1180 $mentioned[$tag['url']] = $tag['url'];
1183 foreach ($tags as $tag) {
1184 if ($tag['type'] == Tag::HASHTAG) {
1185 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1189 OStatus::getAttachment($doc, $entry, $item);
1193 * Fetch or create title for feed entry
1195 * @param array $item
1196 * @return string title
1198 private static function getTitle(array $item)
1200 if ($item['title'] != '') {
1201 return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1204 // Fetch information about the post
1205 $siteinfo = BBCode::getAttachedData($item["body"]);
1206 if (isset($siteinfo["title"])) {
1207 return $siteinfo["title"];
1210 // If no bookmark is found then take the first line
1211 // Remove the share element before fetching the first line
1212 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1214 $title = BBCode::toPlaintext($title)."\n";
1215 $pos = strpos($title, "\n");
1217 if (($pos == 0) || ($pos > 100)) {
1222 return substr($title, 0, $pos) . $trailer;