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\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\Item;
37 use Friendica\Model\Post;
38 use Friendica\Model\Tag;
39 use Friendica\Model\User;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Network;
42 use Friendica\Util\ParseUrl;
43 use Friendica\Util\Strings;
44 use Friendica\Util\XML;
47 * This class contain functions to import feeds (RSS/RDF/Atom)
52 * consume - process atom feed and update anything/everything we might need to update
54 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
56 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
57 * It is this person's stuff that is going to be updated.
58 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
59 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
60 * have a contact record.
61 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
62 * might not) try and subscribe to it.
63 * $datedir sorts in reverse order
64 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
65 * imported prior to its children being seen in the stream unless we are certain
66 * of how the feed is arranged/ordered.
67 * With $pass = 1, we only pull parent items out of the stream.
68 * With $pass = 2, we only pull children (comments/likes).
70 * So running this twice, first with pass 1 and then with pass 2 will do the right
71 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
72 * model where comments can have sub-threads. That would require some massive sorting
73 * to get all the feed items into a mostly linear ordering, and might still require
77 * @param array $importer
78 * @param array $contact
80 * @throws ImagickException
81 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
83 public static function consume($xml, array $importer, array $contact, &$hub)
85 if ($contact['network'] === Protocol::OSTATUS) {
86 Logger::info('Consume OStatus messages');
87 OStatus::import($xml, $importer, $contact, $hub);
92 if ($contact['network'] === Protocol::FEED) {
93 Logger::info('Consume feeds');
94 self::import($xml, $importer, $contact);
99 if ($contact['network'] === Protocol::DFRN) {
100 Logger::info('Consume DFRN messages');
101 $dfrn_importer = DFRN::getImporter($contact['id'], $importer['uid']);
102 if (!empty($dfrn_importer)) {
103 Logger::info('Now import the DFRN feed');
104 DFRN::import($xml, $dfrn_importer, true, Conversation::PARCEL_LEGACY_DFRN);
111 * Get the poll interval for the given contact array
113 * @param array $contact
114 * @return int Poll interval in minutes
116 public static function getPollInterval(array $contact)
118 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
119 $ratings = [0, 3, 7, 8, 9, 10];
120 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
121 $rating = $contact['rating'];
122 } elseif (array_key_exists($contact['priority'], $ratings)) {
123 $rating = $ratings[$contact['priority']];
128 // Check once a week per default for all other networks
132 // Friendica and OStatus are checked once a day
133 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
137 // Check archived contacts or contacts with unsupported protocols once a month
138 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
146 * Based on $contact['priority'], should we poll this site now? Or later?
149 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
151 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
153 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
154 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
156 return $poll_intervals[$rating];
160 * Read a RSS/RDF/Atom feed and create an item entry for it
162 * @param string $xml The feed data
163 * @param array $importer The user record of the importer
164 * @param array $contact The contact record of the feed
166 * @return array Returns the header and the first item in dry run mode
167 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169 public static function import($xml, array $importer = [], array $contact = [])
171 $dryRun = empty($importer) && empty($contact);
174 Logger::info("Test Atom/RSS feed");
176 Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
180 Logger::info('XML is empty.');
184 if (!empty($contact['poll'])) {
185 $basepath = $contact['poll'];
186 } elseif (!empty($contact['url'])) {
187 $basepath = $contact['url'];
192 $doc = new DOMDocument();
193 @$doc->loadXML(trim($xml));
194 $xpath = new DOMXPath($doc);
195 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
196 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
197 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
198 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
199 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
200 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
201 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
207 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
208 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
209 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
211 if (empty($author["author-name"])) {
212 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
214 $entries = $xpath->query('/rdf:RDF/rss:item');
218 if ($xpath->query('/atom:feed')->length > 0) {
219 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
220 if (is_object($alternate)) {
221 foreach ($alternate AS $attribute) {
222 if ($attribute->name == "href") {
223 $author["author-link"] = $attribute->textContent;
228 if (empty($author["author-link"])) {
229 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
230 if (is_object($self)) {
231 foreach ($self AS $attribute) {
232 if ($attribute->name == "href") {
233 $author["author-link"] = $attribute->textContent;
239 if (empty($author["author-link"])) {
240 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
242 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
244 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
246 if (empty($author["author-name"])) {
247 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
250 if (empty($author["author-name"])) {
251 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
254 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
256 $author["author-name"] = $value;
260 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
262 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
263 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
265 $author["author-link"] = $value;
268 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
270 $author["author-nick"] = $value;
273 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
275 $author["author-location"] = $value;
278 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
280 $author["author-about"] = $value;
283 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
284 if (is_object($avatar)) {
285 foreach ($avatar AS $attribute) {
286 if ($attribute->name == "href") {
287 $author["author-avatar"] = $attribute->textContent;
293 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
295 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
297 $entries = $xpath->query('/atom:feed/atom:entry');
301 if ($xpath->query('/rss/channel')->length > 0) {
302 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
304 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
305 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
307 if (empty($author["author-name"])) {
308 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
311 if (empty($author["author-name"])) {
312 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
315 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
317 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
319 $entries = $xpath->query('/rss/channel/item');
323 $author["author-link"] = $contact["url"];
325 if (empty($author["author-name"])) {
326 $author["author-name"] = $contact["name"];
329 $author["author-avatar"] = $contact["thumb"];
331 $author["owner-link"] = $contact["url"];
332 $author["owner-name"] = $contact["name"];
333 $author["owner-avatar"] = $contact["thumb"];
337 $header["uid"] = $importer["uid"] ?? 0;
338 $header["network"] = Protocol::FEED;
340 $header["origin"] = 0;
341 $header["gravity"] = GRAVITY_PARENT;
342 $header["private"] = Item::PUBLIC;
343 $header["verb"] = Activity::POST;
344 $header["object-type"] = Activity\ObjectType::NOTE;
346 $header["contact-id"] = $contact["id"] ?? 0;
348 if (!is_object($entries)) {
349 Logger::info("There are no entries in this feed.");
354 $creation_dates = [];
356 // Limit the number of items that are about to be fetched
357 $total_items = ($entries->length - 1);
358 $max_items = DI::config()->get('system', 'max_feed_items');
359 if (($max_items > 0) && ($total_items > $max_items)) {
360 $total_items = $max_items;
365 // Importing older entries first
366 for ($i = $total_items; $i >= 0; --$i) {
367 $entry = $entries->item($i);
369 $item = array_merge($header, $author);
371 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
372 if (!is_object($alternate)) {
373 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
375 if (is_object($alternate)) {
376 foreach ($alternate AS $attribute) {
377 if ($attribute->name == "href") {
378 $item["plink"] = $attribute->textContent;
383 if (empty($item["plink"])) {
384 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
387 if (empty($item["plink"])) {
388 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
391 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
393 if (empty($item["uri"])) {
394 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
397 if (empty($item["uri"])) {
398 $item["uri"] = $item["plink"];
401 // Add the base path if missing
402 $item["uri"] = Network::addBasePath($item["uri"], $basepath);
403 $item["plink"] = Network::addBasePath($item["plink"], $basepath);
405 $orig_plink = $item["plink"];
407 $item["plink"] = DI::httpRequest()->finalUrl($item["plink"]);
409 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
411 if (empty($item["title"])) {
412 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
414 if (empty($item["title"])) {
415 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
418 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
420 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
422 if (empty($published)) {
423 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
426 if (empty($published)) {
427 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
430 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
432 if (empty($updated) && !empty($published)) {
433 $updated = $published;
436 if (empty($published) && !empty($updated)) {
437 $published = $updated;
440 if ($published != "") {
441 $item["created"] = $published;
444 if ($updated != "") {
445 $item["edited"] = $updated;
449 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
450 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
451 $previous = Item::selectFirst(['id', 'created'], $condition);
452 if (DBA::isResult($previous)) {
453 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
454 $creation_dates[] = $previous['created'];
455 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
458 $creation_dates[] = DateTimeFormat::utc($item['created']);
461 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
463 if (empty($creator)) {
464 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
467 if (empty($creator)) {
468 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
471 if ($creator != "") {
472 $item["author-name"] = $creator;
475 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
477 if ($creator != "") {
478 $item["author-name"] = $creator;
482 // <category>Ausland</category>
483 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
487 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
488 foreach ($enclosures AS $enclosure) {
493 foreach ($enclosure->attributes AS $attribute) {
494 if (in_array($attribute->name, ["url", "href"])) {
495 $href = $attribute->textContent;
496 } elseif ($attribute->name == "length") {
497 $length = (int)$attribute->textContent;
498 } elseif ($attribute->name == "type") {
499 $type = $attribute->textContent;
504 $attachments[] = ['type' => Post\Media::DOCUMENT, 'url' => $href, 'mimetype' => $type, 'size' => $length];
509 $categories = $xpath->query("category", $entry);
510 foreach ($categories AS $category) {
511 $taglist[] = $category->nodeValue;
514 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
517 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
520 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
522 if (empty($summary)) {
523 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
531 if ($body == $summary) {
535 // remove the content of the title if it is identically to the body
536 // This helps with auto generated titles e.g. from tumblr
537 if (self::titleIsBody($item["title"], $body)) {
540 $item["body"] = HTML::toBBCode($body, $basepath);
542 // Remove tracking pixels
543 $item["body"] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item["body"]);
545 if (($item["body"] == '') && ($item["title"] != '')) {
546 $item["body"] = $item["title"];
553 } elseif (!Item::isValid($item)) {
554 Logger::info('Feed is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
559 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
560 // Handle enclosures and treat them as preview picture
561 foreach ($attachments AS $attachment) {
562 if ($attachment["mimetype"] == "image/jpeg") {
563 $preview = $attachment["url"];
567 // Remove a possible link to the item itself
568 $item["body"] = str_replace($item["plink"], '', $item["body"]);
569 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
571 // Replace the content when the title is longer than the body
572 $replace = (strlen($item["title"]) > strlen($item["body"]));
574 // Replace it, when there is an image in the body
575 if (strstr($item["body"], '[/img]')) {
579 // Replace it, when there is a link in the body
580 if (strstr($item["body"], '[/url]')) {
584 $saved_body = $item["body"];
585 $saved_title = $item["title"];
588 $item["body"] = trim($item["title"]);
591 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
592 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
593 // When the fetched page info text is longer than the body, we do try to enhance the body
594 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
595 // The body is not part of the fetched page info title or page info text. So we add the text to the body
596 $item['body'] .= "\n\n" . $data['text'];
598 // Else we replace the body with the page info text
599 $item['body'] = $data['text'];
603 $data = PageInfo::queryUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
606 // Take the data that was provided by the feed if the query is empty
607 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
608 $data['title'] = $saved_title;
609 $item["body"] = $saved_body;
612 $data_text = strip_tags(trim($data['text'] ?? ''));
613 $item_body = strip_tags(trim($item['body'] ?? ''));
615 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
619 // We always strip the title since it will be added in the page information
621 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromData($data, false);
622 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
623 $item["object-type"] = Activity\ObjectType::BOOKMARK;
627 if (!empty($summary)) {
628 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
631 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
632 if (empty($taglist)) {
633 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
635 $item["body"] .= "\n" . self::tagToString($taglist);
640 // Add the link to the original feed entry if not present in feed
641 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
642 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
646 Logger::info('Stored feed', ['item' => $item]);
648 $notify = Item::isRemoteSelf($contact, $item);
650 // Distributed items should have a well formatted URI.
651 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
653 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
655 unset($item['thr-parent']);
656 unset($item['parent-uri']);
658 // Set the delivery priority for "remote self" to "medium"
659 $notify = PRIORITY_MEDIUM;
662 $postings[] = ['item' => $item, 'notify' => $notify,
663 'taglist' => $taglist, 'attachments' => $attachments];
666 if (!empty($postings)) {
667 $total = count($postings);
669 $interval = self::getPollInterval($contact);
670 $delay = round(($interval * 60) / $total);
671 Logger::notice('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
678 foreach ($postings as $posting) {
680 $publish_at = DateTimeFormat::utc('now + ' . $post_delay . ' minute');
681 Logger::notice('Got publishing date', ['delay' => $delay, 'publish_at' => $publish_at, 'cid' => $contact['id'], 'url' => $contact['url']]);
682 $post_delay += $delay;
685 $id = Item::insert($posting['item'], $posting['notify']);
687 Logger::notice("Feed for contact " . $contact["url"] . " stored under id " . $id);
689 if (!empty($id) && (!empty($posting['taglist']) || !empty($posting['attachments']))) {
690 $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
691 foreach ($posting['taglist'] as $tag) {
692 Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
694 foreach ($posting['attachments'] as $attachment) {
695 $attachment['uri-id'] = $feeditem['uri-id'];
696 Post\Media::insert($attachment);
702 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
703 self::adjustPollFrequency($contact, $creation_dates);
706 return ["header" => $author, "items" => $items];
710 * Automatically adjust the poll frequency according to the post frequency
712 * @param array $contact
713 * @param array $creation_dates
716 private static function adjustPollFrequency(array $contact, array $creation_dates)
718 if ($contact['network'] != Protocol::FEED) {
719 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
723 if (!empty($creation_dates)) {
724 // Count the post frequency and the earliest and latest post date
728 $oldest_date = $newest_date = '';
730 foreach ($creation_dates as $date) {
731 $timestamp = strtotime($date);
732 $day = intdiv($timestamp, 86400);
733 $hour = $timestamp % 86400;
735 // Only have a look at values from the last seven days
736 if (((time() / 86400) - $day) < 7) {
737 if (empty($frequency[$day])) {
738 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
740 ++$frequency[$day]['count'];
741 if ($frequency[$day]['low'] > $hour) {
742 $frequency[$day]['low'] = $hour;
744 if ($frequency[$day]['high'] < $hour) {
745 $frequency[$day]['high'] = $hour;
749 if ($oldest > $day) {
751 $oldest_date = $date;
754 if ($newest < $day) {
756 $newest_date = $date;
760 if (count($creation_dates) == 1) {
761 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
762 $priority = 8; // Poll once a day
765 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
766 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']]);
767 $priority = 10; // Poll every month
770 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
771 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']]);
772 $priority = 9; // Poll every week
775 if (empty($priority) && empty($frequency)) {
776 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']]);
777 $priority = 8; // Poll once a day
780 if (empty($priority)) {
781 // Calculate the highest "posts per day" value
783 foreach ($frequency as $entry) {
784 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
788 // We take the earliest and latest post day and interpolate the number of post per day
789 // that would had been created with this post frequency
791 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
792 $duration = max($entry['high'] - $entry['low'], 14400);
793 $ppd = (86400 / $duration) * $entry['count'];
799 $priority = 1; // Poll every quarter hour
800 } elseif ($max > 24) {
801 $priority = 2; // Poll half an hour
802 } elseif ($max > 12) {
803 $priority = 3; // Poll hourly
804 } elseif ($max > 8) {
805 $priority = 4; // Poll every two hours
806 } elseif ($max > 4) {
807 $priority = 5; // Poll every three hours
808 } elseif ($max > 2) {
809 $priority = 6; // Poll every six hours
811 $priority = 7; // Poll twice a day
813 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
816 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
817 $priority = 8; // Poll once a day
820 if ($contact['rating'] != $priority) {
821 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
822 DBA::update('contact', ['rating' => $priority], ['id' => $contact['id']]);
827 * Convert a tag array to a tag string
830 * @return string tag string
832 private static function tagToString(array $tags)
836 foreach ($tags as $tag) {
841 $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
847 private static function titleIsBody($title, $body)
849 $title = strip_tags($title);
850 $title = trim($title);
851 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
852 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
854 $body = strip_tags($body);
856 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
857 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
859 if (strlen($title) < strlen($body)) {
860 $body = substr($body, 0, strlen($title));
863 if (($title != $body) && (substr($title, -3) == "...")) {
864 $pos = strrpos($title, "...");
866 $title = substr($title, 0, $pos);
867 $body = substr($body, 0, $pos);
870 return ($title == $body);
874 * Creates the Atom feed for a given nickname
877 * - activity (default): all the public posts
878 * - posts: all the public top-level posts
879 * - comments: all the public replies
881 * Updates the provided last_update parameter if the result comes from the
882 * cache or it is empty
884 * @param string $owner_nick Nickname of the feed owner
885 * @param string $last_update Date of the last update
886 * @param integer $max_items Number of maximum items to fetch
887 * @param string $filter Feed items filter (activity, posts or comments)
888 * @param boolean $nocache Wether to bypass caching
890 * @return string Atom feed
891 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
892 * @throws \ImagickException
894 public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
896 $stamp = microtime(true);
898 $owner = User::getOwnerDataByNick($owner_nick);
903 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
905 $previous_created = $last_update;
907 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
908 if ((time() - strtotime($owner['last-item'])) < 15*60) {
909 $result = DI::cache()->get($cachekey);
910 if (!$nocache && !is_null($result)) {
911 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
912 return $result['feed'];
916 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
917 $authorid = Contact::getIdForURL($owner["url"]);
919 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
920 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
921 $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
922 Item::PRIVATE, Protocol::ACTIVITYPUB,
923 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
925 if ($filter === 'comments') {
926 $condition[0] .= " AND `object-type` = ? ";
927 $condition[] = Activity\ObjectType::COMMENT;
930 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
931 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
932 $condition[] = $owner["id"];
933 $condition[] = $authorid;
936 $params = ['order' => ['received' => true], 'limit' => $max_items];
938 if ($filter === 'posts') {
939 $ret = Item::selectThread([], $condition, $params);
941 $ret = Item::select([], $condition, $params);
944 $items = Item::inArray($ret);
946 $doc = new DOMDocument('1.0', 'utf-8');
947 $doc->formatOutput = true;
949 $root = self::addHeader($doc, $owner, $filter);
951 foreach ($items as $item) {
952 $entry = self::entry($doc, $item, $owner);
953 $root->appendChild($entry);
955 if ($last_update < $item['created']) {
956 $last_update = $item['created'];
960 $feeddata = trim($doc->saveXML());
962 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
963 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
965 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
971 * Adds the header elements to the XML document
973 * @param DOMDocument $doc XML document
974 * @param array $owner Contact data of the poster
975 * @param string $filter The related feed filter (activity, posts or comments)
977 * @return object header root element
978 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
980 private static function addHeader(DOMDocument $doc, array $owner, $filter)
982 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
983 $doc->appendChild($root);
986 $selfUri = '/feed/' . $owner["nick"] . '/';
989 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
993 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
996 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1001 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1002 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1003 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1004 XML::addElement($doc, $root, "title", $title);
1005 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1006 XML::addElement($doc, $root, "logo", $owner["photo"]);
1007 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1009 $author = self::addAuthor($doc, $owner);
1010 $root->appendChild($author);
1012 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1013 XML::addElement($doc, $root, "link", "", $attributes);
1015 OStatus::hublinks($doc, $root, $owner["nick"]);
1017 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1018 XML::addElement($doc, $root, "link", "", $attributes);
1024 * Adds the author element to the XML document
1026 * @param DOMDocument $doc XML document
1027 * @param array $owner Contact data of the poster
1029 * @return \DOMElement author element
1030 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1032 private static function addAuthor(DOMDocument $doc, array $owner)
1034 $author = $doc->createElement("author");
1035 XML::addElement($doc, $author, "uri", $owner["url"]);
1036 XML::addElement($doc, $author, "name", $owner["nick"]);
1037 XML::addElement($doc, $author, "email", $owner["addr"]);
1043 * Adds an entry element to the XML document
1045 * @param DOMDocument $doc XML document
1046 * @param array $item Data of the item that is to be posted
1047 * @param array $owner Contact data of the poster
1048 * @param bool $toplevel optional default false
1050 * @return \DOMElement Entry element
1051 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1052 * @throws \ImagickException
1054 private static function entry(DOMDocument $doc, array $item, array $owner)
1058 $repeated_guid = OStatus::getResharedGuid($item);
1059 if ($repeated_guid != "") {
1060 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
1067 return self::noteEntry($doc, $item, $owner);
1071 * Adds an entry element with reshared content
1073 * @param DOMDocument $doc XML document
1074 * @param array $item Data of the item that is to be posted
1075 * @param array $owner Contact data of the poster
1076 * @param string $repeated_guid guid
1077 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1079 * @return bool Entry element
1080 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1081 * @throws \ImagickException
1083 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
1085 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1086 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1089 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1091 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1092 'network' => Protocol::FEDERATED];
1093 $repeated_item = Item::selectFirst([], $condition);
1094 if (!DBA::isResult($repeated_item)) {
1098 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
1100 self::entryFooter($doc, $entry, $item, $owner);
1106 * Adds a regular entry element
1108 * @param DOMDocument $doc XML document
1109 * @param array $item Data of the item that is to be posted
1110 * @param array $owner Contact data of the poster
1111 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1113 * @return \DOMElement Entry element
1114 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1115 * @throws \ImagickException
1117 private static function noteEntry(DOMDocument $doc, array $item, array $owner)
1119 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1120 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1123 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1125 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1127 self::entryFooter($doc, $entry, $item, $owner);
1133 * Adds elements to the XML document
1135 * @param DOMDocument $doc XML document
1136 * @param \DOMElement $entry Entry element where the content is 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 string $title Title for the post
1140 * @param string $verb The activity verb
1141 * @param bool $complete Add the "status_net" element?
1142 * @param bool $feed_mode Behave like a regular feed for users if true
1144 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1146 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
1149 $verb = OStatus::constructVerb($item);
1152 XML::addElement($doc, $entry, "id", $item["uri"]);
1153 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1155 $body = OStatus::formatPicturePost($item['body']);
1157 $body = BBCode::convert($body, false, BBCode::OSTATUS);
1159 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1161 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1162 "href" => DI::baseUrl()."/display/".$item["guid"]]
1165 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1166 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1170 * Adds the elements at the foot of an entry to the XML document
1172 * @param DOMDocument $doc XML document
1173 * @param object $entry The entry element where the elements are added
1174 * @param array $item Data of the item that is to be posted
1175 * @param array $owner Contact data of the poster
1176 * @param bool $complete default true
1178 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1180 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1184 if ($item['gravity'] != GRAVITY_PARENT) {
1185 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1187 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $item['thr-parent']]);
1189 if (DBA::isResult($thrparent)) {
1190 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1191 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1192 $parent_plink = $thrparent["plink"];
1194 $mentioned[$parent["author-link"]] = $parent["author-link"];
1195 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1196 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1200 "ref" => $item['thr-parent'],
1201 "href" => $parent_plink];
1202 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1206 "href" => $parent_plink];
1207 XML::addElement($doc, $entry, "link", "", $attributes);
1210 // uri-id isn't present for follow entry pseudo-items
1211 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1212 foreach ($tags as $tag) {
1213 $mentioned[$tag['url']] = $tag['url'];
1216 foreach ($tags as $tag) {
1217 if ($tag['type'] == Tag::HASHTAG) {
1218 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
1222 OStatus::getAttachment($doc, $entry, $item);
1226 * Fetch or create title for feed entry
1228 * @param array $item
1229 * @return string title
1231 private static function getTitle(array $item)
1233 if ($item['title'] != '') {
1234 return BBCode::convert($item['title'], false, BBCode::OSTATUS);
1237 // Fetch information about the post
1238 $siteinfo = BBCode::getAttachedData($item["body"]);
1239 if (isset($siteinfo["title"])) {
1240 return $siteinfo["title"];
1243 // If no bookmark is found then take the first line
1244 // Remove the share element before fetching the first line
1245 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1247 $title = HTML::toPlaintext(BBCode::convert($title, false), 0, true)."\n";
1248 $pos = strpos($title, "\n");
1250 if (($pos == 0) || ($pos > 100)) {
1255 return substr($title, 0, $pos) . $trailer;