3 * @file src/Protocol/Feed.php
4 * Imports RSS/RDF/Atom feeds
7 namespace Friendica\Protocol;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Database\DBA;
16 use Friendica\Model\Item;
17 use Friendica\Util\Network;
18 use Friendica\Util\ParseUrl;
19 use Friendica\Util\XML;
22 * This class contain functions to import feeds
27 * Read a RSS/RDF/Atom feed and create an item entry for it
29 * @param string $xml The feed data
30 * @param array $importer The user record of the importer
31 * @param array $contact The contact record of the feed
33 * @return array Returns the header and the first item in dry run mode
34 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
36 public static function import($xml, array $importer = [], array $contact = [])
38 $dryRun = empty($importer) && empty($contact);
41 Logger::info("Test Atom/RSS feed");
43 Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
47 Logger::info('XML is empty.');
51 if (!empty($contact['poll'])) {
52 $basepath = $contact['poll'];
53 } elseif (!empty($contact['url'])) {
54 $basepath = $contact['url'];
59 $doc = new DOMDocument();
60 @$doc->loadXML(trim($xml));
61 $xpath = new DOMXPath($doc);
62 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
63 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
64 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
65 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
66 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
67 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
68 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
74 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
75 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
76 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
78 if (empty($author["author-name"])) {
79 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
81 $entries = $xpath->query('/rdf:RDF/rss:item');
85 if ($xpath->query('/atom:feed')->length > 0) {
86 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
87 if (is_object($alternate)) {
88 foreach ($alternate AS $attribute) {
89 if ($attribute->name == "href") {
90 $author["author-link"] = $attribute->textContent;
95 if (empty($author["author-link"])) {
96 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
97 if (is_object($self)) {
98 foreach ($self AS $attribute) {
99 if ($attribute->name == "href") {
100 $author["author-link"] = $attribute->textContent;
106 if (empty($author["author-link"])) {
107 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
109 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
111 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
113 if (empty($author["author-name"])) {
114 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
117 if (empty($author["author-name"])) {
118 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
121 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
123 $author["author-name"] = $value;
127 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
129 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
130 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
132 $author["author-link"] = $value;
135 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
137 $author["author-nick"] = $value;
140 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
142 $author["author-location"] = $value;
145 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
147 $author["author-about"] = $value;
150 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
151 if (is_object($avatar)) {
152 foreach ($avatar AS $attribute) {
153 if ($attribute->name == "href") {
154 $author["author-avatar"] = $attribute->textContent;
160 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
162 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
164 $entries = $xpath->query('/atom:feed/atom:entry');
168 if ($xpath->query('/rss/channel')->length > 0) {
169 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
171 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
172 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
174 if (empty($author["author-name"])) {
175 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
178 if (empty($author["author-name"])) {
179 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
182 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
184 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
186 $entries = $xpath->query('/rss/channel/item');
190 $author["author-link"] = $contact["url"];
192 if (empty($author["author-name"])) {
193 $author["author-name"] = $contact["name"];
196 $author["author-avatar"] = $contact["thumb"];
198 $author["owner-link"] = $contact["url"];
199 $author["owner-name"] = $contact["name"];
200 $author["owner-avatar"] = $contact["thumb"];
204 $header["uid"] = $importer["uid"] ?? 0;
205 $header["network"] = Protocol::FEED;
207 $header["origin"] = 0;
208 $header["gravity"] = GRAVITY_PARENT;
209 $header["private"] = 2;
210 $header["verb"] = Activity::POST;
211 $header["object-type"] = Activity\ObjectType::NOTE;
213 $header["contact-id"] = $contact["id"] ?? 0;
215 if (!is_object($entries)) {
216 Logger::info("There are no entries in this feed.");
221 // Importing older entries first
222 for ($i = $entries->length - 1; $i >= 0; --$i) {
223 $entry = $entries->item($i);
225 $item = array_merge($header, $author);
227 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
228 if (!is_object($alternate)) {
229 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
231 if (is_object($alternate)) {
232 foreach ($alternate AS $attribute) {
233 if ($attribute->name == "href") {
234 $item["plink"] = $attribute->textContent;
239 if (empty($item["plink"])) {
240 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
243 if (empty($item["plink"])) {
244 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
247 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
249 if (empty($item["uri"])) {
250 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
253 if (empty($item["uri"])) {
254 $item["uri"] = $item["plink"];
257 $orig_plink = $item["plink"];
259 $item["plink"] = Network::finalUrl($item["plink"]);
261 $item["parent-uri"] = $item["uri"];
264 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
265 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
266 $previous = Item::selectFirst(['id'], $condition);
267 if (DBA::isResult($previous)) {
268 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
273 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
275 if (empty($item["title"])) {
276 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
278 if (empty($item["title"])) {
279 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
282 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
284 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
286 if (empty($published)) {
287 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
290 if (empty($published)) {
291 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
294 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
296 if (empty($updated) && !empty($published)) {
297 $updated = $published;
300 if (empty($published) && !empty($updated)) {
301 $published = $updated;
304 if ($published != "") {
305 $item["created"] = $published;
308 if ($updated != "") {
309 $item["edited"] = $updated;
312 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
314 if (empty($creator)) {
315 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
318 if (empty($creator)) {
319 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
322 if ($creator != "") {
323 $item["author-name"] = $creator;
326 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
328 if ($creator != "") {
329 $item["author-name"] = $creator;
333 // <category>Ausland</category>
334 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
338 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
339 foreach ($enclosures AS $enclosure) {
344 foreach ($enclosure->attributes AS $attribute) {
345 if (in_array($attribute->name, ["url", "href"])) {
346 $href = $attribute->textContent;
347 } elseif ($attribute->name == "length") {
348 $length = $attribute->textContent;
349 } elseif ($attribute->name == "type") {
350 $type = $attribute->textContent;
354 if (!empty($item["attach"])) {
355 $item["attach"] .= ',';
357 $item["attach"] = '';
360 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
362 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
366 $categories = $xpath->query("category", $entry);
367 foreach ($categories AS $category) {
368 $hashtag = $category->nodeValue;
373 $taglink = "#[url=" . DI::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
377 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
380 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
383 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
385 if (empty($summary)) {
386 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
394 if ($body == $summary) {
398 // remove the content of the title if it is identically to the body
399 // This helps with auto generated titles e.g. from tumblr
400 if (self::titleIsBody($item["title"], $body)) {
403 $item["body"] = HTML::toBBCode($body, $basepath);
405 if (($item["body"] == '') && ($item["title"] != '')) {
406 $item["body"] = $item["title"];
411 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
412 // Handle enclosures and treat them as preview picture
413 foreach ($attachments AS $attachment) {
414 if ($attachment["type"] == "image/jpeg") {
415 $preview = $attachment["link"];
419 // Remove a possible link to the item itself
420 $item["body"] = str_replace($item["plink"], '', $item["body"]);
421 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
423 // Replace the content when the title is longer than the body
424 $replace = (strlen($item["title"]) > strlen($item["body"]));
426 // Replace it, when there is an image in the body
427 if (strstr($item["body"], '[/img]')) {
431 // Replace it, when there is a link in the body
432 if (strstr($item["body"], '[/url]')) {
437 $item["body"] = trim($item["title"]);
440 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
441 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
442 // When the fetched page info text is longer than the body, we do try to enhance the body
443 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
444 // The body is not part of the fetched page info title or page info text. So we add the text to the body
445 $item['body'] .= "\n\n" . $data['text'];
447 // Else we replace the body with the page info text
448 $item['body'] = $data['text'];
452 // We always strip the title since it will be added in the page information
454 $item["body"] = $item["body"] . add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
455 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
456 $item["object-type"] = Activity\ObjectType::BOOKMARK;
457 unset($item["attach"]);
459 if (!empty($summary)) {
460 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
463 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
465 $item["tag"] = $tags;
467 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
468 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
470 $item["body"] .= "\n" . $item['tag'];
473 // Add the link to the original feed entry if not present in feed
474 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
475 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
483 Logger::info("Stored feed: " . print_r($item, true));
485 $notify = Item::isRemoteSelf($contact, $item);
487 // Distributed items should have a well formatted URI.
488 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
490 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
492 unset($item['parent-uri']);
494 // Set the delivery priority for "remote self" to "medium"
495 $notify = PRIORITY_MEDIUM;
498 $id = Item::insert($item, false, $notify);
500 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
504 return ["header" => $author, "items" => $items];
507 private static function titleIsBody($title, $body)
509 $title = strip_tags($title);
510 $title = trim($title);
511 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
512 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
514 $body = strip_tags($body);
516 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
517 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
519 if (strlen($title) < strlen($body)) {
520 $body = substr($body, 0, strlen($title));
523 if (($title != $body) && (substr($title, -3) == "...")) {
524 $pos = strrpos($title, "...");
526 $title = substr($title, 0, $pos);
527 $body = substr($body, 0, $pos);
530 return ($title == $body);