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\Model\Tag;
33 use Friendica\Util\Network;
34 use Friendica\Util\ParseUrl;
35 use Friendica\Util\XML;
38 * This class contain functions to import feeds (RSS/RDF/Atom)
42 * Read a RSS/RDF/Atom feed and create an item entry for it
44 * @param string $xml The feed data
45 * @param array $importer The user record of the importer
46 * @param array $contact The contact record of the feed
48 * @return array Returns the header and the first item in dry run mode
49 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
51 public static function import($xml, array $importer = [], array $contact = [])
53 $dryRun = empty($importer) && empty($contact);
56 Logger::info("Test Atom/RSS feed");
58 Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
62 Logger::info('XML is empty.');
66 if (!empty($contact['poll'])) {
67 $basepath = $contact['poll'];
68 } elseif (!empty($contact['url'])) {
69 $basepath = $contact['url'];
74 $doc = new DOMDocument();
75 @$doc->loadXML(trim($xml));
76 $xpath = new DOMXPath($doc);
77 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
78 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
79 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
80 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
81 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
82 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
83 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
89 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
90 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
91 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
93 if (empty($author["author-name"])) {
94 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
96 $entries = $xpath->query('/rdf:RDF/rss:item');
100 if ($xpath->query('/atom:feed')->length > 0) {
101 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
102 if (is_object($alternate)) {
103 foreach ($alternate AS $attribute) {
104 if ($attribute->name == "href") {
105 $author["author-link"] = $attribute->textContent;
110 if (empty($author["author-link"])) {
111 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
112 if (is_object($self)) {
113 foreach ($self AS $attribute) {
114 if ($attribute->name == "href") {
115 $author["author-link"] = $attribute->textContent;
121 if (empty($author["author-link"])) {
122 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
124 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
126 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
128 if (empty($author["author-name"])) {
129 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
132 if (empty($author["author-name"])) {
133 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
136 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
138 $author["author-name"] = $value;
142 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
144 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
145 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
147 $author["author-link"] = $value;
150 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
152 $author["author-nick"] = $value;
155 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
157 $author["author-location"] = $value;
160 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
162 $author["author-about"] = $value;
165 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
166 if (is_object($avatar)) {
167 foreach ($avatar AS $attribute) {
168 if ($attribute->name == "href") {
169 $author["author-avatar"] = $attribute->textContent;
175 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
177 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
179 $entries = $xpath->query('/atom:feed/atom:entry');
183 if ($xpath->query('/rss/channel')->length > 0) {
184 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
186 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
187 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
189 if (empty($author["author-name"])) {
190 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
193 if (empty($author["author-name"])) {
194 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
197 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
199 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
201 $entries = $xpath->query('/rss/channel/item');
205 $author["author-link"] = $contact["url"];
207 if (empty($author["author-name"])) {
208 $author["author-name"] = $contact["name"];
211 $author["author-avatar"] = $contact["thumb"];
213 $author["owner-link"] = $contact["url"];
214 $author["owner-name"] = $contact["name"];
215 $author["owner-avatar"] = $contact["thumb"];
219 $header["uid"] = $importer["uid"] ?? 0;
220 $header["network"] = Protocol::FEED;
222 $header["origin"] = 0;
223 $header["gravity"] = GRAVITY_PARENT;
224 $header["private"] = Item::PUBLIC;
225 $header["verb"] = Activity::POST;
226 $header["object-type"] = Activity\ObjectType::NOTE;
228 $header["contact-id"] = $contact["id"] ?? 0;
230 if (!is_object($entries)) {
231 Logger::info("There are no entries in this feed.");
237 // Limit the number of items that are about to be fetched
238 $total_items = ($entries->length - 1);
239 $max_items = DI::config()->get('system', 'max_feed_items');
240 if (($max_items > 0) && ($total_items > $max_items)) {
241 $total_items = $max_items;
244 // Importing older entries first
245 for ($i = $total_items; $i >= 0; --$i) {
246 $entry = $entries->item($i);
248 $item = array_merge($header, $author);
250 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
251 if (!is_object($alternate)) {
252 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
254 if (is_object($alternate)) {
255 foreach ($alternate AS $attribute) {
256 if ($attribute->name == "href") {
257 $item["plink"] = $attribute->textContent;
262 if (empty($item["plink"])) {
263 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
266 if (empty($item["plink"])) {
267 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
270 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
272 if (empty($item["uri"])) {
273 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
276 if (empty($item["uri"])) {
277 $item["uri"] = $item["plink"];
280 $orig_plink = $item["plink"];
282 $item["plink"] = Network::finalUrl($item["plink"]);
284 $item["parent-uri"] = $item["uri"];
287 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
288 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
289 $previous = Item::selectFirst(['id'], $condition);
290 if (DBA::isResult($previous)) {
291 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
296 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
298 if (empty($item["title"])) {
299 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
301 if (empty($item["title"])) {
302 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
305 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
307 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
309 if (empty($published)) {
310 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
313 if (empty($published)) {
314 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
317 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
319 if (empty($updated) && !empty($published)) {
320 $updated = $published;
323 if (empty($published) && !empty($updated)) {
324 $published = $updated;
327 if ($published != "") {
328 $item["created"] = $published;
331 if ($updated != "") {
332 $item["edited"] = $updated;
335 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
337 if (empty($creator)) {
338 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
341 if (empty($creator)) {
342 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
345 if ($creator != "") {
346 $item["author-name"] = $creator;
349 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
351 if ($creator != "") {
352 $item["author-name"] = $creator;
356 // <category>Ausland</category>
357 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
361 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
362 foreach ($enclosures AS $enclosure) {
367 foreach ($enclosure->attributes AS $attribute) {
368 if (in_array($attribute->name, ["url", "href"])) {
369 $href = $attribute->textContent;
370 } elseif ($attribute->name == "length") {
371 $length = $attribute->textContent;
372 } elseif ($attribute->name == "type") {
373 $type = $attribute->textContent;
377 if (!empty($item["attach"])) {
378 $item["attach"] .= ',';
380 $item["attach"] = '';
383 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
385 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
389 $categories = $xpath->query("category", $entry);
390 foreach ($categories AS $category) {
391 $taglist[] = $category->nodeValue;
394 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
397 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
400 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
402 if (empty($summary)) {
403 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
411 if ($body == $summary) {
415 // remove the content of the title if it is identically to the body
416 // This helps with auto generated titles e.g. from tumblr
417 if (self::titleIsBody($item["title"], $body)) {
420 $item["body"] = HTML::toBBCode($body, $basepath);
422 if (($item["body"] == '') && ($item["title"] != '')) {
423 $item["body"] = $item["title"];
428 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
429 // Handle enclosures and treat them as preview picture
430 foreach ($attachments AS $attachment) {
431 if ($attachment["type"] == "image/jpeg") {
432 $preview = $attachment["link"];
436 // Remove a possible link to the item itself
437 $item["body"] = str_replace($item["plink"], '', $item["body"]);
438 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
440 // Replace the content when the title is longer than the body
441 $replace = (strlen($item["title"]) > strlen($item["body"]));
443 // Replace it, when there is an image in the body
444 if (strstr($item["body"], '[/img]')) {
448 // Replace it, when there is a link in the body
449 if (strstr($item["body"], '[/url]')) {
454 $item["body"] = trim($item["title"]);
457 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
458 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
459 // When the fetched page info text is longer than the body, we do try to enhance the body
460 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
461 // The body is not part of the fetched page info title or page info text. So we add the text to the body
462 $item['body'] .= "\n\n" . $data['text'];
464 // Else we replace the body with the page info text
465 $item['body'] = $data['text'];
469 // We always strip the title since it will be added in the page information
471 $item["body"] = $item["body"] . add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
472 $taglist = get_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
473 $item["object-type"] = Activity\ObjectType::BOOKMARK;
474 unset($item["attach"]);
476 if (!empty($summary)) {
477 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
480 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
481 if (empty($taglist)) {
482 $taglist = get_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
484 $item["body"] .= "\n" . self::tagToString($taglist);
489 // Add the link to the original feed entry if not present in feed
490 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
491 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
499 Logger::info("Stored feed: " . print_r($item, true));
501 $notify = Item::isRemoteSelf($contact, $item);
503 // Distributed items should have a well formatted URI.
504 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
506 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
508 unset($item['parent-uri']);
510 // Set the delivery priority for "remote self" to "medium"
511 $notify = PRIORITY_MEDIUM;
514 $id = Item::insert($item, false, $notify);
516 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
518 if (!empty($id) && !empty($taglist)) {
519 $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
520 foreach ($taglist as $tag) {
521 Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
527 return ["header" => $author, "items" => $items];
531 * Convert a tag array to a tag string
534 * @return string tag string
536 private static function tagToString(array $tags)
540 foreach ($tags as $tag) {
545 $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
551 private static function titleIsBody($title, $body)
553 $title = strip_tags($title);
554 $title = trim($title);
555 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
556 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
558 $body = strip_tags($body);
560 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
561 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
563 if (strlen($title) < strlen($body)) {
564 $body = substr($body, 0, strlen($title));
567 if (($title != $body) && (substr($title, -3) == "...")) {
568 $pos = strrpos($title, "...");
570 $title = substr($title, 0, $pos);
571 $body = substr($body, 0, $pos);
574 return ($title == $body);