3 * @copyright Copyright (C) 2020, Friendica
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\Duration;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\Item;
38 use Friendica\Model\Post;
39 use Friendica\Model\Tag;
40 use Friendica\Model\User;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Network;
43 use Friendica\Util\ParseUrl;
44 use Friendica\Util\Strings;
45 use Friendica\Util\XML;
48 * This class contain functions to import feeds (RSS/RDF/Atom)
53 * consume - process atom feed and update anything/everything we might need to update
55 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
57 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
58 * It is this person's stuff that is going to be updated.
59 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
60 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
61 * have a contact record.
62 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
63 * might not) try and subscribe to it.
64 * $datedir sorts in reverse order
65 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
66 * imported prior to its children being seen in the stream unless we are certain
67 * of how the feed is arranged/ordered.
68 * With $pass = 1, we only pull parent items out of the stream.
69 * With $pass = 2, we only pull children (comments/likes).
71 * So running this twice, first with pass 1 and then with pass 2 will do the right
72 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
73 * model where comments can have sub-threads. That would require some massive sorting
74 * to get all the feed items into a mostly linear ordering, and might still require
78 * @param array $importer
79 * @param array $contact
81 * @throws ImagickException
82 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
84 public static function consume($xml, array $importer, array $contact, &$hub)
86 if ($contact['network'] === Protocol::OSTATUS) {
87 Logger::info('Consume OStatus messages');
88 OStatus::import($xml, $importer, $contact, $hub);
93 if ($contact['network'] === Protocol::FEED) {
94 Logger::info('Consume feeds');
95 self::import($xml, $importer, $contact);
100 if ($contact['network'] === Protocol::DFRN) {
101 Logger::info('Consume DFRN messages');
102 $dfrn_importer = DFRN::getImporter($contact['id'], $importer['uid']);
103 if (!empty($dfrn_importer)) {
104 Logger::info('Now import the DFRN feed');
105 DFRN::import($xml, $dfrn_importer, true, Conversation::PARCEL_LEGACY_DFRN);
112 * Read a RSS/RDF/Atom feed and create an item entry for it
114 * @param string $xml The feed data
115 * @param array $importer The user record of the importer
116 * @param array $contact The contact record of the feed
118 * @return array Returns the header and the first item in dry run mode
119 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
121 public static function import($xml, array $importer = [], array $contact = [])
123 $dryRun = empty($importer) && empty($contact);
126 Logger::info("Test Atom/RSS feed");
128 Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
132 Logger::info('XML is empty.');
136 if (!empty($contact['poll'])) {
137 $basepath = $contact['poll'];
138 } elseif (!empty($contact['url'])) {
139 $basepath = $contact['url'];
144 $doc = new DOMDocument();
145 @$doc->loadXML(trim($xml));
146 $xpath = new DOMXPath($doc);
147 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
148 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
149 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
150 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
151 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
152 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
153 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
159 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
160 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
161 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
163 if (empty($author["author-name"])) {
164 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
166 $entries = $xpath->query('/rdf:RDF/rss:item');
170 if ($xpath->query('/atom:feed')->length > 0) {
171 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
172 if (is_object($alternate)) {
173 foreach ($alternate AS $attribute) {
174 if ($attribute->name == "href") {
175 $author["author-link"] = $attribute->textContent;
180 if (empty($author["author-link"])) {
181 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
182 if (is_object($self)) {
183 foreach ($self AS $attribute) {
184 if ($attribute->name == "href") {
185 $author["author-link"] = $attribute->textContent;
191 if (empty($author["author-link"])) {
192 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
194 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
196 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
198 if (empty($author["author-name"])) {
199 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
202 if (empty($author["author-name"])) {
203 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
206 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
208 $author["author-name"] = $value;
212 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
214 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
215 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
217 $author["author-link"] = $value;
220 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
222 $author["author-nick"] = $value;
225 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
227 $author["author-location"] = $value;
230 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
232 $author["author-about"] = $value;
235 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
236 if (is_object($avatar)) {
237 foreach ($avatar AS $attribute) {
238 if ($attribute->name == "href") {
239 $author["author-avatar"] = $attribute->textContent;
245 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
247 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
249 $entries = $xpath->query('/atom:feed/atom:entry');
253 if ($xpath->query('/rss/channel')->length > 0) {
254 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
256 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
257 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
259 if (empty($author["author-name"])) {
260 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
263 if (empty($author["author-name"])) {
264 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
267 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
269 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
271 $entries = $xpath->query('/rss/channel/item');
275 $author["author-link"] = $contact["url"];
277 if (empty($author["author-name"])) {
278 $author["author-name"] = $contact["name"];
281 $author["author-avatar"] = $contact["thumb"];
283 $author["owner-link"] = $contact["url"];
284 $author["owner-name"] = $contact["name"];
285 $author["owner-avatar"] = $contact["thumb"];
289 $header["uid"] = $importer["uid"] ?? 0;
290 $header["network"] = Protocol::FEED;
292 $header["origin"] = 0;
293 $header["gravity"] = GRAVITY_PARENT;
294 $header["private"] = Item::PUBLIC;
295 $header["verb"] = Activity::POST;
296 $header["object-type"] = Activity\ObjectType::NOTE;
298 $header["contact-id"] = $contact["id"] ?? 0;
300 if (!is_object($entries)) {
301 Logger::info("There are no entries in this feed.");
306 $creation_dates = [];
308 // Limit the number of items that are about to be fetched
309 $total_items = ($entries->length - 1);
310 $max_items = DI::config()->get('system', 'max_feed_items');
311 if (($max_items > 0) && ($total_items > $max_items)) {
312 $total_items = $max_items;
317 // Importing older entries first
318 for ($i = $total_items; $i >= 0; --$i) {
319 $entry = $entries->item($i);
321 $item = array_merge($header, $author);
323 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
324 if (!is_object($alternate)) {
325 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
327 if (is_object($alternate)) {
328 foreach ($alternate AS $attribute) {
329 if ($attribute->name == "href") {
330 $item["plink"] = $attribute->textContent;
335 if (empty($item["plink"])) {
336 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
339 if (empty($item["plink"])) {
340 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
343 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
345 if (empty($item["uri"])) {
346 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
349 if (empty($item["uri"])) {
350 $item["uri"] = $item["plink"];
353 // Add the base path if missing
354 $item["uri"] = Network::addBasePath($item["uri"], $basepath);
355 $item["plink"] = Network::addBasePath($item["plink"], $basepath);
357 $orig_plink = $item["plink"];
359 $item["plink"] = DI::httpRequest()->finalUrl($item["plink"]);
361 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
363 if (empty($item["title"])) {
364 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
366 if (empty($item["title"])) {
367 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
370 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
372 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
374 if (empty($published)) {
375 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
378 if (empty($published)) {
379 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
382 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
384 if (empty($updated) && !empty($published)) {
385 $updated = $published;
388 if (empty($published) && !empty($updated)) {
389 $published = $updated;
392 if ($published != "") {
393 $item["created"] = $published;
396 if ($updated != "") {
397 $item["edited"] = $updated;
401 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
402 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
403 $previous = Item::selectFirst(['id', 'created'], $condition);
404 if (DBA::isResult($previous)) {
405 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
406 $creation_dates[] = $previous['created'];
407 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
410 $creation_dates[] = DateTimeFormat::utc($item['created']);
413 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
415 if (empty($creator)) {
416 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
419 if (empty($creator)) {
420 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
423 if ($creator != "") {
424 $item["author-name"] = $creator;
427 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
429 if ($creator != "") {
430 $item["author-name"] = $creator;
434 // <category>Ausland</category>
435 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
439 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
440 foreach ($enclosures AS $enclosure) {
445 foreach ($enclosure->attributes AS $attribute) {
446 if (in_array($attribute->name, ["url", "href"])) {
447 $href = $attribute->textContent;
448 } elseif ($attribute->name == "length") {
449 $length = (int)$attribute->textContent;
450 } elseif ($attribute->name == "type") {
451 $type = $attribute->textContent;
456 $attachments[] = ['type' => Post\Media::DOCUMENT, 'url' => $href, 'mimetype' => $type, 'size' => $length];
461 $categories = $xpath->query("category", $entry);
462 foreach ($categories AS $category) {
463 $taglist[] = $category->nodeValue;
466 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
469 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
472 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
474 if (empty($summary)) {
475 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
483 if ($body == $summary) {
487 // remove the content of the title if it is identically to the body
488 // This helps with auto generated titles e.g. from tumblr
489 if (self::titleIsBody($item["title"], $body)) {
492 $item["body"] = HTML::toBBCode($body, $basepath);
494 // Remove tracking pixels
495 $item["body"] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item["body"]);
497 if (($item["body"] == '') && ($item["title"] != '')) {
498 $item["body"] = $item["title"];
505 } elseif (!Item::isValid($item)) {
506 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
508 } elseif (Item::isTooOld($item)) {
509 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
514 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
515 // Handle enclosures and treat them as preview picture
516 foreach ($attachments AS $attachment) {
517 if ($attachment["mimetype"] == "image/jpeg") {
518 $preview = $attachment["url"];
522 // Remove a possible link to the item itself
523 $item["body"] = str_replace($item["plink"], '', $item["body"]);
524 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
526 // Replace the content when the title is longer than the body
527 $replace = (strlen($item["title"]) > strlen($item["body"]));
529 // Replace it, when there is an image in the body
530 if (strstr($item["body"], '[/img]')) {
534 // Replace it, when there is a link in the body
535 if (strstr($item["body"], '[/url]')) {
539 $saved_body = $item["body"];
540 $saved_title = $item["title"];
543 $item["body"] = trim($item["title"]);
546 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
547 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
548 // When the fetched page info text is longer than the body, we do try to enhance the body
549 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
550 // The body is not part of the fetched page info title or page info text. So we add the text to the body
551 $item['body'] .= "\n\n" . $data['text'];
553 // Else we replace the body with the page info text
554 $item['body'] = $data['text'];
558 $data = PageInfo::queryUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
561 // Take the data that was provided by the feed if the query is empty
562 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
563 $data['title'] = $saved_title;
564 $item["body"] = $saved_body;
567 $data_text = strip_tags(trim($data['text'] ?? ''));
568 $item_body = strip_tags(trim($item['body'] ?? ''));
570 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
574 // We always strip the title since it will be added in the page information
576 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromData($data, false);
577 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
578 $item["object-type"] = Activity\ObjectType::BOOKMARK;
582 if (!empty($summary)) {
583 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
586 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
587 if (empty($taglist)) {
588 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
590 $item["body"] .= "\n" . self::tagToString($taglist);
595 // Add the link to the original feed entry if not present in feed
596 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
597 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
601 Logger::info('Stored feed', ['item' => $item]);
603 $notify = Item::isRemoteSelf($contact, $item);
605 // Distributed items should have a well formatted URI.
606 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
608 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
609 $item['uri'] = Item::newURI($item['uid'], $item['guid']);
610 unset($item['thr-parent']);
611 unset($item['parent-uri']);
613 // Set the delivery priority for "remote self" to "medium"
614 $notify = PRIORITY_MEDIUM;
617 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
618 if (!Item::exists($condition) && !Post\Delayed::exists($item["uri"], $item['uid'])) {
619 $postings[] = ['item' => $item, 'notify' => $notify,
620 'taglist' => $taglist, 'attachments' => $attachments];
622 Logger::info('Post already exists in the delayed posts queue', ['uri' => $item["uri"]]);
626 if (!empty($postings)) {
627 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
628 $total = count($postings);
630 // Posts shouldn't be delayed more than a day
631 $interval = min(1440, self::getPollInterval($contact));
632 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
633 Logger::notice('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
640 foreach ($postings as $posting) {
641 if (!$posting['notify']) {
642 Post\Delayed::publish($posting['item'], $posting['notify'], $posting['taglist'], $posting['attachments']);
647 $publish_time = time() + $post_delay;
648 Logger::notice('Got publishing date', ['delay' => $delay, 'cid' => $contact['id'], 'url' => $contact['url']]);
649 $post_delay += $delay;
651 $publish_time = time();
654 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
655 $next_publish = max($last_publish + (60 * $min_posting), time());
656 if ($publish_time < $next_publish) {
657 Logger::notice('Adapting publish time',
658 ['last' => date(DateTimeFormat::MYSQL, $last_publish),
659 'next' => date(DateTimeFormat::MYSQL, $next_publish),
660 'publish' => date(DateTimeFormat::MYSQL, $publish_time)]);
661 $publish_time = $next_publish;
663 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
665 Post\Delayed::add($publish_at, $posting['item'], $posting['notify'], $posting['taglist'], $posting['attachments']);
666 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $next_publish);
670 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
671 self::adjustPollFrequency($contact, $creation_dates);
674 return ["header" => $author, "items" => $items];
678 * Automatically adjust the poll frequency according to the post frequency
680 * @param array $contact
681 * @param array $creation_dates
684 private static function adjustPollFrequency(array $contact, array $creation_dates)
686 if ($contact['network'] != Protocol::FEED) {
687 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
691 if (!empty($creation_dates)) {
692 // Count the post frequency and the earliest and latest post date
696 $oldest_date = $newest_date = '';
698 foreach ($creation_dates as $date) {
699 $timestamp = strtotime($date);
700 $day = intdiv($timestamp, 86400);
701 $hour = $timestamp % 86400;
703 // Only have a look at values from the last seven days
704 if (((time() / 86400) - $day) < 7) {
705 if (empty($frequency[$day])) {
706 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
708 ++$frequency[$day]['count'];
709 if ($frequency[$day]['low'] > $hour) {
710 $frequency[$day]['low'] = $hour;
712 if ($frequency[$day]['high'] < $hour) {
713 $frequency[$day]['high'] = $hour;
717 if ($oldest > $day) {
719 $oldest_date = $date;
722 if ($newest < $day) {
724 $newest_date = $date;
728 if (count($creation_dates) == 1) {
729 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
730 $priority = 8; // Poll once a day
733 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
734 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']]);
735 $priority = 10; // Poll every month
738 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
739 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']]);
740 $priority = 9; // Poll every week
743 if (empty($priority) && empty($frequency)) {
744 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']]);
745 $priority = 8; // Poll once a day
748 if (empty($priority)) {
749 // Calculate the highest "posts per day" value
751 foreach ($frequency as $entry) {
752 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
756 // We take the earliest and latest post day and interpolate the number of post per day
757 // that would had been created with this post frequency
759 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
760 $duration = max($entry['high'] - $entry['low'], 14400);
761 $ppd = (86400 / $duration) * $entry['count'];
767 $priority = 1; // Poll every quarter hour
768 } elseif ($max > 24) {
769 $priority = 2; // Poll half an hour
770 } elseif ($max > 12) {
771 $priority = 3; // Poll hourly
772 } elseif ($max > 8) {
773 $priority = 4; // Poll every two hours
774 } elseif ($max > 4) {
775 $priority = 5; // Poll every three hours
776 } elseif ($max > 2) {
777 $priority = 6; // Poll every six hours
779 $priority = 7; // Poll twice a day
781 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
784 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
785 $priority = 8; // Poll once a day
788 if ($contact['rating'] != $priority) {
789 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
790 DBA::update('contact', ['rating' => $priority], ['id' => $contact['id']]);
795 * Get the poll interval for the given contact array
797 * @param array $contact
798 * @return int Poll interval in minutes
800 public static function getPollInterval(array $contact)
802 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
803 $ratings = [0, 3, 7, 8, 9, 10];
804 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
805 $rating = $contact['rating'];
806 } elseif (array_key_exists($contact['priority'], $ratings)) {
807 $rating = $ratings[$contact['priority']];
812 // Check once a week per default for all other networks
816 // Friendica and OStatus are checked once a day
817 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
821 // Check archived contacts or contacts with unsupported protocols once a month
822 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
830 * Based on $contact['priority'], should we poll this site now? Or later?
833 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
835 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
837 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
838 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
840 return $poll_intervals[$rating];
844 * Convert a tag array to a tag string
847 * @return string tag string
849 private static function tagToString(array $tags)
853 foreach ($tags as $tag) {
858 $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
864 private static function titleIsBody($title, $body)
866 $title = strip_tags($title);
867 $title = trim($title);
868 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
869 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
871 $body = strip_tags($body);
873 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
874 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
876 if (strlen($title) < strlen($body)) {
877 $body = substr($body, 0, strlen($title));
880 if (($title != $body) && (substr($title, -3) == "...")) {
881 $pos = strrpos($title, "...");
883 $title = substr($title, 0, $pos);
884 $body = substr($body, 0, $pos);
887 return ($title == $body);
891 * Creates the Atom feed for a given nickname
894 * - activity (default): all the public posts
895 * - posts: all the public top-level posts
896 * - comments: all the public replies
898 * Updates the provided last_update parameter if the result comes from the
899 * cache or it is empty
901 * @param string $owner_nick Nickname of the feed owner
902 * @param string $last_update Date of the last update
903 * @param integer $max_items Number of maximum items to fetch
904 * @param string $filter Feed items filter (activity, posts or comments)
905 * @param boolean $nocache Wether to bypass caching
907 * @return string Atom feed
908 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
909 * @throws \ImagickException
911 public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
913 $stamp = microtime(true);
915 $owner = User::getOwnerDataByNick($owner_nick);
920 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
922 $previous_created = $last_update;
924 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
925 if ((time() - strtotime($owner['last-item'])) < 15*60) {
926 $result = DI::cache()->get($cachekey);
927 if (!$nocache && !is_null($result)) {
928 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
929 return $result['feed'];
933 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
934 $authorid = Contact::getIdForURL($owner["url"]);
936 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
937 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
938 $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
939 Item::PRIVATE, Protocol::ACTIVITYPUB,
940 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
942 if ($filter === 'comments') {
943 $condition[0] .= " AND `object-type` = ? ";
944 $condition[] = Activity\ObjectType::COMMENT;
947 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
948 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
949 $condition[] = $owner["id"];
950 $condition[] = $authorid;
953 $params = ['order' => ['received' => true], 'limit' => $max_items];
955 if ($filter === 'posts') {
956 $ret = Item::selectThread([], $condition, $params);
958 $ret = Item::select([], $condition, $params);
961 $items = Item::inArray($ret);
963 $doc = new DOMDocument('1.0', 'utf-8');
964 $doc->formatOutput = true;
966 $root = self::addHeader($doc, $owner, $filter);
968 foreach ($items as $item) {
969 $entry = self::entry($doc, $item, $owner);
970 $root->appendChild($entry);
972 if ($last_update < $item['created']) {
973 $last_update = $item['created'];
977 $feeddata = trim($doc->saveXML());
979 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
980 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
982 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
988 * Adds the header elements to the XML document
990 * @param DOMDocument $doc XML document
991 * @param array $owner Contact data of the poster
992 * @param string $filter The related feed filter (activity, posts or comments)
994 * @return object header root element
995 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
997 private static function addHeader(DOMDocument $doc, array $owner, $filter)
999 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1000 $doc->appendChild($root);
1003 $selfUri = '/feed/' . $owner["nick"] . '/';
1006 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1007 $selfUri .= $filter;
1010 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1013 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1014 $selfUri .= $filter;
1018 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1019 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1020 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1021 XML::addElement($doc, $root, "title", $title);
1022 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1023 XML::addElement($doc, $root, "logo", $owner["photo"]);
1024 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1026 $author = self::addAuthor($doc, $owner);
1027 $root->appendChild($author);
1029 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1030 XML::addElement($doc, $root, "link", "", $attributes);
1032 OStatus::hublinks($doc, $root, $owner["nick"]);
1034 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1035 XML::addElement($doc, $root, "link", "", $attributes);
1041 * Adds the author element to the XML document
1043 * @param DOMDocument $doc XML document
1044 * @param array $owner Contact data of the poster
1046 * @return \DOMElement author element
1047 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1049 private static function addAuthor(DOMDocument $doc, array $owner)
1051 $author = $doc->createElement("author");
1052 XML::addElement($doc, $author, "uri", $owner["url"]);
1053 XML::addElement($doc, $author, "name", $owner["nick"]);
1054 XML::addElement($doc, $author, "email", $owner["addr"]);
1060 * Adds an entry element to the XML document
1062 * @param DOMDocument $doc XML document
1063 * @param array $item Data of the item that is to be posted
1064 * @param array $owner Contact data of the poster
1065 * @param bool $toplevel optional default false
1067 * @return \DOMElement Entry element
1068 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1069 * @throws \ImagickException
1071 private static function entry(DOMDocument $doc, array $item, array $owner)
1075 $repeated_guid = OStatus::getResharedGuid($item);
1076 if ($repeated_guid != "") {
1077 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
1084 return self::noteEntry($doc, $item, $owner);
1088 * Adds an entry element with reshared content
1090 * @param DOMDocument $doc XML document
1091 * @param array $item Data of the item that is to be posted
1092 * @param array $owner Contact data of the poster
1093 * @param string $repeated_guid guid
1094 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1096 * @return bool Entry element
1097 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1098 * @throws \ImagickException
1100 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
1102 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1103 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1106 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1108 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1109 'network' => Protocol::FEDERATED];
1110 $repeated_item = Item::selectFirst([], $condition);
1111 if (!DBA::isResult($repeated_item)) {
1115 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
1117 self::entryFooter($doc, $entry, $item, $owner);
1123 * Adds a regular entry element
1125 * @param DOMDocument $doc XML document
1126 * @param array $item Data of the item that is to be posted
1127 * @param array $owner Contact data of the poster
1128 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1130 * @return \DOMElement Entry element
1131 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1132 * @throws \ImagickException
1134 private static function noteEntry(DOMDocument $doc, array $item, array $owner)
1136 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1137 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1140 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1142 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1144 self::entryFooter($doc, $entry, $item, $owner);
1150 * Adds elements to the XML document
1152 * @param DOMDocument $doc XML document
1153 * @param \DOMElement $entry Entry element where the content is added
1154 * @param array $item Data of the item that is to be posted
1155 * @param array $owner Contact data of the poster
1156 * @param string $title Title for the post
1157 * @param string $verb The activity verb
1158 * @param bool $complete Add the "status_net" element?
1159 * @param bool $feed_mode Behave like a regular feed for users if true
1161 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1163 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
1166 $verb = OStatus::constructVerb($item);
1169 XML::addElement($doc, $entry, "id", $item["uri"]);
1170 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1172 $body = OStatus::formatPicturePost($item['body']);
1174 $body = BBCode::convert($body, false, BBCode::OSTATUS);
1176 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1178 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1179 "href" => DI::baseUrl()."/display/".$item["guid"]]
1182 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1183 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1187 * Adds the elements at the foot of an entry to the XML document
1189 * @param DOMDocument $doc XML document
1190 * @param object $entry The entry element where the elements are added
1191 * @param array $item Data of the item that is to be posted
1192 * @param array $owner Contact data of the poster
1193 * @param bool $complete default true
1195 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1197 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1201 if ($item['gravity'] != GRAVITY_PARENT) {
1202 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1204 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $item['thr-parent']]);
1206 if (DBA::isResult($thrparent)) {
1207 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1208 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1209 $parent_plink = $thrparent["plink"];
1211 $mentioned[$parent["author-link"]] = $parent["author-link"];
1212 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1213 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1217 "ref" => $item['thr-parent'],
1218 "href" => $parent_plink];
1219 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1223 "href" => $parent_plink];
1224 XML::addElement($doc, $entry, "link", "", $attributes);
1227 // uri-id isn't present for follow entry pseudo-items
1228 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1229 foreach ($tags as $tag) {
1230 $mentioned[$tag['url']] = $tag['url'];
1233 foreach ($tags as $tag) {
1234 if ($tag['type'] == Tag::HASHTAG) {
1235 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
1239 OStatus::getAttachment($doc, $entry, $item);
1243 * Fetch or create title for feed entry
1245 * @param array $item
1246 * @return string title
1248 private static function getTitle(array $item)
1250 if ($item['title'] != '') {
1251 return BBCode::convert($item['title'], false, BBCode::OSTATUS);
1254 // Fetch information about the post
1255 $siteinfo = BBCode::getAttachedData($item["body"]);
1256 if (isset($siteinfo["title"])) {
1257 return $siteinfo["title"];
1260 // If no bookmark is found then take the first line
1261 // Remove the share element before fetching the first line
1262 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1264 $title = HTML::toPlaintext(BBCode::convert($title, false), 0, true)."\n";
1265 $pos = strpos($title, "\n");
1267 if (($pos == 0) || ($pos > 100)) {
1272 return substr($title, 0, $pos) . $trailer;