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"] = 2;
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.");
235 // Importing older entries first
236 for ($i = $entries->length - 1; $i >= 0; --$i) {
237 $entry = $entries->item($i);
239 $item = array_merge($header, $author);
241 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
242 if (!is_object($alternate)) {
243 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
245 if (is_object($alternate)) {
246 foreach ($alternate AS $attribute) {
247 if ($attribute->name == "href") {
248 $item["plink"] = $attribute->textContent;
253 if (empty($item["plink"])) {
254 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
257 if (empty($item["plink"])) {
258 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
261 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
263 if (empty($item["uri"])) {
264 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
267 if (empty($item["uri"])) {
268 $item["uri"] = $item["plink"];
271 $orig_plink = $item["plink"];
273 $item["plink"] = Network::finalUrl($item["plink"]);
275 $item["parent-uri"] = $item["uri"];
278 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
279 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
280 $previous = Item::selectFirst(['id'], $condition);
281 if (DBA::isResult($previous)) {
282 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
287 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
289 if (empty($item["title"])) {
290 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
292 if (empty($item["title"])) {
293 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
296 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
298 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
300 if (empty($published)) {
301 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
304 if (empty($published)) {
305 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
308 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
310 if (empty($updated) && !empty($published)) {
311 $updated = $published;
314 if (empty($published) && !empty($updated)) {
315 $published = $updated;
318 if ($published != "") {
319 $item["created"] = $published;
322 if ($updated != "") {
323 $item["edited"] = $updated;
326 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
328 if (empty($creator)) {
329 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
332 if (empty($creator)) {
333 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
336 if ($creator != "") {
337 $item["author-name"] = $creator;
340 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
342 if ($creator != "") {
343 $item["author-name"] = $creator;
347 // <category>Ausland</category>
348 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
352 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
353 foreach ($enclosures AS $enclosure) {
358 foreach ($enclosure->attributes AS $attribute) {
359 if (in_array($attribute->name, ["url", "href"])) {
360 $href = $attribute->textContent;
361 } elseif ($attribute->name == "length") {
362 $length = $attribute->textContent;
363 } elseif ($attribute->name == "type") {
364 $type = $attribute->textContent;
368 if (!empty($item["attach"])) {
369 $item["attach"] .= ',';
371 $item["attach"] = '';
374 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
376 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
380 $categories = $xpath->query("category", $entry);
381 foreach ($categories AS $category) {
382 $hashtag = $category->nodeValue;
387 $taglink = "#[url=" . DI::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
391 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
394 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
397 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
399 if (empty($summary)) {
400 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
408 if ($body == $summary) {
412 // remove the content of the title if it is identically to the body
413 // This helps with auto generated titles e.g. from tumblr
414 if (self::titleIsBody($item["title"], $body)) {
417 $item["body"] = HTML::toBBCode($body, $basepath);
419 if (($item["body"] == '') && ($item["title"] != '')) {
420 $item["body"] = $item["title"];
425 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
426 // Handle enclosures and treat them as preview picture
427 foreach ($attachments AS $attachment) {
428 if ($attachment["type"] == "image/jpeg") {
429 $preview = $attachment["link"];
433 // Remove a possible link to the item itself
434 $item["body"] = str_replace($item["plink"], '', $item["body"]);
435 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
437 // Replace the content when the title is longer than the body
438 $replace = (strlen($item["title"]) > strlen($item["body"]));
440 // Replace it, when there is an image in the body
441 if (strstr($item["body"], '[/img]')) {
445 // Replace it, when there is a link in the body
446 if (strstr($item["body"], '[/url]')) {
451 $item["body"] = trim($item["title"]);
454 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
455 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
456 // When the fetched page info text is longer than the body, we do try to enhance the body
457 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
458 // The body is not part of the fetched page info title or page info text. So we add the text to the body
459 $item['body'] .= "\n\n" . $data['text'];
461 // Else we replace the body with the page info text
462 $item['body'] = $data['text'];
466 // We always strip the title since it will be added in the page information
468 $item["body"] = $item["body"] . add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
469 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
470 $item["object-type"] = Activity\ObjectType::BOOKMARK;
471 unset($item["attach"]);
473 if (!empty($summary)) {
474 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
477 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
479 $item["tag"] = $tags;
481 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
482 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
484 $item["body"] .= "\n" . $item['tag'];
487 // Add the link to the original feed entry if not present in feed
488 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
489 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
497 Logger::info("Stored feed: " . print_r($item, true));
499 $notify = Item::isRemoteSelf($contact, $item);
501 // Distributed items should have a well formatted URI.
502 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
504 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
506 unset($item['parent-uri']);
508 // Set the delivery priority for "remote self" to "medium"
509 $notify = PRIORITY_MEDIUM;
512 $id = Item::insert($item, false, $notify);
514 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
518 return ["header" => $author, "items" => $items];
521 private static function titleIsBody($title, $body)
523 $title = strip_tags($title);
524 $title = trim($title);
525 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
526 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
528 $body = strip_tags($body);
530 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
531 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
533 if (strlen($title) < strlen($body)) {
534 $body = substr($body, 0, strlen($title));
537 if (($title != $body) && (substr($title, -3) == "...")) {
538 $pos = strrpos($title, "...");
540 $title = substr($title, 0, $pos);
541 $body = substr($body, 0, $pos);
544 return ($title == $body);