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\Item;
36 use Friendica\Model\Post;
37 use Friendica\Model\Tag;
38 use Friendica\Model\User;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Network;
41 use Friendica\Util\ParseUrl;
42 use Friendica\Util\Strings;
43 use Friendica\Util\XML;
46 * This class contain functions to import feeds (RSS/RDF/Atom)
51 * consume - process atom feed and update anything/everything we might need to update
53 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
55 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
56 * It is this person's stuff that is going to be updated.
57 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
58 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
59 * have a contact record.
60 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
61 * might not) try and subscribe to it.
62 * $datedir sorts in reverse order
63 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
64 * imported prior to its children being seen in the stream unless we are certain
65 * of how the feed is arranged/ordered.
66 * With $pass = 1, we only pull parent items out of the stream.
67 * With $pass = 2, we only pull children (comments/likes).
69 * So running this twice, first with pass 1 and then with pass 2 will do the right
70 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
71 * model where comments can have sub-threads. That would require some massive sorting
72 * to get all the feed items into a mostly linear ordering, and might still require
76 * @param array $importer
77 * @param array $contact
79 * @throws ImagickException
80 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
82 public static function consume($xml, array $importer, array $contact, &$hub)
84 if ($contact['network'] === Protocol::OSTATUS) {
85 Logger::info('Consume OStatus messages');
86 OStatus::import($xml, $importer, $contact, $hub);
91 if ($contact['network'] === Protocol::FEED) {
92 Logger::info('Consume feeds');
93 self::import($xml, $importer, $contact);
98 if ($contact['network'] === Protocol::DFRN) {
99 Logger::info('Consume DFRN messages');
100 $dfrn_importer = DFRN::getImporter($contact['id'], $importer['uid']);
101 if (!empty($dfrn_importer)) {
102 Logger::info('Now import the DFRN feed');
103 DFRN::import($xml, $dfrn_importer, true);
110 * Read a RSS/RDF/Atom feed and create an item entry for it
112 * @param string $xml The feed data
113 * @param array $importer The user record of the importer
114 * @param array $contact The contact record of the feed
116 * @return array Returns the header and the first item in dry run mode
117 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
119 public static function import($xml, array $importer = [], array $contact = [])
121 $dryRun = empty($importer) && empty($contact);
124 Logger::info("Test Atom/RSS feed");
126 Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
130 Logger::info('XML is empty.');
134 if (!empty($contact['poll'])) {
135 $basepath = $contact['poll'];
136 } elseif (!empty($contact['url'])) {
137 $basepath = $contact['url'];
142 $doc = new DOMDocument();
143 @$doc->loadXML(trim($xml));
144 $xpath = new DOMXPath($doc);
145 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
146 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
147 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
148 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
149 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
150 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
151 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
157 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
158 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
159 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
161 if (empty($author["author-name"])) {
162 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
164 $entries = $xpath->query('/rdf:RDF/rss:item');
168 if ($xpath->query('/atom:feed')->length > 0) {
169 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
170 if (is_object($alternate)) {
171 foreach ($alternate AS $attribute) {
172 if ($attribute->name == "href") {
173 $author["author-link"] = $attribute->textContent;
178 if (empty($author["author-link"])) {
179 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
180 if (is_object($self)) {
181 foreach ($self AS $attribute) {
182 if ($attribute->name == "href") {
183 $author["author-link"] = $attribute->textContent;
189 if (empty($author["author-link"])) {
190 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
192 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
194 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
196 if (empty($author["author-name"])) {
197 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
200 if (empty($author["author-name"])) {
201 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
204 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
206 $author["author-name"] = $value;
210 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
212 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
213 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
215 $author["author-link"] = $value;
218 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
220 $author["author-nick"] = $value;
223 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
225 $author["author-location"] = $value;
228 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
230 $author["author-about"] = $value;
233 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
234 if (is_object($avatar)) {
235 foreach ($avatar AS $attribute) {
236 if ($attribute->name == "href") {
237 $author["author-avatar"] = $attribute->textContent;
243 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
245 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
247 $entries = $xpath->query('/atom:feed/atom:entry');
251 if ($xpath->query('/rss/channel')->length > 0) {
252 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
254 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
255 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
257 if (empty($author["author-name"])) {
258 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
261 if (empty($author["author-name"])) {
262 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
265 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
267 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
269 $entries = $xpath->query('/rss/channel/item');
273 $author["author-link"] = $contact["url"];
275 if (empty($author["author-name"])) {
276 $author["author-name"] = $contact["name"];
279 $author["author-avatar"] = $contact["thumb"];
281 $author["owner-link"] = $contact["url"];
282 $author["owner-name"] = $contact["name"];
283 $author["owner-avatar"] = $contact["thumb"];
287 $header["uid"] = $importer["uid"] ?? 0;
288 $header["network"] = Protocol::FEED;
290 $header["origin"] = 0;
291 $header["gravity"] = GRAVITY_PARENT;
292 $header["private"] = Item::PUBLIC;
293 $header["verb"] = Activity::POST;
294 $header["object-type"] = Activity\ObjectType::NOTE;
296 $header["contact-id"] = $contact["id"] ?? 0;
298 if (!is_object($entries)) {
299 Logger::info("There are no entries in this feed.");
304 $creation_dates = [];
306 // Limit the number of items that are about to be fetched
307 $total_items = ($entries->length - 1);
308 $max_items = DI::config()->get('system', 'max_feed_items');
309 if (($max_items > 0) && ($total_items > $max_items)) {
310 $total_items = $max_items;
313 // Importing older entries first
314 for ($i = $total_items; $i >= 0; --$i) {
315 $entry = $entries->item($i);
317 $item = array_merge($header, $author);
319 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
320 if (!is_object($alternate)) {
321 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
323 if (is_object($alternate)) {
324 foreach ($alternate AS $attribute) {
325 if ($attribute->name == "href") {
326 $item["plink"] = $attribute->textContent;
331 if (empty($item["plink"])) {
332 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
335 if (empty($item["plink"])) {
336 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
339 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
341 if (empty($item["uri"])) {
342 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
345 if (empty($item["uri"])) {
346 $item["uri"] = $item["plink"];
349 // Add the base path if missing
350 $item["uri"] = Network::addBasePath($item["uri"], $basepath);
351 $item["plink"] = Network::addBasePath($item["plink"], $basepath);
353 $orig_plink = $item["plink"];
355 $item["plink"] = DI::httpRequest()->finalUrl($item["plink"]);
357 $item["parent-uri"] = $item["uri"];
359 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
361 if (empty($item["title"])) {
362 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
364 if (empty($item["title"])) {
365 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
368 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
370 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
372 if (empty($published)) {
373 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
376 if (empty($published)) {
377 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
380 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
382 if (empty($updated) && !empty($published)) {
383 $updated = $published;
386 if (empty($published) && !empty($updated)) {
387 $published = $updated;
390 if ($published != "") {
391 $item["created"] = $published;
394 if ($updated != "") {
395 $item["edited"] = $updated;
399 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
400 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
401 $previous = Item::selectFirst(['id', 'created'], $condition);
402 if (DBA::isResult($previous)) {
403 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
404 $creation_dates[] = $previous['created'];
405 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
408 $creation_dates[] = DateTimeFormat::utc($item['created']);
411 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
413 if (empty($creator)) {
414 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
417 if (empty($creator)) {
418 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
421 if ($creator != "") {
422 $item["author-name"] = $creator;
425 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
427 if ($creator != "") {
428 $item["author-name"] = $creator;
432 // <category>Ausland</category>
433 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
437 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
438 foreach ($enclosures AS $enclosure) {
443 foreach ($enclosure->attributes AS $attribute) {
444 if (in_array($attribute->name, ["url", "href"])) {
445 $href = $attribute->textContent;
446 } elseif ($attribute->name == "length") {
447 $length = (int)$attribute->textContent;
448 } elseif ($attribute->name == "type") {
449 $type = $attribute->textContent;
454 $attachments[] = ['type' => Post\Media::DOCUMENT, 'url' => $href, 'mimetype' => $type, 'size' => $length];
459 $categories = $xpath->query("category", $entry);
460 foreach ($categories AS $category) {
461 $taglist[] = $category->nodeValue;
464 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
467 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
470 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
472 if (empty($summary)) {
473 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
481 if ($body == $summary) {
485 // remove the content of the title if it is identically to the body
486 // This helps with auto generated titles e.g. from tumblr
487 if (self::titleIsBody($item["title"], $body)) {
490 $item["body"] = HTML::toBBCode($body, $basepath);
492 // Remove tracking pixels
493 $item["body"] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item["body"]);
495 if (($item["body"] == '') && ($item["title"] != '')) {
496 $item["body"] = $item["title"];
503 } elseif (!Item::isValid($item)) {
504 Logger::info('Feed is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
509 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
510 // Handle enclosures and treat them as preview picture
511 foreach ($attachments AS $attachment) {
512 if ($attachment["mimetype"] == "image/jpeg") {
513 $preview = $attachment["url"];
517 // Remove a possible link to the item itself
518 $item["body"] = str_replace($item["plink"], '', $item["body"]);
519 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
521 // Replace the content when the title is longer than the body
522 $replace = (strlen($item["title"]) > strlen($item["body"]));
524 // Replace it, when there is an image in the body
525 if (strstr($item["body"], '[/img]')) {
529 // Replace it, when there is a link in the body
530 if (strstr($item["body"], '[/url]')) {
534 $saved_body = $item["body"];
535 $saved_title = $item["title"];
538 $item["body"] = trim($item["title"]);
541 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
542 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
543 // When the fetched page info text is longer than the body, we do try to enhance the body
544 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
545 // The body is not part of the fetched page info title or page info text. So we add the text to the body
546 $item['body'] .= "\n\n" . $data['text'];
548 // Else we replace the body with the page info text
549 $item['body'] = $data['text'];
553 $data = PageInfo::queryUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
555 // Take the data that was provided by the feed if the query is empty
556 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
557 $data['title'] = $saved_title;
558 $item["body"] = $saved_body;
561 $data_text = strip_tags(trim($data['text'] ?? ''));
562 $item_body = strip_tags(trim($item['body'] ?? ''));
564 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
568 // We always strip the title since it will be added in the page information
570 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromData($data, false);
571 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
572 $item["object-type"] = Activity\ObjectType::BOOKMARK;
575 if (!empty($summary)) {
576 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
579 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
580 if (empty($taglist)) {
581 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
583 $item["body"] .= "\n" . self::tagToString($taglist);
588 // Add the link to the original feed entry if not present in feed
589 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
590 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
594 Logger::info('Stored feed', ['item' => $item]);
596 $notify = Item::isRemoteSelf($contact, $item);
598 // Distributed items should have a well formatted URI.
599 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
601 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
603 unset($item['parent-uri']);
605 // Set the delivery priority for "remote self" to "medium"
606 $notify = PRIORITY_MEDIUM;
609 $id = Item::insert($item, $notify);
611 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
613 if (!empty($id) && (!empty($taglist) || !empty($attachments))) {
614 $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
615 foreach ($taglist as $tag) {
616 Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
618 foreach ($attachments as $attachment) {
619 $attachment['uri-id'] = $feeditem['uri-id'];
620 Post\Media::insert($attachment);
625 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
626 self::adjustPollFrequency($contact, $creation_dates);
629 return ["header" => $author, "items" => $items];
633 * Automatically adjust the poll frequency according to the post frequency
635 * @param array $contact
636 * @param array $creation_dates
639 private static function adjustPollFrequency(array $contact, array $creation_dates)
641 if ($contact['network'] != Protocol::FEED) {
642 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
646 if (!empty($creation_dates)) {
647 // Count the post frequency and the earliest and latest post date
651 $oldest_date = $newest_date = '';
653 foreach ($creation_dates as $date) {
654 $timestamp = strtotime($date);
655 $day = intdiv($timestamp, 86400);
656 $hour = $timestamp % 86400;
658 // Only have a look at values from the last seven days
659 if (((time() / 86400) - $day) < 7) {
660 if (empty($frequency[$day])) {
661 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
663 ++$frequency[$day]['count'];
664 if ($frequency[$day]['low'] > $hour) {
665 $frequency[$day]['low'] = $hour;
667 if ($frequency[$day]['high'] < $hour) {
668 $frequency[$day]['high'] = $hour;
672 if ($oldest > $day) {
674 $oldest_date = $date;
677 if ($newest < $day) {
679 $newest_date = $date;
683 if (count($creation_dates) == 1) {
684 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
685 $priority = 8; // Poll once a day
688 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
689 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']]);
690 $priority = 10; // Poll every month
693 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
694 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']]);
695 $priority = 9; // Poll every week
698 if (empty($priority) && empty($frequency)) {
699 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']]);
700 $priority = 8; // Poll once a day
703 if (empty($priority)) {
704 // Calculate the highest "posts per day" value
706 foreach ($frequency as $entry) {
707 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
711 // We take the earliest and latest post day and interpolate the number of post per day
712 // that would had been created with this post frequency
714 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
715 $duration = max($entry['high'] - $entry['low'], 14400);
716 $ppd = (86400 / $duration) * $entry['count'];
722 $priority = 1; // Poll every quarter hour
723 } elseif ($max > 24) {
724 $priority = 2; // Poll half an hour
725 } elseif ($max > 12) {
726 $priority = 3; // Poll hourly
727 } elseif ($max > 8) {
728 $priority = 4; // Poll every two hours
729 } elseif ($max > 4) {
730 $priority = 5; // Poll every three hours
731 } elseif ($max > 2) {
732 $priority = 6; // Poll every six hours
734 $priority = 7; // Poll twice a day
736 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
739 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
740 $priority = 8; // Poll once a day
743 if ($contact['rating'] != $priority) {
744 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
745 DBA::update('contact', ['rating' => $priority], ['id' => $contact['id']]);
750 * Convert a tag array to a tag string
753 * @return string tag string
755 private static function tagToString(array $tags)
759 foreach ($tags as $tag) {
764 $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
770 private static function titleIsBody($title, $body)
772 $title = strip_tags($title);
773 $title = trim($title);
774 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
775 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
777 $body = strip_tags($body);
779 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
780 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
782 if (strlen($title) < strlen($body)) {
783 $body = substr($body, 0, strlen($title));
786 if (($title != $body) && (substr($title, -3) == "...")) {
787 $pos = strrpos($title, "...");
789 $title = substr($title, 0, $pos);
790 $body = substr($body, 0, $pos);
793 return ($title == $body);
797 * Creates the Atom feed for a given nickname
800 * - activity (default): all the public posts
801 * - posts: all the public top-level posts
802 * - comments: all the public replies
804 * Updates the provided last_update parameter if the result comes from the
805 * cache or it is empty
807 * @param string $owner_nick Nickname of the feed owner
808 * @param string $last_update Date of the last update
809 * @param integer $max_items Number of maximum items to fetch
810 * @param string $filter Feed items filter (activity, posts or comments)
811 * @param boolean $nocache Wether to bypass caching
813 * @return string Atom feed
814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
815 * @throws \ImagickException
817 public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
819 $stamp = microtime(true);
821 $owner = User::getOwnerDataByNick($owner_nick);
826 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
828 $previous_created = $last_update;
830 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
831 if ((time() - strtotime($owner['last-item'])) < 15*60) {
832 $result = DI::cache()->get($cachekey);
833 if (!$nocache && !is_null($result)) {
834 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
835 return $result['feed'];
839 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
840 $authorid = Contact::getIdForURL($owner["url"]);
842 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
843 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
844 $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
845 Item::PRIVATE, Protocol::ACTIVITYPUB,
846 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
848 if ($filter === 'comments') {
849 $condition[0] .= " AND `object-type` = ? ";
850 $condition[] = Activity\ObjectType::COMMENT;
853 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
854 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
855 $condition[] = $owner["id"];
856 $condition[] = $authorid;
859 $params = ['order' => ['received' => true], 'limit' => $max_items];
861 if ($filter === 'posts') {
862 $ret = Item::selectThread([], $condition, $params);
864 $ret = Item::select([], $condition, $params);
867 $items = Item::inArray($ret);
869 $doc = new DOMDocument('1.0', 'utf-8');
870 $doc->formatOutput = true;
872 $root = self::addHeader($doc, $owner, $filter);
874 foreach ($items as $item) {
875 $entry = self::entry($doc, $item, $owner);
876 $root->appendChild($entry);
878 if ($last_update < $item['created']) {
879 $last_update = $item['created'];
883 $feeddata = trim($doc->saveXML());
885 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
886 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
888 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
894 * Adds the header elements to the XML document
896 * @param DOMDocument $doc XML document
897 * @param array $owner Contact data of the poster
898 * @param string $filter The related feed filter (activity, posts or comments)
900 * @return object header root element
901 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
903 private static function addHeader(DOMDocument $doc, array $owner, $filter)
905 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
906 $doc->appendChild($root);
909 $selfUri = '/feed/' . $owner["nick"] . '/';
912 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
916 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
919 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
924 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
925 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
926 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
927 XML::addElement($doc, $root, "title", $title);
928 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
929 XML::addElement($doc, $root, "logo", $owner["photo"]);
930 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
932 $author = self::addAuthor($doc, $owner);
933 $root->appendChild($author);
935 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
936 XML::addElement($doc, $root, "link", "", $attributes);
938 OStatus::hublinks($doc, $root, $owner["nick"]);
940 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
941 XML::addElement($doc, $root, "link", "", $attributes);
947 * Adds the author element to the XML document
949 * @param DOMDocument $doc XML document
950 * @param array $owner Contact data of the poster
952 * @return \DOMElement author element
953 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
955 private static function addAuthor(DOMDocument $doc, array $owner)
957 $author = $doc->createElement("author");
958 XML::addElement($doc, $author, "uri", $owner["url"]);
959 XML::addElement($doc, $author, "name", $owner["nick"]);
960 XML::addElement($doc, $author, "email", $owner["addr"]);
966 * Adds an entry element to the XML document
968 * @param DOMDocument $doc XML document
969 * @param array $item Data of the item that is to be posted
970 * @param array $owner Contact data of the poster
971 * @param bool $toplevel optional default false
973 * @return \DOMElement Entry element
974 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
975 * @throws \ImagickException
977 private static function entry(DOMDocument $doc, array $item, array $owner)
981 $repeated_guid = OStatus::getResharedGuid($item);
982 if ($repeated_guid != "") {
983 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
990 return self::noteEntry($doc, $item, $owner);
994 * Adds an entry element with reshared content
996 * @param DOMDocument $doc XML document
997 * @param array $item Data of the item that is to be posted
998 * @param array $owner Contact data of the poster
999 * @param string $repeated_guid guid
1000 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1002 * @return bool Entry element
1003 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1004 * @throws \ImagickException
1006 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
1008 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1009 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1012 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1014 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1015 'network' => Protocol::FEDERATED];
1016 $repeated_item = Item::selectFirst([], $condition);
1017 if (!DBA::isResult($repeated_item)) {
1021 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
1023 self::entryFooter($doc, $entry, $item, $owner);
1029 * Adds a regular entry element
1031 * @param DOMDocument $doc XML document
1032 * @param array $item Data of the item that is to be posted
1033 * @param array $owner Contact data of the poster
1034 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1036 * @return \DOMElement Entry element
1037 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1038 * @throws \ImagickException
1040 private static function noteEntry(DOMDocument $doc, array $item, array $owner)
1042 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1043 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1046 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1048 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1050 self::entryFooter($doc, $entry, $item, $owner);
1056 * Adds elements to the XML document
1058 * @param DOMDocument $doc XML document
1059 * @param \DOMElement $entry Entry element where the content is added
1060 * @param array $item Data of the item that is to be posted
1061 * @param array $owner Contact data of the poster
1062 * @param string $title Title for the post
1063 * @param string $verb The activity verb
1064 * @param bool $complete Add the "status_net" element?
1065 * @param bool $feed_mode Behave like a regular feed for users if true
1067 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1069 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
1072 $verb = OStatus::constructVerb($item);
1075 XML::addElement($doc, $entry, "id", $item["uri"]);
1076 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1078 $body = OStatus::formatPicturePost($item['body']);
1080 $body = BBCode::convert($body, false, BBCode::OSTATUS);
1082 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1084 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1085 "href" => DI::baseUrl()."/display/".$item["guid"]]
1088 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1089 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1093 * Adds the elements at the foot of an entry to the XML document
1095 * @param DOMDocument $doc XML document
1096 * @param object $entry The entry element where the elements are added
1097 * @param array $item Data of the item that is to be posted
1098 * @param array $owner Contact data of the poster
1099 * @param bool $complete default true
1101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1103 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1107 if ($item['gravity'] != GRAVITY_PARENT) {
1108 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1109 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1111 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
1113 if (DBA::isResult($thrparent)) {
1114 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1115 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1116 $parent_plink = $thrparent["plink"];
1118 $mentioned[$parent["author-link"]] = $parent["author-link"];
1119 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1120 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1124 "ref" => $parent_item,
1125 "href" => $parent_plink];
1126 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1130 "href" => $parent_plink];
1131 XML::addElement($doc, $entry, "link", "", $attributes);
1134 // uri-id isn't present for follow entry pseudo-items
1135 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1136 foreach ($tags as $tag) {
1137 $mentioned[$tag['url']] = $tag['url'];
1140 foreach ($tags as $tag) {
1141 if ($tag['type'] == Tag::HASHTAG) {
1142 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
1146 OStatus::getAttachment($doc, $entry, $item);
1150 * Fetch or create title for feed entry
1152 * @param array $item
1153 * @return string title
1155 private static function getTitle(array $item)
1157 if ($item['title'] != '') {
1158 return BBCode::convert($item['title'], false, BBCode::OSTATUS);
1161 // Fetch information about the post
1162 $siteinfo = BBCode::getAttachedData($item["body"]);
1163 if (isset($siteinfo["title"])) {
1164 return $siteinfo["title"];
1167 // If no bookmark is found then take the first line
1168 // Remove the share element before fetching the first line
1169 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1171 $title = HTML::toPlaintext(BBCode::convert($title, false), 0, true)."\n";
1172 $pos = strpos($title, "\n");
1174 if (($pos == 0) || ($pos > 100)) {
1179 return substr($title, 0, $pos) . $trailer;