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\Text\HTML;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Database\DBA;
31 use Friendica\Model\Item;
32 use Friendica\Util\Network;
33 use Friendica\Util\ParseUrl;
34 use Friendica\Util\XML;
37 * This class contain functions to import feeds (RSS/RDF/Atom)
41 * Read a RSS/RDF/Atom feed and create an item entry for it
43 * @param string $xml The feed data
44 * @param array $importer The user record of the importer
45 * @param array $contact The contact record of the feed
47 * @return array Returns the header and the first item in dry run mode
48 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
50 public static function import($xml, array $importer = [], array $contact = [])
52 $dryRun = empty($importer) && empty($contact);
55 Logger::info("Test Atom/RSS feed");
57 Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
61 Logger::info('XML is empty.');
65 if (!empty($contact['poll'])) {
66 $basepath = $contact['poll'];
67 } elseif (!empty($contact['url'])) {
68 $basepath = $contact['url'];
73 $doc = new DOMDocument();
74 @$doc->loadXML(trim($xml));
75 $xpath = new DOMXPath($doc);
76 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
77 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
78 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
79 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
80 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
81 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
82 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
88 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
89 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
90 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
92 if (empty($author["author-name"])) {
93 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
95 $entries = $xpath->query('/rdf:RDF/rss:item');
99 if ($xpath->query('/atom:feed')->length > 0) {
100 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
101 if (is_object($alternate)) {
102 foreach ($alternate AS $attribute) {
103 if ($attribute->name == "href") {
104 $author["author-link"] = $attribute->textContent;
109 if (empty($author["author-link"])) {
110 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
111 if (is_object($self)) {
112 foreach ($self AS $attribute) {
113 if ($attribute->name == "href") {
114 $author["author-link"] = $attribute->textContent;
120 if (empty($author["author-link"])) {
121 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
123 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
125 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
127 if (empty($author["author-name"])) {
128 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
131 if (empty($author["author-name"])) {
132 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
135 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
137 $author["author-name"] = $value;
141 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
143 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
144 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
146 $author["author-link"] = $value;
149 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
151 $author["author-nick"] = $value;
154 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
156 $author["author-location"] = $value;
159 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
161 $author["author-about"] = $value;
164 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
165 if (is_object($avatar)) {
166 foreach ($avatar AS $attribute) {
167 if ($attribute->name == "href") {
168 $author["author-avatar"] = $attribute->textContent;
174 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
176 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
178 $entries = $xpath->query('/atom:feed/atom:entry');
182 if ($xpath->query('/rss/channel')->length > 0) {
183 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
185 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
186 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
188 if (empty($author["author-name"])) {
189 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
192 if (empty($author["author-name"])) {
193 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
196 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
198 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
200 $entries = $xpath->query('/rss/channel/item');
204 $author["author-link"] = $contact["url"];
206 if (empty($author["author-name"])) {
207 $author["author-name"] = $contact["name"];
210 $author["author-avatar"] = $contact["thumb"];
212 $author["owner-link"] = $contact["url"];
213 $author["owner-name"] = $contact["name"];
214 $author["owner-avatar"] = $contact["thumb"];
218 $header["uid"] = $importer["uid"] ?? 0;
219 $header["network"] = Protocol::FEED;
221 $header["origin"] = 0;
222 $header["gravity"] = GRAVITY_PARENT;
223 $header["private"] = Item::PUBLIC;
224 $header["verb"] = Activity::POST;
225 $header["object-type"] = Activity\ObjectType::NOTE;
227 $header["contact-id"] = $contact["id"] ?? 0;
229 if (!is_object($entries)) {
230 Logger::info("There are no entries in this feed.");
236 // Limit the number of items that are about to be fetched
237 $total_items = ($entries->length - 1);
238 $max_items = DI::config()->get('system', 'max_feed_items');
239 if (($max_items > 0) && ($total_items > $max_items)) {
240 $total_items = $max_items;
243 // Importing older entries first
244 for ($i = $total_items; $i >= 0; --$i) {
245 $entry = $entries->item($i);
247 $item = array_merge($header, $author);
249 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
250 if (!is_object($alternate)) {
251 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
253 if (is_object($alternate)) {
254 foreach ($alternate AS $attribute) {
255 if ($attribute->name == "href") {
256 $item["plink"] = $attribute->textContent;
261 if (empty($item["plink"])) {
262 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
265 if (empty($item["plink"])) {
266 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
269 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
271 if (empty($item["uri"])) {
272 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
275 if (empty($item["uri"])) {
276 $item["uri"] = $item["plink"];
279 $orig_plink = $item["plink"];
281 $item["plink"] = Network::finalUrl($item["plink"]);
283 $item["parent-uri"] = $item["uri"];
286 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
287 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
288 $previous = Item::selectFirst(['id'], $condition);
289 if (DBA::isResult($previous)) {
290 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
295 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
297 if (empty($item["title"])) {
298 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
300 if (empty($item["title"])) {
301 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
304 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
306 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
308 if (empty($published)) {
309 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
312 if (empty($published)) {
313 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
316 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
318 if (empty($updated) && !empty($published)) {
319 $updated = $published;
322 if (empty($published) && !empty($updated)) {
323 $published = $updated;
326 if ($published != "") {
327 $item["created"] = $published;
330 if ($updated != "") {
331 $item["edited"] = $updated;
334 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
336 if (empty($creator)) {
337 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
340 if (empty($creator)) {
341 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
344 if ($creator != "") {
345 $item["author-name"] = $creator;
348 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
350 if ($creator != "") {
351 $item["author-name"] = $creator;
355 // <category>Ausland</category>
356 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
360 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
361 foreach ($enclosures AS $enclosure) {
366 foreach ($enclosure->attributes AS $attribute) {
367 if (in_array($attribute->name, ["url", "href"])) {
368 $href = $attribute->textContent;
369 } elseif ($attribute->name == "length") {
370 $length = $attribute->textContent;
371 } elseif ($attribute->name == "type") {
372 $type = $attribute->textContent;
376 if (!empty($item["attach"])) {
377 $item["attach"] .= ',';
379 $item["attach"] = '';
382 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
384 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
388 $categories = $xpath->query("category", $entry);
389 foreach ($categories AS $category) {
390 $hashtag = $category->nodeValue;
395 $taglink = "#[url=" . DI::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
399 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
402 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
405 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
407 if (empty($summary)) {
408 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
416 if ($body == $summary) {
420 // remove the content of the title if it is identically to the body
421 // This helps with auto generated titles e.g. from tumblr
422 if (self::titleIsBody($item["title"], $body)) {
425 $item["body"] = HTML::toBBCode($body, $basepath);
427 if (($item["body"] == '') && ($item["title"] != '')) {
428 $item["body"] = $item["title"];
433 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
434 // Handle enclosures and treat them as preview picture
435 foreach ($attachments AS $attachment) {
436 if ($attachment["type"] == "image/jpeg") {
437 $preview = $attachment["link"];
441 // Remove a possible link to the item itself
442 $item["body"] = str_replace($item["plink"], '', $item["body"]);
443 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
445 // Replace the content when the title is longer than the body
446 $replace = (strlen($item["title"]) > strlen($item["body"]));
448 // Replace it, when there is an image in the body
449 if (strstr($item["body"], '[/img]')) {
453 // Replace it, when there is a link in the body
454 if (strstr($item["body"], '[/url]')) {
459 $item["body"] = trim($item["title"]);
462 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
463 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
464 // When the fetched page info text is longer than the body, we do try to enhance the body
465 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
466 // The body is not part of the fetched page info title or page info text. So we add the text to the body
467 $item['body'] .= "\n\n" . $data['text'];
469 // Else we replace the body with the page info text
470 $item['body'] = $data['text'];
474 // We always strip the title since it will be added in the page information
476 $item["body"] = $item["body"] . add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
477 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
478 $item["object-type"] = Activity\ObjectType::BOOKMARK;
479 unset($item["attach"]);
481 if (!empty($summary)) {
482 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
485 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
487 $item["tag"] = $tags;
489 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
490 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
492 $item["body"] .= "\n" . $item['tag'];
495 // Add the link to the original feed entry if not present in feed
496 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
497 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
505 Logger::info("Stored feed: " . print_r($item, true));
507 $notify = Item::isRemoteSelf($contact, $item);
509 // Distributed items should have a well formatted URI.
510 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
512 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
514 unset($item['parent-uri']);
516 // Set the delivery priority for "remote self" to "medium"
517 $notify = PRIORITY_MEDIUM;
520 $id = Item::insert($item, false, $notify);
522 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
526 return ["header" => $author, "items" => $items];
529 private static function titleIsBody($title, $body)
531 $title = strip_tags($title);
532 $title = trim($title);
533 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
534 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
536 $body = strip_tags($body);
538 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
539 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
541 if (strlen($title) < strlen($body)) {
542 $body = substr($body, 0, strlen($title));
545 if (($title != $body) && (substr($title, -3) == "...")) {
546 $pos = strrpos($title, "...");
548 $title = substr($title, 0, $pos);
549 $body = substr($body, 0, $pos);
552 return ($title == $body);