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.");
304 // Limit the number of items that are about to be fetched
305 $total_items = ($entries->length - 1);
306 $max_items = DI::config()->get('system', 'max_feed_items');
307 if (($max_items > 0) && ($total_items > $max_items)) {
308 $total_items = $max_items;
311 // Importing older entries first
312 for ($i = $total_items; $i >= 0; --$i) {
313 $entry = $entries->item($i);
315 $item = array_merge($header, $author);
317 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
318 if (!is_object($alternate)) {
319 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
321 if (is_object($alternate)) {
322 foreach ($alternate AS $attribute) {
323 if ($attribute->name == "href") {
324 $item["plink"] = $attribute->textContent;
329 if (empty($item["plink"])) {
330 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
333 if (empty($item["plink"])) {
334 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
337 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
339 if (empty($item["uri"])) {
340 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
343 if (empty($item["uri"])) {
344 $item["uri"] = $item["plink"];
347 // Add the base path if missing
348 $item["uri"] = Network::addBasePath($item["uri"], $basepath);
349 $item["plink"] = Network::addBasePath($item["plink"], $basepath);
351 $orig_plink = $item["plink"];
353 $item["plink"] = DI::httpRequest()->finalUrl($item["plink"]);
355 $item["parent-uri"] = $item["uri"];
358 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
359 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
360 $previous = Item::selectFirst(['id'], $condition);
361 if (DBA::isResult($previous)) {
362 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
367 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
369 if (empty($item["title"])) {
370 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
372 if (empty($item["title"])) {
373 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
376 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
378 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
380 if (empty($published)) {
381 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
384 if (empty($published)) {
385 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
388 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
390 if (empty($updated) && !empty($published)) {
391 $updated = $published;
394 if (empty($published) && !empty($updated)) {
395 $published = $updated;
398 if ($published != "") {
399 $item["created"] = $published;
402 if ($updated != "") {
403 $item["edited"] = $updated;
406 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
408 if (empty($creator)) {
409 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
412 if (empty($creator)) {
413 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
416 if ($creator != "") {
417 $item["author-name"] = $creator;
420 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
422 if ($creator != "") {
423 $item["author-name"] = $creator;
427 // <category>Ausland</category>
428 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
432 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
433 foreach ($enclosures AS $enclosure) {
438 foreach ($enclosure->attributes AS $attribute) {
439 if (in_array($attribute->name, ["url", "href"])) {
440 $href = $attribute->textContent;
441 } elseif ($attribute->name == "length") {
442 $length = $attribute->textContent;
443 } elseif ($attribute->name == "type") {
444 $type = $attribute->textContent;
448 if (!empty($item["attach"])) {
449 $item["attach"] .= ',';
451 $item["attach"] = '';
454 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
456 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
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 if (($item["body"] == '') && ($item["title"] != '')) {
494 $item["body"] = $item["title"];
501 } elseif (!Item::isValid($item)) {
502 Logger::info('Feed is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
507 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
508 // Handle enclosures and treat them as preview picture
509 foreach ($attachments AS $attachment) {
510 if ($attachment["type"] == "image/jpeg") {
511 $preview = $attachment["link"];
515 // Remove a possible link to the item itself
516 $item["body"] = str_replace($item["plink"], '', $item["body"]);
517 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
519 // Replace the content when the title is longer than the body
520 $replace = (strlen($item["title"]) > strlen($item["body"]));
522 // Replace it, when there is an image in the body
523 if (strstr($item["body"], '[/img]')) {
527 // Replace it, when there is a link in the body
528 if (strstr($item["body"], '[/url]')) {
533 $item["body"] = trim($item["title"]);
536 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
537 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
538 // When the fetched page info text is longer than the body, we do try to enhance the body
539 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
540 // The body is not part of the fetched page info title or page info text. So we add the text to the body
541 $item['body'] .= "\n\n" . $data['text'];
543 // Else we replace the body with the page info text
544 $item['body'] = $data['text'];
548 // We always strip the title since it will be added in the page information
550 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
551 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
552 $item["object-type"] = Activity\ObjectType::BOOKMARK;
553 unset($item["attach"]);
555 if (!empty($summary)) {
556 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
559 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
560 if (empty($taglist)) {
561 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
563 $item["body"] .= "\n" . self::tagToString($taglist);
568 // Add the link to the original feed entry if not present in feed
569 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
570 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
574 Logger::info('Stored feed', ['item' => $item]);
576 $notify = Item::isRemoteSelf($contact, $item);
578 // Distributed items should have a well formatted URI.
579 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
581 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
583 unset($item['parent-uri']);
585 // Set the delivery priority for "remote self" to "medium"
586 $notify = PRIORITY_MEDIUM;
589 $id = Item::insert($item, $notify);
591 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
593 if (!empty($id) && !empty($taglist)) {
594 $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
595 foreach ($taglist as $tag) {
596 Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
601 return ["header" => $author, "items" => $items];
605 * Convert a tag array to a tag string
608 * @return string tag string
610 private static function tagToString(array $tags)
614 foreach ($tags as $tag) {
619 $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
625 private static function titleIsBody($title, $body)
627 $title = strip_tags($title);
628 $title = trim($title);
629 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
630 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
632 $body = strip_tags($body);
634 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
635 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
637 if (strlen($title) < strlen($body)) {
638 $body = substr($body, 0, strlen($title));
641 if (($title != $body) && (substr($title, -3) == "...")) {
642 $pos = strrpos($title, "...");
644 $title = substr($title, 0, $pos);
645 $body = substr($body, 0, $pos);
648 return ($title == $body);
652 * Creates the Atom feed for a given nickname
655 * - activity (default): all the public posts
656 * - posts: all the public top-level posts
657 * - comments: all the public replies
659 * Updates the provided last_update parameter if the result comes from the
660 * cache or it is empty
662 * @param string $owner_nick Nickname of the feed owner
663 * @param string $last_update Date of the last update
664 * @param integer $max_items Number of maximum items to fetch
665 * @param string $filter Feed items filter (activity, posts or comments)
666 * @param boolean $nocache Wether to bypass caching
668 * @return string Atom feed
669 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
670 * @throws \ImagickException
672 public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
674 $stamp = microtime(true);
676 $owner = User::getOwnerDataByNick($owner_nick);
681 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
683 $previous_created = $last_update;
685 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
686 if ((time() - strtotime($owner['last-item'])) < 15*60) {
687 $result = DI::cache()->get($cachekey);
688 if (!$nocache && !is_null($result)) {
689 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
690 return $result['feed'];
694 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
695 $authorid = Contact::getIdForURL($owner["url"]);
697 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
698 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
699 $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
700 Item::PRIVATE, Protocol::ACTIVITYPUB,
701 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
703 if ($filter === 'comments') {
704 $condition[0] .= " AND `object-type` = ? ";
705 $condition[] = Activity\ObjectType::COMMENT;
708 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
709 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
710 $condition[] = $owner["id"];
711 $condition[] = $authorid;
714 $params = ['order' => ['received' => true], 'limit' => $max_items];
716 if ($filter === 'posts') {
717 $ret = Item::selectThread([], $condition, $params);
719 $ret = Item::select([], $condition, $params);
722 $items = Item::inArray($ret);
724 $doc = new DOMDocument('1.0', 'utf-8');
725 $doc->formatOutput = true;
727 $root = self::addHeader($doc, $owner, $filter);
729 foreach ($items as $item) {
730 $entry = self::entry($doc, $item, $owner);
731 $root->appendChild($entry);
733 if ($last_update < $item['created']) {
734 $last_update = $item['created'];
738 $feeddata = trim($doc->saveXML());
740 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
741 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
743 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
749 * Adds the header elements to the XML document
751 * @param DOMDocument $doc XML document
752 * @param array $owner Contact data of the poster
753 * @param string $filter The related feed filter (activity, posts or comments)
755 * @return object header root element
756 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
758 private static function addHeader(DOMDocument $doc, array $owner, $filter)
760 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
761 $doc->appendChild($root);
764 $selfUri = '/feed/' . $owner["nick"] . '/';
767 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
771 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
774 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
779 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
780 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
781 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
782 XML::addElement($doc, $root, "title", $title);
783 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
784 XML::addElement($doc, $root, "logo", $owner["photo"]);
785 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
787 $author = self::addAuthor($doc, $owner);
788 $root->appendChild($author);
790 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
791 XML::addElement($doc, $root, "link", "", $attributes);
793 OStatus::hublinks($doc, $root, $owner["nick"]);
795 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
796 XML::addElement($doc, $root, "link", "", $attributes);
802 * Adds the author element to the XML document
804 * @param DOMDocument $doc XML document
805 * @param array $owner Contact data of the poster
807 * @return \DOMElement author element
808 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
810 private static function addAuthor(DOMDocument $doc, array $owner)
812 $author = $doc->createElement("author");
813 XML::addElement($doc, $author, "uri", $owner["url"]);
814 XML::addElement($doc, $author, "name", $owner["nick"]);
815 XML::addElement($doc, $author, "email", $owner["addr"]);
821 * Adds an entry element to the XML document
823 * @param DOMDocument $doc XML document
824 * @param array $item Data of the item that is to be posted
825 * @param array $owner Contact data of the poster
826 * @param bool $toplevel optional default false
828 * @return \DOMElement Entry element
829 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
830 * @throws \ImagickException
832 private static function entry(DOMDocument $doc, array $item, array $owner)
836 $repeated_guid = OStatus::getResharedGuid($item);
837 if ($repeated_guid != "") {
838 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
845 return self::noteEntry($doc, $item, $owner);
849 * Adds an entry element with reshared content
851 * @param DOMDocument $doc XML document
852 * @param array $item Data of the item that is to be posted
853 * @param array $owner Contact data of the poster
854 * @param string $repeated_guid guid
855 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
857 * @return bool Entry element
858 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
859 * @throws \ImagickException
861 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
863 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
864 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
867 $entry = OStatus::entryHeader($doc, $owner, $item, false);
869 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
870 'network' => Protocol::FEDERATED];
871 $repeated_item = Item::selectFirst([], $condition);
872 if (!DBA::isResult($repeated_item)) {
876 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
878 self::entryFooter($doc, $entry, $item, $owner);
884 * Adds a regular entry element
886 * @param DOMDocument $doc XML document
887 * @param array $item Data of the item that is to be posted
888 * @param array $owner Contact data of the poster
889 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
891 * @return \DOMElement Entry element
892 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
893 * @throws \ImagickException
895 private static function noteEntry(DOMDocument $doc, array $item, array $owner)
897 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
898 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
901 $entry = OStatus::entryHeader($doc, $owner, $item, false);
903 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
905 self::entryFooter($doc, $entry, $item, $owner);
911 * Adds elements to the XML document
913 * @param DOMDocument $doc XML document
914 * @param \DOMElement $entry Entry element where the content is added
915 * @param array $item Data of the item that is to be posted
916 * @param array $owner Contact data of the poster
917 * @param string $title Title for the post
918 * @param string $verb The activity verb
919 * @param bool $complete Add the "status_net" element?
920 * @param bool $feed_mode Behave like a regular feed for users if true
922 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
924 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
927 $verb = OStatus::constructVerb($item);
930 XML::addElement($doc, $entry, "id", $item["uri"]);
931 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
933 $body = OStatus::formatPicturePost($item['body']);
935 $body = BBCode::convert($body, false, BBCode::OSTATUS);
937 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
939 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
940 "href" => DI::baseUrl()."/display/".$item["guid"]]
943 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
944 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
948 * Adds the elements at the foot of an entry to the XML document
950 * @param DOMDocument $doc XML document
951 * @param object $entry The entry element where the elements are added
952 * @param array $item Data of the item that is to be posted
953 * @param array $owner Contact data of the poster
954 * @param bool $complete default true
956 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
958 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
962 if ($item['gravity'] != GRAVITY_PARENT) {
963 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
964 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
966 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
968 if (DBA::isResult($thrparent)) {
969 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
970 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
971 $parent_plink = $thrparent["plink"];
973 $mentioned[$parent["author-link"]] = $parent["author-link"];
974 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
975 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
979 "ref" => $parent_item,
980 "href" => $parent_plink];
981 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
985 "href" => $parent_plink];
986 XML::addElement($doc, $entry, "link", "", $attributes);
989 // uri-id isn't present for follow entry pseudo-items
990 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
991 foreach ($tags as $tag) {
992 $mentioned[$tag['url']] = $tag['url'];
995 foreach ($tags as $tag) {
996 if ($tag['type'] == Tag::HASHTAG) {
997 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
1001 OStatus::getAttachment($doc, $entry, $item);
1005 * Fetch or create title for feed entry
1007 * @param array $item
1008 * @return string title
1010 private static function getTitle(array $item)
1012 if ($item['title'] != '') {
1013 return BBCode::convert($item['title'], false, BBCode::OSTATUS);
1016 // Fetch information about the post
1017 $siteinfo = BBCode::getAttachedData($item["body"]);
1018 if (isset($siteinfo["title"])) {
1019 return $siteinfo["title"];
1022 // If no bookmark is found then take the first line
1023 // Remove the share element before fetching the first line
1024 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1026 $title = HTML::toPlaintext(BBCode::convert($title, false), 0, true)."\n";
1027 $pos = strpos($title, "\n");
1029 if (($pos == 0) || ($pos > 100)) {
1034 return substr($title, 0, $pos) . $trailer;