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\Tag;
37 use Friendica\Model\User;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Network;
40 use Friendica\Util\ParseUrl;
41 use Friendica\Util\Strings;
42 use Friendica\Util\XML;
45 * This class contain functions to import feeds (RSS/RDF/Atom)
50 * consume - process atom feed and update anything/everything we might need to update
52 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
54 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
55 * It is this person's stuff that is going to be updated.
56 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
57 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
58 * have a contact record.
59 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
60 * might not) try and subscribe to it.
61 * $datedir sorts in reverse order
62 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
63 * imported prior to its children being seen in the stream unless we are certain
64 * of how the feed is arranged/ordered.
65 * With $pass = 1, we only pull parent items out of the stream.
66 * With $pass = 2, we only pull children (comments/likes).
68 * So running this twice, first with pass 1 and then with pass 2 will do the right
69 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
70 * model where comments can have sub-threads. That would require some massive sorting
71 * to get all the feed items into a mostly linear ordering, and might still require
75 * @param array $importer
76 * @param array $contact
78 * @throws ImagickException
79 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
81 public static function consume($xml, array $importer, array $contact, &$hub)
83 if ($contact['network'] === Protocol::OSTATUS) {
84 Logger::info('Consume OStatus messages');
85 OStatus::import($xml, $importer, $contact, $hub);
90 if ($contact['network'] === Protocol::FEED) {
91 Logger::info('Consume feeds');
92 self::import($xml, $importer, $contact);
97 if ($contact['network'] === Protocol::DFRN) {
98 Logger::info('Consume DFRN messages');
99 $dfrn_importer = DFRN::getImporter($contact['id'], $importer['uid']);
100 if (!empty($dfrn_importer)) {
101 Logger::info('Now import the DFRN feed');
102 DFRN::import($xml, $dfrn_importer, true);
109 * Read a RSS/RDF/Atom feed and create an item entry for it
111 * @param string $xml The feed data
112 * @param array $importer The user record of the importer
113 * @param array $contact The contact record of the feed
115 * @return array Returns the header and the first item in dry run mode
116 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
118 public static function import($xml, array $importer = [], array $contact = [])
120 $dryRun = empty($importer) && empty($contact);
123 Logger::info("Test Atom/RSS feed");
125 Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
129 Logger::info('XML is empty.');
133 if (!empty($contact['poll'])) {
134 $basepath = $contact['poll'];
135 } elseif (!empty($contact['url'])) {
136 $basepath = $contact['url'];
141 $doc = new DOMDocument();
142 @$doc->loadXML(trim($xml));
143 $xpath = new DOMXPath($doc);
144 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
145 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
146 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
147 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
148 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
149 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
150 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
156 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
157 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
158 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
160 if (empty($author["author-name"])) {
161 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
163 $entries = $xpath->query('/rdf:RDF/rss:item');
167 if ($xpath->query('/atom:feed')->length > 0) {
168 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
169 if (is_object($alternate)) {
170 foreach ($alternate AS $attribute) {
171 if ($attribute->name == "href") {
172 $author["author-link"] = $attribute->textContent;
177 if (empty($author["author-link"])) {
178 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
179 if (is_object($self)) {
180 foreach ($self AS $attribute) {
181 if ($attribute->name == "href") {
182 $author["author-link"] = $attribute->textContent;
188 if (empty($author["author-link"])) {
189 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
191 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
193 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
195 if (empty($author["author-name"])) {
196 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
199 if (empty($author["author-name"])) {
200 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
203 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
205 $author["author-name"] = $value;
209 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
211 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
212 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
214 $author["author-link"] = $value;
217 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
219 $author["author-nick"] = $value;
222 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
224 $author["author-location"] = $value;
227 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
229 $author["author-about"] = $value;
232 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
233 if (is_object($avatar)) {
234 foreach ($avatar AS $attribute) {
235 if ($attribute->name == "href") {
236 $author["author-avatar"] = $attribute->textContent;
242 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
244 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
246 $entries = $xpath->query('/atom:feed/atom:entry');
250 if ($xpath->query('/rss/channel')->length > 0) {
251 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
253 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
254 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
256 if (empty($author["author-name"])) {
257 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
260 if (empty($author["author-name"])) {
261 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
264 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
266 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
268 $entries = $xpath->query('/rss/channel/item');
272 $author["author-link"] = $contact["url"];
274 if (empty($author["author-name"])) {
275 $author["author-name"] = $contact["name"];
278 $author["author-avatar"] = $contact["thumb"];
280 $author["owner-link"] = $contact["url"];
281 $author["owner-name"] = $contact["name"];
282 $author["owner-avatar"] = $contact["thumb"];
286 $header["uid"] = $importer["uid"] ?? 0;
287 $header["network"] = Protocol::FEED;
289 $header["origin"] = 0;
290 $header["gravity"] = GRAVITY_PARENT;
291 $header["private"] = Item::PUBLIC;
292 $header["verb"] = Activity::POST;
293 $header["object-type"] = Activity\ObjectType::NOTE;
295 $header["contact-id"] = $contact["id"] ?? 0;
297 if (!is_object($entries)) {
298 Logger::info("There are no entries in this feed.");
303 $creation_dates = [];
305 // Limit the number of items that are about to be fetched
306 $total_items = ($entries->length - 1);
307 $max_items = DI::config()->get('system', 'max_feed_items');
308 if (($max_items > 0) && ($total_items > $max_items)) {
309 $total_items = $max_items;
312 // Importing older entries first
313 for ($i = $total_items; $i >= 0; --$i) {
314 $entry = $entries->item($i);
316 $item = array_merge($header, $author);
318 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
319 if (!is_object($alternate)) {
320 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
322 if (is_object($alternate)) {
323 foreach ($alternate AS $attribute) {
324 if ($attribute->name == "href") {
325 $item["plink"] = $attribute->textContent;
330 if (empty($item["plink"])) {
331 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
334 if (empty($item["plink"])) {
335 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
338 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
340 if (empty($item["uri"])) {
341 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
344 if (empty($item["uri"])) {
345 $item["uri"] = $item["plink"];
348 // Add the base path if missing
349 $item["uri"] = Network::addBasePath($item["uri"], $basepath);
350 $item["plink"] = Network::addBasePath($item["plink"], $basepath);
352 $orig_plink = $item["plink"];
354 $item["plink"] = DI::httpRequest()->finalUrl($item["plink"]);
356 $item["parent-uri"] = $item["uri"];
358 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
360 if (empty($item["title"])) {
361 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
363 if (empty($item["title"])) {
364 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
367 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
369 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
371 if (empty($published)) {
372 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
375 if (empty($published)) {
376 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
379 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
381 if (empty($updated) && !empty($published)) {
382 $updated = $published;
385 if (empty($published) && !empty($updated)) {
386 $published = $updated;
389 if ($published != "") {
390 $item["created"] = $published;
393 if ($updated != "") {
394 $item["edited"] = $updated;
398 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
399 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
400 $previous = Item::selectFirst(['id', 'created'], $condition);
401 if (DBA::isResult($previous)) {
402 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
403 $creation_dates[] = $previous['created'];
404 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
407 $creation_dates[] = DateTimeFormat::utc($item['created']);
410 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
412 if (empty($creator)) {
413 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
416 if (empty($creator)) {
417 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
420 if ($creator != "") {
421 $item["author-name"] = $creator;
424 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
426 if ($creator != "") {
427 $item["author-name"] = $creator;
431 // <category>Ausland</category>
432 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
436 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
437 foreach ($enclosures AS $enclosure) {
442 foreach ($enclosure->attributes AS $attribute) {
443 if (in_array($attribute->name, ["url", "href"])) {
444 $href = $attribute->textContent;
445 } elseif ($attribute->name == "length") {
446 $length = $attribute->textContent;
447 } elseif ($attribute->name == "type") {
448 $type = $attribute->textContent;
452 if (!empty($item["attach"])) {
453 $item["attach"] .= ',';
455 $item["attach"] = '';
458 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
460 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
464 $categories = $xpath->query("category", $entry);
465 foreach ($categories AS $category) {
466 $taglist[] = $category->nodeValue;
469 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
472 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
475 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
477 if (empty($summary)) {
478 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
486 if ($body == $summary) {
490 // remove the content of the title if it is identically to the body
491 // This helps with auto generated titles e.g. from tumblr
492 if (self::titleIsBody($item["title"], $body)) {
495 $item["body"] = HTML::toBBCode($body, $basepath);
497 if (($item["body"] == '') && ($item["title"] != '')) {
498 $item["body"] = $item["title"];
505 } elseif (!Item::isValid($item)) {
506 Logger::info('Feed is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
511 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
512 // Handle enclosures and treat them as preview picture
513 foreach ($attachments AS $attachment) {
514 if ($attachment["type"] == "image/jpeg") {
515 $preview = $attachment["link"];
519 // Remove a possible link to the item itself
520 $item["body"] = str_replace($item["plink"], '', $item["body"]);
521 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
523 // Replace the content when the title is longer than the body
524 $replace = (strlen($item["title"]) > strlen($item["body"]));
526 // Replace it, when there is an image in the body
527 if (strstr($item["body"], '[/img]')) {
531 // Replace it, when there is a link in the body
532 if (strstr($item["body"], '[/url]')) {
536 $saved_body = $item["body"];
537 $saved_title = $item["title"];
540 $item["body"] = trim($item["title"]);
543 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
544 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
545 // When the fetched page info text is longer than the body, we do try to enhance the body
546 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
547 // The body is not part of the fetched page info title or page info text. So we add the text to the body
548 $item['body'] .= "\n\n" . $data['text'];
550 // Else we replace the body with the page info text
551 $item['body'] = $data['text'];
555 $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;
575 unset($item["attach"]);
577 if (!empty($summary)) {
578 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
581 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
582 if (empty($taglist)) {
583 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
585 $item["body"] .= "\n" . self::tagToString($taglist);
590 // Add the link to the original feed entry if not present in feed
591 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
592 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
596 Logger::info('Stored feed', ['item' => $item]);
598 $notify = Item::isRemoteSelf($contact, $item);
600 // Distributed items should have a well formatted URI.
601 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
603 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
605 unset($item['parent-uri']);
607 // Set the delivery priority for "remote self" to "medium"
608 $notify = PRIORITY_MEDIUM;
611 $id = Item::insert($item, $notify);
613 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
615 if (!empty($id) && !empty($taglist)) {
616 $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
617 foreach ($taglist as $tag) {
618 Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
623 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
624 self::adjustPollFrequency($contact, $creation_dates);
627 return ["header" => $author, "items" => $items];
631 * Automatically adjust the poll frequency according to the post frequency
633 * @param array $contact
634 * @param array $creation_dates
637 private static function adjustPollFrequency(array $contact, array $creation_dates)
639 if ($contact['network'] != Protocol::FEED) {
640 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
644 if (!empty($creation_dates)) {
645 // Count the post frequency and the earliest and latest post date
649 $oldest_date = $newest_date = '';
651 foreach ($creation_dates as $date) {
652 $timestamp = strtotime($date);
653 $day = intdiv($timestamp, 86400);
654 $hour = $timestamp % 86400;
656 // Only have a look at values from the last seven days
657 if (((time() / 86400) - $day) < 7) {
658 if (empty($frequency[$day])) {
659 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
661 ++$frequency[$day]['count'];
662 if ($frequency[$day]['low'] > $hour) {
663 $frequency[$day]['low'] = $hour;
665 if ($frequency[$day]['high'] < $hour) {
666 $frequency[$day]['high'] = $hour;
670 if ($oldest > $day) {
672 $oldest_date = $date;
675 if ($newest < $day) {
677 $newest_date = $date;
681 if (count($creation_dates) == 1) {
682 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
683 $priority = 8; // Poll once a day
686 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
687 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']]);
688 $priority = 10; // Poll every month
691 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
692 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']]);
693 $priority = 9; // Poll every week
696 if (empty($priority) && empty($frequency)) {
697 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']]);
698 $priority = 8; // Poll once a day
701 if (empty($priority)) {
702 // Calculate the highest "posts per day" value
704 foreach ($frequency as $entry) {
705 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
709 // We take the earliest and latest post day and interpolate the number of post per day
710 // that would had been created with this post frequency
712 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
713 $duration = max($entry['high'] - $entry['low'], 14400);
714 $ppd = (86400 / $duration) * $entry['count'];
720 $priority = 1; // Poll every quarter hour
721 } elseif ($max > 24) {
722 $priority = 2; // Poll half an hour
723 } elseif ($max > 12) {
724 $priority = 3; // Poll hourly
725 } elseif ($max > 8) {
726 $priority = 4; // Poll every two hours
727 } elseif ($max > 4) {
728 $priority = 5; // Poll every three hours
729 } elseif ($max > 2) {
730 $priority = 6; // Poll every six hours
732 $priority = 7; // Poll twice a day
734 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
737 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
738 $priority = 8; // Poll once a day
741 if ($contact['rating'] != $priority) {
742 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
743 DBA::update('contact', ['rating' => $priority], ['id' => $contact['id']]);
748 * Convert a tag array to a tag string
751 * @return string tag string
753 private static function tagToString(array $tags)
757 foreach ($tags as $tag) {
762 $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
768 private static function titleIsBody($title, $body)
770 $title = strip_tags($title);
771 $title = trim($title);
772 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
773 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
775 $body = strip_tags($body);
777 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
778 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
780 if (strlen($title) < strlen($body)) {
781 $body = substr($body, 0, strlen($title));
784 if (($title != $body) && (substr($title, -3) == "...")) {
785 $pos = strrpos($title, "...");
787 $title = substr($title, 0, $pos);
788 $body = substr($body, 0, $pos);
791 return ($title == $body);
795 * Creates the Atom feed for a given nickname
798 * - activity (default): all the public posts
799 * - posts: all the public top-level posts
800 * - comments: all the public replies
802 * Updates the provided last_update parameter if the result comes from the
803 * cache or it is empty
805 * @param string $owner_nick Nickname of the feed owner
806 * @param string $last_update Date of the last update
807 * @param integer $max_items Number of maximum items to fetch
808 * @param string $filter Feed items filter (activity, posts or comments)
809 * @param boolean $nocache Wether to bypass caching
811 * @return string Atom feed
812 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
813 * @throws \ImagickException
815 public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
817 $stamp = microtime(true);
819 $owner = User::getOwnerDataByNick($owner_nick);
824 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
826 $previous_created = $last_update;
828 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
829 if ((time() - strtotime($owner['last-item'])) < 15*60) {
830 $result = DI::cache()->get($cachekey);
831 if (!$nocache && !is_null($result)) {
832 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
833 return $result['feed'];
837 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
838 $authorid = Contact::getIdForURL($owner["url"]);
840 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
841 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
842 $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
843 Item::PRIVATE, Protocol::ACTIVITYPUB,
844 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
846 if ($filter === 'comments') {
847 $condition[0] .= " AND `object-type` = ? ";
848 $condition[] = Activity\ObjectType::COMMENT;
851 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
852 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
853 $condition[] = $owner["id"];
854 $condition[] = $authorid;
857 $params = ['order' => ['received' => true], 'limit' => $max_items];
859 if ($filter === 'posts') {
860 $ret = Item::selectThread([], $condition, $params);
862 $ret = Item::select([], $condition, $params);
865 $items = Item::inArray($ret);
867 $doc = new DOMDocument('1.0', 'utf-8');
868 $doc->formatOutput = true;
870 $root = self::addHeader($doc, $owner, $filter);
872 foreach ($items as $item) {
873 $entry = self::entry($doc, $item, $owner);
874 $root->appendChild($entry);
876 if ($last_update < $item['created']) {
877 $last_update = $item['created'];
881 $feeddata = trim($doc->saveXML());
883 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
884 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
886 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
892 * Adds the header elements to the XML document
894 * @param DOMDocument $doc XML document
895 * @param array $owner Contact data of the poster
896 * @param string $filter The related feed filter (activity, posts or comments)
898 * @return object header root element
899 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
901 private static function addHeader(DOMDocument $doc, array $owner, $filter)
903 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
904 $doc->appendChild($root);
907 $selfUri = '/feed/' . $owner["nick"] . '/';
910 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
914 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
917 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
922 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
923 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
924 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
925 XML::addElement($doc, $root, "title", $title);
926 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
927 XML::addElement($doc, $root, "logo", $owner["photo"]);
928 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
930 $author = self::addAuthor($doc, $owner);
931 $root->appendChild($author);
933 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
934 XML::addElement($doc, $root, "link", "", $attributes);
936 OStatus::hublinks($doc, $root, $owner["nick"]);
938 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
939 XML::addElement($doc, $root, "link", "", $attributes);
945 * Adds the author element to the XML document
947 * @param DOMDocument $doc XML document
948 * @param array $owner Contact data of the poster
950 * @return \DOMElement author element
951 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
953 private static function addAuthor(DOMDocument $doc, array $owner)
955 $author = $doc->createElement("author");
956 XML::addElement($doc, $author, "uri", $owner["url"]);
957 XML::addElement($doc, $author, "name", $owner["nick"]);
958 XML::addElement($doc, $author, "email", $owner["addr"]);
964 * Adds an entry element to the XML document
966 * @param DOMDocument $doc XML document
967 * @param array $item Data of the item that is to be posted
968 * @param array $owner Contact data of the poster
969 * @param bool $toplevel optional default false
971 * @return \DOMElement Entry element
972 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
973 * @throws \ImagickException
975 private static function entry(DOMDocument $doc, array $item, array $owner)
979 $repeated_guid = OStatus::getResharedGuid($item);
980 if ($repeated_guid != "") {
981 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
988 return self::noteEntry($doc, $item, $owner);
992 * Adds an entry element with reshared content
994 * @param DOMDocument $doc XML document
995 * @param array $item Data of the item that is to be posted
996 * @param array $owner Contact data of the poster
997 * @param string $repeated_guid guid
998 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1000 * @return bool Entry element
1001 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1002 * @throws \ImagickException
1004 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
1006 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1007 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1010 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1012 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1013 'network' => Protocol::FEDERATED];
1014 $repeated_item = Item::selectFirst([], $condition);
1015 if (!DBA::isResult($repeated_item)) {
1019 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
1021 self::entryFooter($doc, $entry, $item, $owner);
1027 * Adds a regular entry element
1029 * @param DOMDocument $doc XML document
1030 * @param array $item Data of the item that is to be posted
1031 * @param array $owner Contact data of the poster
1032 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1034 * @return \DOMElement Entry element
1035 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1036 * @throws \ImagickException
1038 private static function noteEntry(DOMDocument $doc, array $item, array $owner)
1040 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1041 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1044 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1046 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1048 self::entryFooter($doc, $entry, $item, $owner);
1054 * Adds elements to the XML document
1056 * @param DOMDocument $doc XML document
1057 * @param \DOMElement $entry Entry element where the content is added
1058 * @param array $item Data of the item that is to be posted
1059 * @param array $owner Contact data of the poster
1060 * @param string $title Title for the post
1061 * @param string $verb The activity verb
1062 * @param bool $complete Add the "status_net" element?
1063 * @param bool $feed_mode Behave like a regular feed for users if true
1065 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1067 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
1070 $verb = OStatus::constructVerb($item);
1073 XML::addElement($doc, $entry, "id", $item["uri"]);
1074 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1076 $body = OStatus::formatPicturePost($item['body']);
1078 $body = BBCode::convert($body, false, BBCode::OSTATUS);
1080 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1082 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1083 "href" => DI::baseUrl()."/display/".$item["guid"]]
1086 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1087 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1091 * Adds the elements at the foot of an entry to the XML document
1093 * @param DOMDocument $doc XML document
1094 * @param object $entry The entry element where the elements are added
1095 * @param array $item Data of the item that is to be posted
1096 * @param array $owner Contact data of the poster
1097 * @param bool $complete default true
1099 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1101 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1105 if ($item['gravity'] != GRAVITY_PARENT) {
1106 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1107 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1109 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
1111 if (DBA::isResult($thrparent)) {
1112 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1113 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1114 $parent_plink = $thrparent["plink"];
1116 $mentioned[$parent["author-link"]] = $parent["author-link"];
1117 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1118 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1122 "ref" => $parent_item,
1123 "href" => $parent_plink];
1124 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1128 "href" => $parent_plink];
1129 XML::addElement($doc, $entry, "link", "", $attributes);
1132 // uri-id isn't present for follow entry pseudo-items
1133 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1134 foreach ($tags as $tag) {
1135 $mentioned[$tag['url']] = $tag['url'];
1138 foreach ($tags as $tag) {
1139 if ($tag['type'] == Tag::HASHTAG) {
1140 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
1144 OStatus::getAttachment($doc, $entry, $item);
1148 * Fetch or create title for feed entry
1150 * @param array $item
1151 * @return string title
1153 private static function getTitle(array $item)
1155 if ($item['title'] != '') {
1156 return BBCode::convert($item['title'], false, BBCode::OSTATUS);
1159 // Fetch information about the post
1160 $siteinfo = BBCode::getAttachedData($item["body"]);
1161 if (isset($siteinfo["title"])) {
1162 return $siteinfo["title"];
1165 // If no bookmark is found then take the first line
1166 // Remove the share element before fetching the first line
1167 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1169 $title = HTML::toPlaintext(BBCode::convert($title, false), 0, true)."\n";
1170 $pos = strpos($title, "\n");
1172 if (($pos == 0) || ($pos > 100)) {
1177 return substr($title, 0, $pos) . $trailer;