3 * @copyright Copyright (C) 2010-2021, 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()');
200 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
202 if (empty($author["author-name"])) {
203 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
206 if (empty($author["author-name"])) {
207 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
210 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
212 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
214 $entries = $xpath->query('/rss/channel/item');
218 $author["author-link"] = $contact["url"];
220 if (empty($author["author-name"])) {
221 $author["author-name"] = $contact["name"];
224 $author["author-avatar"] = $contact["thumb"];
226 $author["owner-link"] = $contact["url"];
227 $author["owner-name"] = $contact["name"];
228 $author["owner-avatar"] = $contact["thumb"];
232 $header["uid"] = $importer["uid"] ?? 0;
233 $header["network"] = Protocol::FEED;
235 $header["origin"] = 0;
236 $header["gravity"] = GRAVITY_PARENT;
237 $header["private"] = Item::PUBLIC;
238 $header["verb"] = Activity::POST;
239 $header["object-type"] = Activity\ObjectType::NOTE;
240 $header["post-type"] = Item::PT_ARTICLE;
242 $header["contact-id"] = $contact["id"] ?? 0;
244 if (!is_object($entries)) {
245 Logger::info("There are no entries in this feed.");
250 $creation_dates = [];
252 // Limit the number of items that are about to be fetched
253 $total_items = ($entries->length - 1);
254 $max_items = DI::config()->get('system', 'max_feed_items');
255 if (($max_items > 0) && ($total_items > $max_items)) {
256 $total_items = $max_items;
261 // Importing older entries first
262 for ($i = $total_items; $i >= 0; --$i) {
263 $entry = $entries->item($i);
265 $item = array_merge($header, $author);
267 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
268 if (!is_object($alternate)) {
269 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
271 if (is_object($alternate)) {
272 foreach ($alternate as $attribute) {
273 if ($attribute->name == "href") {
274 $item["plink"] = $attribute->textContent;
279 if (empty($item["plink"])) {
280 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
283 if (empty($item["plink"])) {
284 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
287 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
289 if (empty($item["uri"])) {
290 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
293 if (empty($item["uri"])) {
294 $item["uri"] = $item["plink"];
297 // Add the base path if missing
298 $item["uri"] = Network::addBasePath($item["uri"], $basepath);
299 $item["plink"] = Network::addBasePath($item["plink"], $basepath);
301 $orig_plink = $item["plink"];
304 $item["plink"] = DI::httpClient()->finalUrl($item["plink"]);
305 } catch (TransferException $exception) {
306 Logger::notice('Item URL couldn\'t get expanded', ['url' => $item["plink"], 'exception' => $exception]);
309 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
311 if (empty($item["title"])) {
312 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
314 if (empty($item["title"])) {
315 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
318 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
320 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
322 if (empty($published)) {
323 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
326 if (empty($published)) {
327 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
330 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
332 if (empty($updated) && !empty($published)) {
333 $updated = $published;
336 if (empty($published) && !empty($updated)) {
337 $published = $updated;
340 if ($published != "") {
341 $item["created"] = $published;
344 if ($updated != "") {
345 $item["edited"] = $updated;
349 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
350 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
351 $previous = Post::selectFirst(['id', 'created'], $condition);
352 if (DBA::isResult($previous)) {
353 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
354 $creation_dates[] = $previous['created'];
355 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
358 $creation_dates[] = DateTimeFormat::utc($item['created']);
361 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
363 if (empty($creator)) {
364 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
367 if (empty($creator)) {
368 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
371 if ($creator != "") {
372 $item["author-name"] = $creator;
375 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
377 if ($creator != "") {
378 $item["author-name"] = $creator;
382 // <category>Ausland</category>
383 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
387 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
388 foreach ($enclosures as $enclosure) {
393 foreach ($enclosure->attributes as $attribute) {
394 if (in_array($attribute->name, ["url", "href"])) {
395 $href = $attribute->textContent;
396 } elseif ($attribute->name == "length") {
397 $length = (int)$attribute->textContent;
398 } elseif ($attribute->name == "type") {
399 $type = $attribute->textContent;
404 $attachments[] = ['type' => Post\Media::DOCUMENT, 'url' => $href, 'mimetype' => $type, 'size' => $length];
409 $categories = $xpath->query("category", $entry);
410 foreach ($categories as $category) {
411 $taglist[] = $category->nodeValue;
414 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
417 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
420 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
422 if (empty($summary)) {
423 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
431 if ($body == $summary) {
435 // remove the content of the title if it is identically to the body
436 // This helps with auto generated titles e.g. from tumblr
437 if (self::titleIsBody($item["title"], $body)) {
440 $item["body"] = HTML::toBBCode($body, $basepath);
442 // Remove tracking pixels
443 $item["body"] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item["body"]);
445 if (($item["body"] == '') && ($item["title"] != '')) {
446 $item["body"] = $item["title"];
453 } elseif (!Item::isValid($item)) {
454 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
456 } elseif (Item::isTooOld($item)) {
457 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
462 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
463 // Handle enclosures and treat them as preview picture
464 foreach ($attachments as $attachment) {
465 if ($attachment["mimetype"] == "image/jpeg") {
466 $preview = $attachment["url"];
470 // Remove a possible link to the item itself
471 $item["body"] = str_replace($item["plink"], '', $item["body"]);
472 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
474 // Replace the content when the title is longer than the body
475 $replace = (strlen($item["title"]) > strlen($item["body"]));
477 // Replace it, when there is an image in the body
478 if (strstr($item["body"], '[/img]')) {
482 // Replace it, when there is a link in the body
483 if (strstr($item["body"], '[/url]')) {
487 $saved_body = $item["body"];
488 $saved_title = $item["title"];
491 $item["body"] = trim($item["title"]);
494 $data = ParseUrl::getSiteinfoCached($item['plink']);
495 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
496 // When the fetched page info text is longer than the body, we do try to enhance the body
497 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
498 // The body is not part of the fetched page info title or page info text. So we add the text to the body
499 $item['body'] .= "\n\n" . $data['text'];
501 // Else we replace the body with the page info text
502 $item['body'] = $data['text'];
506 $data = PageInfo::queryUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
509 // Take the data that was provided by the feed if the query is empty
510 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
511 $data['title'] = $saved_title;
512 $item["body"] = $saved_body;
515 $data_text = strip_tags(trim($data['text'] ?? ''));
516 $item_body = strip_tags(trim($item['body'] ?? ''));
518 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
522 // We always strip the title since it will be added in the page information
524 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromData($data, false);
525 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
526 $item["object-type"] = Activity\ObjectType::BOOKMARK;
529 foreach (['audio', 'video'] as $elementname) {
530 if (!empty($data[$elementname])) {
531 foreach ($data[$elementname] as $element) {
532 if (!empty($element['src'])) {
533 $src = $element['src'];
534 } elseif (!empty($element['content'])) {
535 $src = $element['content'];
541 'type' => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
543 'preview' => $element['image'] ?? null,
544 'mimetype' => $element['contenttype'] ?? null,
545 'name' => $element['name'] ?? null,
546 'description' => $element['description'] ?? null,
553 if (!empty($summary)) {
554 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
557 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
558 if (empty($taglist)) {
559 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
561 $item["body"] .= "\n" . self::tagToString($taglist);
566 // Add the link to the original feed entry if not present in feed
567 if (($item['plink'] != '') && !strstr($item["body"], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
568 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
572 if (empty($item['title'])) {
573 $item['post-type'] = Item::PT_NOTE;
576 Logger::info('Stored feed', ['item' => $item]);
578 $notify = Item::isRemoteSelf($contact, $item);
580 // Distributed items should have a well formatted URI.
581 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
583 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
584 $item['uri'] = Item::newURI($item['uid'], $item['guid']);
585 unset($item['thr-parent']);
586 unset($item['parent-uri']);
588 // Set the delivery priority for "remote self" to "medium"
589 $notify = PRIORITY_MEDIUM;
592 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
593 if (!Post::exists($condition) && !Post\Delayed::exists($item["uri"], $item['uid'])) {
595 Post\Delayed::publish($item, $notify, $taglist, $attachments);
597 $postings[] = ['item' => $item, 'notify' => $notify,
598 'taglist' => $taglist, 'attachments' => $attachments];
601 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item["uri"]]);
605 if (!empty($postings)) {
606 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
607 $total = count($postings);
609 // Posts shouldn't be delayed more than a day
610 $interval = min(1440, self::getPollInterval($contact));
611 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
612 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
619 foreach ($postings as $posting) {
621 $publish_time = time() + $post_delay;
622 $post_delay += $delay;
624 $publish_time = time();
627 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
628 $next_publish = max($last_publish + (60 * $min_posting), time());
629 if ($publish_time < $next_publish) {
630 $publish_time = $next_publish;
632 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
634 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
635 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
640 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
641 self::adjustPollFrequency($contact, $creation_dates);
644 return ["header" => $author, "items" => $items];
648 * Automatically adjust the poll frequency according to the post frequency
650 * @param array $contact
651 * @param array $creation_dates
654 private static function adjustPollFrequency(array $contact, array $creation_dates)
656 if ($contact['network'] != Protocol::FEED) {
657 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
661 if (!empty($creation_dates)) {
662 // Count the post frequency and the earliest and latest post date
666 $oldest_date = $newest_date = '';
668 foreach ($creation_dates as $date) {
669 $timestamp = strtotime($date);
670 $day = intdiv($timestamp, 86400);
671 $hour = $timestamp % 86400;
673 // Only have a look at values from the last seven days
674 if (((time() / 86400) - $day) < 7) {
675 if (empty($frequency[$day])) {
676 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
678 ++$frequency[$day]['count'];
679 if ($frequency[$day]['low'] > $hour) {
680 $frequency[$day]['low'] = $hour;
682 if ($frequency[$day]['high'] < $hour) {
683 $frequency[$day]['high'] = $hour;
687 if ($oldest > $day) {
689 $oldest_date = $date;
692 if ($newest < $day) {
694 $newest_date = $date;
698 if (count($creation_dates) == 1) {
699 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
700 $priority = 8; // Poll once a day
703 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
704 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']]);
705 $priority = 10; // Poll every month
708 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
709 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']]);
710 $priority = 9; // Poll every week
713 if (empty($priority) && empty($frequency)) {
714 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']]);
715 $priority = 8; // Poll once a day
718 if (empty($priority)) {
719 // Calculate the highest "posts per day" value
721 foreach ($frequency as $entry) {
722 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
726 // We take the earliest and latest post day and interpolate the number of post per day
727 // that would had been created with this post frequency
729 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
730 $duration = max($entry['high'] - $entry['low'], 14400);
731 $ppd = (86400 / $duration) * $entry['count'];
737 $priority = 1; // Poll every quarter hour
738 } elseif ($max > 24) {
739 $priority = 2; // Poll half an hour
740 } elseif ($max > 12) {
741 $priority = 3; // Poll hourly
742 } elseif ($max > 8) {
743 $priority = 4; // Poll every two hours
744 } elseif ($max > 4) {
745 $priority = 5; // Poll every three hours
746 } elseif ($max > 2) {
747 $priority = 6; // Poll every six hours
749 $priority = 7; // Poll twice a day
751 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
754 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
755 $priority = 8; // Poll once a day
758 if ($contact['rating'] != $priority) {
759 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
760 Contact::update(['rating' => $priority], ['id' => $contact['id']]);
765 * Get the poll interval for the given contact array
767 * @param array $contact
768 * @return int Poll interval in minutes
770 public static function getPollInterval(array $contact)
772 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
773 $ratings = [0, 3, 7, 8, 9, 10];
774 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
775 $rating = $contact['rating'];
776 } elseif (array_key_exists($contact['priority'], $ratings)) {
777 $rating = $ratings[$contact['priority']];
782 // Check once a week per default for all other networks
786 // Friendica and OStatus are checked once a day
787 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
791 // Check archived contacts or contacts with unsupported protocols once a month
792 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
800 * Based on $contact['priority'], should we poll this site now? Or later?
803 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
805 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
807 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
808 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
810 return $poll_intervals[$rating];
814 * Convert a tag array to a tag string
817 * @return string tag string
819 private static function tagToString(array $tags)
823 foreach ($tags as $tag) {
828 $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
834 private static function titleIsBody($title, $body)
836 $title = strip_tags($title);
837 $title = trim($title);
838 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
839 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
841 $body = strip_tags($body);
843 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
844 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
846 if (strlen($title) < strlen($body)) {
847 $body = substr($body, 0, strlen($title));
850 if (($title != $body) && (substr($title, -3) == "...")) {
851 $pos = strrpos($title, "...");
853 $title = substr($title, 0, $pos);
854 $body = substr($body, 0, $pos);
857 return ($title == $body);
861 * Creates the Atom feed for a given nickname
864 * - activity (default): all the public posts
865 * - posts: all the public top-level posts
866 * - comments: all the public replies
868 * Updates the provided last_update parameter if the result comes from the
869 * cache or it is empty
871 * @param string $owner_nick Nickname of the feed owner
872 * @param string $last_update Date of the last update
873 * @param integer $max_items Number of maximum items to fetch
874 * @param string $filter Feed items filter (activity, posts or comments)
875 * @param boolean $nocache Wether to bypass caching
877 * @return string Atom feed
878 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
879 * @throws \ImagickException
881 public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
883 $stamp = microtime(true);
885 $owner = User::getOwnerDataByNick($owner_nick);
890 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
892 $previous_created = $last_update;
894 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
895 if ((time() - strtotime($owner['last-item'])) < 15*60) {
896 $result = DI::cache()->get($cachekey);
897 if (!$nocache && !is_null($result)) {
898 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
899 return $result['feed'];
903 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
904 $authorid = Contact::getIdForURL($owner["url"]);
906 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
907 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
908 $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
909 Item::PRIVATE, Protocol::ACTIVITYPUB,
910 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
912 if ($filter === 'comments') {
913 $condition[0] .= " AND `gravity` = ? ";
914 $condition[] = GRAVITY_COMMENT;
917 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
918 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
919 $condition[] = $owner["id"];
920 $condition[] = $authorid;
923 $params = ['order' => ['received' => true], 'limit' => $max_items];
925 if ($filter === 'posts') {
926 $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
928 $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
931 $items = Post::toArray($ret);
933 $doc = new DOMDocument('1.0', 'utf-8');
934 $doc->formatOutput = true;
936 $root = self::addHeader($doc, $owner, $filter);
938 foreach ($items as $item) {
939 $entry = self::noteEntry($doc, $item, $owner);
940 $root->appendChild($entry);
942 if ($last_update < $item['created']) {
943 $last_update = $item['created'];
947 $feeddata = trim($doc->saveXML());
949 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
950 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
952 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
958 * Adds the header elements to the XML document
960 * @param DOMDocument $doc XML document
961 * @param array $owner Contact data of the poster
962 * @param string $filter The related feed filter (activity, posts or comments)
964 * @return object header root element
965 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
967 private static function addHeader(DOMDocument $doc, array $owner, $filter)
969 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
970 $doc->appendChild($root);
973 $selfUri = '/feed/' . $owner["nick"] . '/';
976 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
980 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
983 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
988 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
989 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
990 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
991 XML::addElement($doc, $root, "title", $title);
992 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
993 XML::addElement($doc, $root, "logo", User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
994 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
996 $author = self::addAuthor($doc, $owner);
997 $root->appendChild($author);
999 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1000 XML::addElement($doc, $root, "link", "", $attributes);
1002 OStatus::hublinks($doc, $root, $owner["nick"]);
1004 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1005 XML::addElement($doc, $root, "link", "", $attributes);
1011 * Adds the author element to the XML document
1013 * @param DOMDocument $doc XML document
1014 * @param array $owner Contact data of the poster
1016 * @return \DOMElement author element
1017 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1019 private static function addAuthor(DOMDocument $doc, array $owner)
1021 $author = $doc->createElement("author");
1022 XML::addElement($doc, $author, "uri", $owner["url"]);
1023 XML::addElement($doc, $author, "name", $owner["nick"]);
1024 XML::addElement($doc, $author, "email", $owner["addr"]);
1030 * Adds a regular entry element
1032 * @param DOMDocument $doc XML document
1033 * @param array $item Data of the item that is to be posted
1034 * @param array $owner Contact data of the poster
1035 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1037 * @return \DOMElement Entry element
1038 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1039 * @throws \ImagickException
1041 private static function noteEntry(DOMDocument $doc, array $item, array $owner)
1043 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1044 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1047 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1049 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1051 self::entryFooter($doc, $entry, $item, $owner);
1057 * Adds elements to the XML document
1059 * @param DOMDocument $doc XML document
1060 * @param \DOMElement $entry Entry element where the content is added
1061 * @param array $item Data of the item that is to be posted
1062 * @param array $owner Contact data of the poster
1063 * @param string $title Title for the post
1064 * @param string $verb The activity verb
1065 * @param bool $complete Add the "status_net" element?
1066 * @param bool $feed_mode Behave like a regular feed for users if true
1068 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1070 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
1073 $verb = OStatus::constructVerb($item);
1076 XML::addElement($doc, $entry, "id", $item["uri"]);
1077 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1079 $body = OStatus::formatPicturePost($item['body'], $item['uri-id']);
1081 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1083 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1085 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1086 "href" => DI::baseUrl()."/display/".$item["guid"]]
1089 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1090 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1094 * Adds the elements at the foot of an entry to the XML document
1096 * @param DOMDocument $doc XML document
1097 * @param object $entry The entry element where the elements are added
1098 * @param array $item Data of the item that is to be posted
1099 * @param array $owner Contact data of the poster
1100 * @param bool $complete default true
1102 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1104 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1108 if ($item['gravity'] != GRAVITY_PARENT) {
1109 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1111 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1113 if (DBA::isResult($thrparent)) {
1114 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1115 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1116 $parent_plink = $thrparent['plink'];
1117 } elseif (DBA::isResult($parent)) {
1118 $mentioned[$parent['author-link']] = $parent['author-link'];
1119 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1120 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1122 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1125 if (isset($parent_plink)) {
1127 'ref' => $item['thr-parent'],
1128 'href' => $parent_plink];
1129 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1133 'href' => $parent_plink];
1134 XML::addElement($doc, $entry, 'link', '', $attributes);
1138 // uri-id isn't present for follow entry pseudo-items
1139 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1140 foreach ($tags as $tag) {
1141 $mentioned[$tag['url']] = $tag['url'];
1144 foreach ($tags as $tag) {
1145 if ($tag['type'] == Tag::HASHTAG) {
1146 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1150 OStatus::getAttachment($doc, $entry, $item);
1154 * Fetch or create title for feed entry
1156 * @param array $item
1157 * @return string title
1159 private static function getTitle(array $item)
1161 if ($item['title'] != '') {
1162 return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1165 // Fetch information about the post
1166 $siteinfo = BBCode::getAttachedData($item["body"]);
1167 if (isset($siteinfo["title"])) {
1168 return $siteinfo["title"];
1171 // If no bookmark is found then take the first line
1172 // Remove the share element before fetching the first line
1173 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1175 $title = BBCode::toPlaintext($title)."\n";
1176 $pos = strpos($title, "\n");
1178 if (($pos == 0) || ($pos > 100)) {
1183 return substr($title, 0, $pos) . $trailer;