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\HTML;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Database\DBA;
32 use Friendica\Model\Item;
33 use Friendica\Model\Tag;
34 use Friendica\Util\Network;
35 use Friendica\Util\ParseUrl;
36 use Friendica\Util\XML;
39 * This class contain functions to import feeds (RSS/RDF/Atom)
44 * consume - process atom feed and update anything/everything we might need to update
46 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
48 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
49 * It is this person's stuff that is going to be updated.
50 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
51 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
52 * have a contact record.
53 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
54 * might not) try and subscribe to it.
55 * $datedir sorts in reverse order
56 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
57 * imported prior to its children being seen in the stream unless we are certain
58 * of how the feed is arranged/ordered.
59 * With $pass = 1, we only pull parent items out of the stream.
60 * With $pass = 2, we only pull children (comments/likes).
62 * So running this twice, first with pass 1 and then with pass 2 will do the right
63 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
64 * model where comments can have sub-threads. That would require some massive sorting
65 * to get all the feed items into a mostly linear ordering, and might still require
69 * @param array $importer
70 * @param array $contact
72 * @throws ImagickException
73 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
75 public static function consume($xml, array $importer, array $contact, &$hub)
77 if ($contact['network'] === Protocol::OSTATUS) {
78 Logger::info('Consume OStatus messages');
79 OStatus::import($xml, $importer, $contact, $hub);
84 if ($contact['network'] === Protocol::FEED) {
85 Logger::info('Consume feeds');
86 self::import($xml, $importer, $contact);
91 if ($contact['network'] === Protocol::DFRN) {
92 Logger::info('Consume DFRN messages');
93 $dfrn_importer = DFRN::getImporter($contact['id'], $importer['uid']);
94 if (!empty($dfrn_importer)) {
95 Logger::info('Now import the DFRN feed');
96 DFRN::import($xml, $dfrn_importer, true);
103 * Read a RSS/RDF/Atom feed and create an item entry for it
105 * @param string $xml The feed data
106 * @param array $importer The user record of the importer
107 * @param array $contact The contact record of the feed
109 * @return array Returns the header and the first item in dry run mode
110 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
112 public static function import($xml, array $importer = [], array $contact = [])
114 $dryRun = empty($importer) && empty($contact);
117 Logger::info("Test Atom/RSS feed");
119 Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
123 Logger::info('XML is empty.');
127 if (!empty($contact['poll'])) {
128 $basepath = $contact['poll'];
129 } elseif (!empty($contact['url'])) {
130 $basepath = $contact['url'];
135 $doc = new DOMDocument();
136 @$doc->loadXML(trim($xml));
137 $xpath = new DOMXPath($doc);
138 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
139 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
140 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
141 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
142 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
143 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
144 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
150 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
151 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
152 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
154 if (empty($author["author-name"])) {
155 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
157 $entries = $xpath->query('/rdf:RDF/rss:item');
161 if ($xpath->query('/atom:feed')->length > 0) {
162 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
163 if (is_object($alternate)) {
164 foreach ($alternate AS $attribute) {
165 if ($attribute->name == "href") {
166 $author["author-link"] = $attribute->textContent;
171 if (empty($author["author-link"])) {
172 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
173 if (is_object($self)) {
174 foreach ($self AS $attribute) {
175 if ($attribute->name == "href") {
176 $author["author-link"] = $attribute->textContent;
182 if (empty($author["author-link"])) {
183 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
185 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
187 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
189 if (empty($author["author-name"])) {
190 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
193 if (empty($author["author-name"])) {
194 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
197 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
199 $author["author-name"] = $value;
203 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
205 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
206 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
208 $author["author-link"] = $value;
211 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
213 $author["author-nick"] = $value;
216 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
218 $author["author-location"] = $value;
221 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
223 $author["author-about"] = $value;
226 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
227 if (is_object($avatar)) {
228 foreach ($avatar AS $attribute) {
229 if ($attribute->name == "href") {
230 $author["author-avatar"] = $attribute->textContent;
236 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
238 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
240 $entries = $xpath->query('/atom:feed/atom:entry');
244 if ($xpath->query('/rss/channel')->length > 0) {
245 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
247 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
248 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
250 if (empty($author["author-name"])) {
251 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
254 if (empty($author["author-name"])) {
255 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
258 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
260 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
262 $entries = $xpath->query('/rss/channel/item');
266 $author["author-link"] = $contact["url"];
268 if (empty($author["author-name"])) {
269 $author["author-name"] = $contact["name"];
272 $author["author-avatar"] = $contact["thumb"];
274 $author["owner-link"] = $contact["url"];
275 $author["owner-name"] = $contact["name"];
276 $author["owner-avatar"] = $contact["thumb"];
280 $header["uid"] = $importer["uid"] ?? 0;
281 $header["network"] = Protocol::FEED;
283 $header["origin"] = 0;
284 $header["gravity"] = GRAVITY_PARENT;
285 $header["private"] = Item::PUBLIC;
286 $header["verb"] = Activity::POST;
287 $header["object-type"] = Activity\ObjectType::NOTE;
289 $header["contact-id"] = $contact["id"] ?? 0;
291 if (!is_object($entries)) {
292 Logger::info("There are no entries in this feed.");
298 // Limit the number of items that are about to be fetched
299 $total_items = ($entries->length - 1);
300 $max_items = DI::config()->get('system', 'max_feed_items');
301 if (($max_items > 0) && ($total_items > $max_items)) {
302 $total_items = $max_items;
305 // Importing older entries first
306 for ($i = $total_items; $i >= 0; --$i) {
307 $entry = $entries->item($i);
309 $item = array_merge($header, $author);
311 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
312 if (!is_object($alternate)) {
313 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
315 if (is_object($alternate)) {
316 foreach ($alternate AS $attribute) {
317 if ($attribute->name == "href") {
318 $item["plink"] = $attribute->textContent;
323 if (empty($item["plink"])) {
324 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
327 if (empty($item["plink"])) {
328 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
331 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
333 if (empty($item["uri"])) {
334 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
337 if (empty($item["uri"])) {
338 $item["uri"] = $item["plink"];
341 // Add the base path if missing
342 $item["uri"] = Network::addBasePath($item["uri"], $basepath);
343 $item["plink"] = Network::addBasePath($item["plink"], $basepath);
345 $orig_plink = $item["plink"];
347 $item["plink"] = Network::finalUrl($item["plink"]);
349 $item["parent-uri"] = $item["uri"];
352 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
353 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
354 $previous = Item::selectFirst(['id'], $condition);
355 if (DBA::isResult($previous)) {
356 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
361 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
363 if (empty($item["title"])) {
364 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
366 if (empty($item["title"])) {
367 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
370 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
372 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
374 if (empty($published)) {
375 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
378 if (empty($published)) {
379 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
382 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
384 if (empty($updated) && !empty($published)) {
385 $updated = $published;
388 if (empty($published) && !empty($updated)) {
389 $published = $updated;
392 if ($published != "") {
393 $item["created"] = $published;
396 if ($updated != "") {
397 $item["edited"] = $updated;
400 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
402 if (empty($creator)) {
403 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
406 if (empty($creator)) {
407 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
410 if ($creator != "") {
411 $item["author-name"] = $creator;
414 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
416 if ($creator != "") {
417 $item["author-name"] = $creator;
421 // <category>Ausland</category>
422 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
426 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
427 foreach ($enclosures AS $enclosure) {
432 foreach ($enclosure->attributes AS $attribute) {
433 if (in_array($attribute->name, ["url", "href"])) {
434 $href = $attribute->textContent;
435 } elseif ($attribute->name == "length") {
436 $length = $attribute->textContent;
437 } elseif ($attribute->name == "type") {
438 $type = $attribute->textContent;
442 if (!empty($item["attach"])) {
443 $item["attach"] .= ',';
445 $item["attach"] = '';
448 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
450 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
454 $categories = $xpath->query("category", $entry);
455 foreach ($categories AS $category) {
456 $taglist[] = $category->nodeValue;
459 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
462 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
465 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
467 if (empty($summary)) {
468 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
476 if ($body == $summary) {
480 // remove the content of the title if it is identically to the body
481 // This helps with auto generated titles e.g. from tumblr
482 if (self::titleIsBody($item["title"], $body)) {
485 $item["body"] = HTML::toBBCode($body, $basepath);
487 if (($item["body"] == '') && ($item["title"] != '')) {
488 $item["body"] = $item["title"];
493 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
494 // Handle enclosures and treat them as preview picture
495 foreach ($attachments AS $attachment) {
496 if ($attachment["type"] == "image/jpeg") {
497 $preview = $attachment["link"];
501 // Remove a possible link to the item itself
502 $item["body"] = str_replace($item["plink"], '', $item["body"]);
503 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
505 // Replace the content when the title is longer than the body
506 $replace = (strlen($item["title"]) > strlen($item["body"]));
508 // Replace it, when there is an image in the body
509 if (strstr($item["body"], '[/img]')) {
513 // Replace it, when there is a link in the body
514 if (strstr($item["body"], '[/url]')) {
519 $item["body"] = trim($item["title"]);
522 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
523 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
524 // When the fetched page info text is longer than the body, we do try to enhance the body
525 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
526 // The body is not part of the fetched page info title or page info text. So we add the text to the body
527 $item['body'] .= "\n\n" . $data['text'];
529 // Else we replace the body with the page info text
530 $item['body'] = $data['text'];
534 // We always strip the title since it will be added in the page information
536 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
537 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
538 $item["object-type"] = Activity\ObjectType::BOOKMARK;
539 unset($item["attach"]);
541 if (!empty($summary)) {
542 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
545 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
546 if (empty($taglist)) {
547 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"]);
549 $item["body"] .= "\n" . self::tagToString($taglist);
554 // Add the link to the original feed entry if not present in feed
555 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
556 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
564 Logger::info('Stored feed', ['item' => $item]);
566 $notify = Item::isRemoteSelf($contact, $item);
568 // Distributed items should have a well formatted URI.
569 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
571 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
573 unset($item['parent-uri']);
575 // Set the delivery priority for "remote self" to "medium"
576 $notify = PRIORITY_MEDIUM;
579 $id = Item::insert($item, $notify);
581 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
583 if (!empty($id) && !empty($taglist)) {
584 $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
585 foreach ($taglist as $tag) {
586 Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
592 return ["header" => $author, "items" => $items];
596 * Convert a tag array to a tag string
599 * @return string tag string
601 private static function tagToString(array $tags)
605 foreach ($tags as $tag) {
610 $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
616 private static function titleIsBody($title, $body)
618 $title = strip_tags($title);
619 $title = trim($title);
620 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
621 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
623 $body = strip_tags($body);
625 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
626 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
628 if (strlen($title) < strlen($body)) {
629 $body = substr($body, 0, strlen($title));
632 if (($title != $body) && (substr($title, -3) == "...")) {
633 $pos = strrpos($title, "...");
635 $title = substr($title, 0, $pos);
636 $body = substr($body, 0, $pos);
639 return ($title == $body);