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 * Read a RSS/RDF/Atom feed and create an item entry for it
113 * @param string $xml The feed data
114 * @param array $importer The user record of the importer
115 * @param array $contact The contact record of the feed
117 * @return array Returns the header and the first item in dry run mode
118 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
120 public static function import($xml, array $importer = [], array $contact = [])
122 $dryRun = empty($importer) && empty($contact);
125 Logger::info("Test Atom/RSS feed");
127 Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
131 Logger::info('XML is empty.');
135 if (!empty($contact['poll'])) {
136 $basepath = $contact['poll'];
137 } elseif (!empty($contact['url'])) {
138 $basepath = $contact['url'];
143 $doc = new DOMDocument();
144 @$doc->loadXML(trim($xml));
145 $xpath = new DOMXPath($doc);
146 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
147 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
148 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
149 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
150 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
151 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
152 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
158 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
159 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
160 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
162 if (empty($author["author-name"])) {
163 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
165 $entries = $xpath->query('/rdf:RDF/rss:item');
169 if ($xpath->query('/atom:feed')->length > 0) {
170 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
171 if (is_object($alternate)) {
172 foreach ($alternate AS $attribute) {
173 if ($attribute->name == "href") {
174 $author["author-link"] = $attribute->textContent;
179 if (empty($author["author-link"])) {
180 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
181 if (is_object($self)) {
182 foreach ($self AS $attribute) {
183 if ($attribute->name == "href") {
184 $author["author-link"] = $attribute->textContent;
190 if (empty($author["author-link"])) {
191 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
193 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
195 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
197 if (empty($author["author-name"])) {
198 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
201 if (empty($author["author-name"])) {
202 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
205 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
207 $author["author-name"] = $value;
211 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
213 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
214 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
216 $author["author-link"] = $value;
219 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
221 $author["author-nick"] = $value;
224 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
226 $author["author-location"] = $value;
229 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
231 $author["author-about"] = $value;
234 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
235 if (is_object($avatar)) {
236 foreach ($avatar AS $attribute) {
237 if ($attribute->name == "href") {
238 $author["author-avatar"] = $attribute->textContent;
244 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
246 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
248 $entries = $xpath->query('/atom:feed/atom:entry');
252 if ($xpath->query('/rss/channel')->length > 0) {
253 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
255 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
256 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
258 if (empty($author["author-name"])) {
259 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
262 if (empty($author["author-name"])) {
263 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
266 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
268 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
270 $entries = $xpath->query('/rss/channel/item');
274 $author["author-link"] = $contact["url"];
276 if (empty($author["author-name"])) {
277 $author["author-name"] = $contact["name"];
280 $author["author-avatar"] = $contact["thumb"];
282 $author["owner-link"] = $contact["url"];
283 $author["owner-name"] = $contact["name"];
284 $author["owner-avatar"] = $contact["thumb"];
288 $header["uid"] = $importer["uid"] ?? 0;
289 $header["network"] = Protocol::FEED;
291 $header["origin"] = 0;
292 $header["gravity"] = GRAVITY_PARENT;
293 $header["private"] = Item::PUBLIC;
294 $header["verb"] = Activity::POST;
295 $header["object-type"] = Activity\ObjectType::NOTE;
297 $header["contact-id"] = $contact["id"] ?? 0;
299 if (!is_object($entries)) {
300 Logger::info("There are no entries in this feed.");
305 $creation_dates = [];
307 // Limit the number of items that are about to be fetched
308 $total_items = ($entries->length - 1);
309 $max_items = DI::config()->get('system', 'max_feed_items');
310 if (($max_items > 0) && ($total_items > $max_items)) {
311 $total_items = $max_items;
316 // Importing older entries first
317 for ($i = $total_items; $i >= 0; --$i) {
318 $entry = $entries->item($i);
320 $item = array_merge($header, $author);
322 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
323 if (!is_object($alternate)) {
324 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
326 if (is_object($alternate)) {
327 foreach ($alternate AS $attribute) {
328 if ($attribute->name == "href") {
329 $item["plink"] = $attribute->textContent;
334 if (empty($item["plink"])) {
335 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
338 if (empty($item["plink"])) {
339 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
342 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
344 if (empty($item["uri"])) {
345 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
348 if (empty($item["uri"])) {
349 $item["uri"] = $item["plink"];
352 // Add the base path if missing
353 $item["uri"] = Network::addBasePath($item["uri"], $basepath);
354 $item["plink"] = Network::addBasePath($item["plink"], $basepath);
356 $orig_plink = $item["plink"];
358 $item["plink"] = DI::httpRequest()->finalUrl($item["plink"]);
360 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
362 if (empty($item["title"])) {
363 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
365 if (empty($item["title"])) {
366 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
369 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
371 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
373 if (empty($published)) {
374 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
377 if (empty($published)) {
378 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
381 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
383 if (empty($updated) && !empty($published)) {
384 $updated = $published;
387 if (empty($published) && !empty($updated)) {
388 $published = $updated;
391 if ($published != "") {
392 $item["created"] = $published;
395 if ($updated != "") {
396 $item["edited"] = $updated;
400 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
401 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
402 $previous = Item::selectFirst(['id', 'created'], $condition);
403 if (DBA::isResult($previous)) {
404 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
405 $creation_dates[] = $previous['created'];
406 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
409 $creation_dates[] = DateTimeFormat::utc($item['created']);
412 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
414 if (empty($creator)) {
415 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
418 if (empty($creator)) {
419 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
422 if ($creator != "") {
423 $item["author-name"] = $creator;
426 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
428 if ($creator != "") {
429 $item["author-name"] = $creator;
433 // <category>Ausland</category>
434 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
438 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
439 foreach ($enclosures AS $enclosure) {
444 foreach ($enclosure->attributes AS $attribute) {
445 if (in_array($attribute->name, ["url", "href"])) {
446 $href = $attribute->textContent;
447 } elseif ($attribute->name == "length") {
448 $length = (int)$attribute->textContent;
449 } elseif ($attribute->name == "type") {
450 $type = $attribute->textContent;
455 $attachments[] = ['type' => Post\Media::DOCUMENT, 'url' => $href, 'mimetype' => $type, 'size' => $length];
460 $categories = $xpath->query("category", $entry);
461 foreach ($categories AS $category) {
462 $taglist[] = $category->nodeValue;
465 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
468 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
471 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
473 if (empty($summary)) {
474 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
482 if ($body == $summary) {
486 // remove the content of the title if it is identically to the body
487 // This helps with auto generated titles e.g. from tumblr
488 if (self::titleIsBody($item["title"], $body)) {
491 $item["body"] = HTML::toBBCode($body, $basepath);
493 // Remove tracking pixels
494 $item["body"] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item["body"]);
496 if (($item["body"] == '') && ($item["title"] != '')) {
497 $item["body"] = $item["title"];
504 } elseif (!Item::isValid($item)) {
505 Logger::info('Feed is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
510 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
511 // Handle enclosures and treat them as preview picture
512 foreach ($attachments AS $attachment) {
513 if ($attachment["mimetype"] == "image/jpeg") {
514 $preview = $attachment["url"];
518 // Remove a possible link to the item itself
519 $item["body"] = str_replace($item["plink"], '', $item["body"]);
520 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
522 // Replace the content when the title is longer than the body
523 $replace = (strlen($item["title"]) > strlen($item["body"]));
525 // Replace it, when there is an image in the body
526 if (strstr($item["body"], '[/img]')) {
530 // Replace it, when there is a link in the body
531 if (strstr($item["body"], '[/url]')) {
535 $saved_body = $item["body"];
536 $saved_title = $item["title"];
539 $item["body"] = trim($item["title"]);
542 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
543 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
544 // When the fetched page info text is longer than the body, we do try to enhance the body
545 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
546 // The body is not part of the fetched page info title or page info text. So we add the text to the body
547 $item['body'] .= "\n\n" . $data['text'];
549 // Else we replace the body with the page info text
550 $item['body'] = $data['text'];
554 $data = PageInfo::queryUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
557 // Take the data that was provided by the feed if the query is empty
558 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
559 $data['title'] = $saved_title;
560 $item["body"] = $saved_body;
563 $data_text = strip_tags(trim($data['text'] ?? ''));
564 $item_body = strip_tags(trim($item['body'] ?? ''));
566 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
570 // We always strip the title since it will be added in the page information
572 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromData($data, false);
573 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
574 $item["object-type"] = Activity\ObjectType::BOOKMARK;
578 if (!empty($summary)) {
579 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
582 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
583 if (empty($taglist)) {
584 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
586 $item["body"] .= "\n" . self::tagToString($taglist);
591 // Add the link to the original feed entry if not present in feed
592 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
593 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
597 Logger::info('Stored feed', ['item' => $item]);
599 $notify = Item::isRemoteSelf($contact, $item);
601 // Distributed items should have a well formatted URI.
602 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
604 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
606 unset($item['thr-parent']);
607 unset($item['parent-uri']);
609 // Set the delivery priority for "remote self" to "medium"
610 $notify = PRIORITY_MEDIUM;
613 $postings[] = ['item' => $item, 'notify' => $notify,
614 'taglist' => $taglist, 'attachments' => $attachments];
617 if (!empty($postings)) {
618 $total = count($postings);
620 // Posts shouldn't be delayed more than a day
621 $interval = max(1440, self::getPollInterval($contact));
622 $delay = round(($interval * 60) / $total);
623 Logger::notice('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
630 foreach ($postings as $posting) {
632 $publish_at = DateTimeFormat::utc('now + ' . $post_delay . ' second');
633 Logger::notice('Got publishing date', ['delay' => $delay, 'publish_at' => $publish_at, 'cid' => $contact['id'], 'url' => $contact['url']]);
634 $post_delay += $delay;
637 $id = Item::insert($posting['item'], $posting['notify']);
639 Logger::notice("Feed for contact " . $contact["url"] . " stored under id " . $id);
641 if (!empty($id) && (!empty($posting['taglist']) || !empty($posting['attachments']))) {
642 $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
643 foreach ($posting['taglist'] as $tag) {
644 Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
646 foreach ($posting['attachments'] as $attachment) {
647 $attachment['uri-id'] = $feeditem['uri-id'];
648 Post\Media::insert($attachment);
654 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
655 self::adjustPollFrequency($contact, $creation_dates);
658 return ["header" => $author, "items" => $items];
662 * Automatically adjust the poll frequency according to the post frequency
664 * @param array $contact
665 * @param array $creation_dates
668 private static function adjustPollFrequency(array $contact, array $creation_dates)
670 if ($contact['network'] != Protocol::FEED) {
671 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
675 if (!empty($creation_dates)) {
676 // Count the post frequency and the earliest and latest post date
680 $oldest_date = $newest_date = '';
682 foreach ($creation_dates as $date) {
683 $timestamp = strtotime($date);
684 $day = intdiv($timestamp, 86400);
685 $hour = $timestamp % 86400;
687 // Only have a look at values from the last seven days
688 if (((time() / 86400) - $day) < 7) {
689 if (empty($frequency[$day])) {
690 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
692 ++$frequency[$day]['count'];
693 if ($frequency[$day]['low'] > $hour) {
694 $frequency[$day]['low'] = $hour;
696 if ($frequency[$day]['high'] < $hour) {
697 $frequency[$day]['high'] = $hour;
701 if ($oldest > $day) {
703 $oldest_date = $date;
706 if ($newest < $day) {
708 $newest_date = $date;
712 if (count($creation_dates) == 1) {
713 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
714 $priority = 8; // Poll once a day
717 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
718 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']]);
719 $priority = 10; // Poll every month
722 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
723 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']]);
724 $priority = 9; // Poll every week
727 if (empty($priority) && empty($frequency)) {
728 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']]);
729 $priority = 8; // Poll once a day
732 if (empty($priority)) {
733 // Calculate the highest "posts per day" value
735 foreach ($frequency as $entry) {
736 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
740 // We take the earliest and latest post day and interpolate the number of post per day
741 // that would had been created with this post frequency
743 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
744 $duration = max($entry['high'] - $entry['low'], 14400);
745 $ppd = (86400 / $duration) * $entry['count'];
751 $priority = 1; // Poll every quarter hour
752 } elseif ($max > 24) {
753 $priority = 2; // Poll half an hour
754 } elseif ($max > 12) {
755 $priority = 3; // Poll hourly
756 } elseif ($max > 8) {
757 $priority = 4; // Poll every two hours
758 } elseif ($max > 4) {
759 $priority = 5; // Poll every three hours
760 } elseif ($max > 2) {
761 $priority = 6; // Poll every six hours
763 $priority = 7; // Poll twice a day
765 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
768 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
769 $priority = 8; // Poll once a day
772 if ($contact['rating'] != $priority) {
773 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
774 DBA::update('contact', ['rating' => $priority], ['id' => $contact['id']]);
779 * Get the poll interval for the given contact array
781 * @param array $contact
782 * @return int Poll interval in minutes
784 public static function getPollInterval(array $contact)
786 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
787 $ratings = [0, 3, 7, 8, 9, 10];
788 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
789 $rating = $contact['rating'];
790 } elseif (array_key_exists($contact['priority'], $ratings)) {
791 $rating = $ratings[$contact['priority']];
796 // Check once a week per default for all other networks
800 // Friendica and OStatus are checked once a day
801 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
805 // Check archived contacts or contacts with unsupported protocols once a month
806 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
814 * Based on $contact['priority'], should we poll this site now? Or later?
817 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
819 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
821 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
822 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
824 return $poll_intervals[$rating];
828 * Convert a tag array to a tag string
831 * @return string tag string
833 private static function tagToString(array $tags)
837 foreach ($tags as $tag) {
842 $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
848 private static function titleIsBody($title, $body)
850 $title = strip_tags($title);
851 $title = trim($title);
852 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
853 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
855 $body = strip_tags($body);
857 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
858 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
860 if (strlen($title) < strlen($body)) {
861 $body = substr($body, 0, strlen($title));
864 if (($title != $body) && (substr($title, -3) == "...")) {
865 $pos = strrpos($title, "...");
867 $title = substr($title, 0, $pos);
868 $body = substr($body, 0, $pos);
871 return ($title == $body);
875 * Creates the Atom feed for a given nickname
878 * - activity (default): all the public posts
879 * - posts: all the public top-level posts
880 * - comments: all the public replies
882 * Updates the provided last_update parameter if the result comes from the
883 * cache or it is empty
885 * @param string $owner_nick Nickname of the feed owner
886 * @param string $last_update Date of the last update
887 * @param integer $max_items Number of maximum items to fetch
888 * @param string $filter Feed items filter (activity, posts or comments)
889 * @param boolean $nocache Wether to bypass caching
891 * @return string Atom feed
892 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
893 * @throws \ImagickException
895 public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
897 $stamp = microtime(true);
899 $owner = User::getOwnerDataByNick($owner_nick);
904 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
906 $previous_created = $last_update;
908 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
909 if ((time() - strtotime($owner['last-item'])) < 15*60) {
910 $result = DI::cache()->get($cachekey);
911 if (!$nocache && !is_null($result)) {
912 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
913 return $result['feed'];
917 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
918 $authorid = Contact::getIdForURL($owner["url"]);
920 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
921 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
922 $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
923 Item::PRIVATE, Protocol::ACTIVITYPUB,
924 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
926 if ($filter === 'comments') {
927 $condition[0] .= " AND `object-type` = ? ";
928 $condition[] = Activity\ObjectType::COMMENT;
931 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
932 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
933 $condition[] = $owner["id"];
934 $condition[] = $authorid;
937 $params = ['order' => ['received' => true], 'limit' => $max_items];
939 if ($filter === 'posts') {
940 $ret = Item::selectThread([], $condition, $params);
942 $ret = Item::select([], $condition, $params);
945 $items = Item::inArray($ret);
947 $doc = new DOMDocument('1.0', 'utf-8');
948 $doc->formatOutput = true;
950 $root = self::addHeader($doc, $owner, $filter);
952 foreach ($items as $item) {
953 $entry = self::entry($doc, $item, $owner);
954 $root->appendChild($entry);
956 if ($last_update < $item['created']) {
957 $last_update = $item['created'];
961 $feeddata = trim($doc->saveXML());
963 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
964 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
966 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
972 * Adds the header elements to the XML document
974 * @param DOMDocument $doc XML document
975 * @param array $owner Contact data of the poster
976 * @param string $filter The related feed filter (activity, posts or comments)
978 * @return object header root element
979 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
981 private static function addHeader(DOMDocument $doc, array $owner, $filter)
983 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
984 $doc->appendChild($root);
987 $selfUri = '/feed/' . $owner["nick"] . '/';
990 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
994 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
997 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1002 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1003 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1004 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1005 XML::addElement($doc, $root, "title", $title);
1006 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1007 XML::addElement($doc, $root, "logo", $owner["photo"]);
1008 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1010 $author = self::addAuthor($doc, $owner);
1011 $root->appendChild($author);
1013 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1014 XML::addElement($doc, $root, "link", "", $attributes);
1016 OStatus::hublinks($doc, $root, $owner["nick"]);
1018 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1019 XML::addElement($doc, $root, "link", "", $attributes);
1025 * Adds the author element to the XML document
1027 * @param DOMDocument $doc XML document
1028 * @param array $owner Contact data of the poster
1030 * @return \DOMElement author element
1031 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1033 private static function addAuthor(DOMDocument $doc, array $owner)
1035 $author = $doc->createElement("author");
1036 XML::addElement($doc, $author, "uri", $owner["url"]);
1037 XML::addElement($doc, $author, "name", $owner["nick"]);
1038 XML::addElement($doc, $author, "email", $owner["addr"]);
1044 * Adds an entry element to the XML document
1046 * @param DOMDocument $doc XML document
1047 * @param array $item Data of the item that is to be posted
1048 * @param array $owner Contact data of the poster
1049 * @param bool $toplevel optional default false
1051 * @return \DOMElement Entry element
1052 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1053 * @throws \ImagickException
1055 private static function entry(DOMDocument $doc, array $item, array $owner)
1059 $repeated_guid = OStatus::getResharedGuid($item);
1060 if ($repeated_guid != "") {
1061 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
1068 return self::noteEntry($doc, $item, $owner);
1072 * Adds an entry element with reshared content
1074 * @param DOMDocument $doc XML document
1075 * @param array $item Data of the item that is to be posted
1076 * @param array $owner Contact data of the poster
1077 * @param string $repeated_guid guid
1078 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1080 * @return bool Entry element
1081 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1082 * @throws \ImagickException
1084 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
1086 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1087 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1090 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1092 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1093 'network' => Protocol::FEDERATED];
1094 $repeated_item = Item::selectFirst([], $condition);
1095 if (!DBA::isResult($repeated_item)) {
1099 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
1101 self::entryFooter($doc, $entry, $item, $owner);
1107 * Adds a regular entry element
1109 * @param DOMDocument $doc XML document
1110 * @param array $item Data of the item that is to be posted
1111 * @param array $owner Contact data of the poster
1112 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1114 * @return \DOMElement Entry element
1115 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1116 * @throws \ImagickException
1118 private static function noteEntry(DOMDocument $doc, array $item, array $owner)
1120 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1121 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1124 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1126 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1128 self::entryFooter($doc, $entry, $item, $owner);
1134 * Adds elements to the XML document
1136 * @param DOMDocument $doc XML document
1137 * @param \DOMElement $entry Entry element where the content is added
1138 * @param array $item Data of the item that is to be posted
1139 * @param array $owner Contact data of the poster
1140 * @param string $title Title for the post
1141 * @param string $verb The activity verb
1142 * @param bool $complete Add the "status_net" element?
1143 * @param bool $feed_mode Behave like a regular feed for users if true
1145 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1147 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
1150 $verb = OStatus::constructVerb($item);
1153 XML::addElement($doc, $entry, "id", $item["uri"]);
1154 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1156 $body = OStatus::formatPicturePost($item['body']);
1158 $body = BBCode::convert($body, false, BBCode::OSTATUS);
1160 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1162 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1163 "href" => DI::baseUrl()."/display/".$item["guid"]]
1166 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1167 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1171 * Adds the elements at the foot of an entry to the XML document
1173 * @param DOMDocument $doc XML document
1174 * @param object $entry The entry element where the elements are added
1175 * @param array $item Data of the item that is to be posted
1176 * @param array $owner Contact data of the poster
1177 * @param bool $complete default true
1179 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1181 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1185 if ($item['gravity'] != GRAVITY_PARENT) {
1186 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1188 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $item['thr-parent']]);
1190 if (DBA::isResult($thrparent)) {
1191 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1192 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1193 $parent_plink = $thrparent["plink"];
1195 $mentioned[$parent["author-link"]] = $parent["author-link"];
1196 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1197 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1201 "ref" => $item['thr-parent'],
1202 "href" => $parent_plink];
1203 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1207 "href" => $parent_plink];
1208 XML::addElement($doc, $entry, "link", "", $attributes);
1211 // uri-id isn't present for follow entry pseudo-items
1212 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1213 foreach ($tags as $tag) {
1214 $mentioned[$tag['url']] = $tag['url'];
1217 foreach ($tags as $tag) {
1218 if ($tag['type'] == Tag::HASHTAG) {
1219 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
1223 OStatus::getAttachment($doc, $entry, $item);
1227 * Fetch or create title for feed entry
1229 * @param array $item
1230 * @return string title
1232 private static function getTitle(array $item)
1234 if ($item['title'] != '') {
1235 return BBCode::convert($item['title'], false, BBCode::OSTATUS);
1238 // Fetch information about the post
1239 $siteinfo = BBCode::getAttachedData($item["body"]);
1240 if (isset($siteinfo["title"])) {
1241 return $siteinfo["title"];
1244 // If no bookmark is found then take the first line
1245 // Remove the share element before fetching the first line
1246 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1248 $title = HTML::toPlaintext(BBCode::convert($title, false), 0, true)."\n";
1249 $pos = strpos($title, "\n");
1251 if (($pos == 0) || ($pos > 100)) {
1256 return substr($title, 0, $pos) . $trailer;