3 * @file src/Protocol/Feed.php
4 * @brief 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\Core\System;
15 use Friendica\Database\DBA;
17 use Friendica\Model\Item;
18 use Friendica\Protocol\ActivityNamespace;
19 use Friendica\Util\ParseUrl;
20 use Friendica\Util\Network;
21 use Friendica\Util\XML;
24 * @brief This class contain functions to import feeds
29 * @brief Read a RSS/RDF/Atom feed and create an item entry for it
31 * @param string $xml The feed data
32 * @param array $importer The user record of the importer
33 * @param array $contact The contact record of the feed
34 * @param string $hub Unused dummy value for compatibility reasons
35 * @param bool $simulate If enabled, no data is imported
37 * @return array In simulation mode it returns the header and the first item
38 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
40 public static function import($xml, $importer, &$contact, &$hub, $simulate = false) {
45 Logger::log("Import Atom/RSS feed '".$contact["name"]."' (Contact ".$contact["id"].") for user ".$importer["uid"], Logger::DEBUG);
47 Logger::log("Test Atom/RSS feed", Logger::DEBUG);
50 Logger::log('XML is empty.', Logger::DEBUG);
54 if (!empty($contact['poll'])) {
55 $basepath = $contact['poll'];
56 } elseif (!empty($contact['url'])) {
57 $basepath = $contact['url'];
62 $doc = new DOMDocument();
63 @$doc->loadXML(trim($xml));
64 $xpath = new DOMXPath($doc);
65 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
66 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
67 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
68 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
69 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
70 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
71 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
77 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
78 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
79 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
81 if (empty($author["author-name"])) {
82 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
84 $entries = $xpath->query('/rdf:RDF/rss:item');
88 if ($xpath->query('/atom:feed')->length > 0) {
89 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
90 if (is_object($alternate)) {
91 foreach ($alternate AS $attribute) {
92 if ($attribute->name == "href") {
93 $author["author-link"] = $attribute->textContent;
98 if (empty($author["author-link"])) {
99 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
100 if (is_object($self)) {
101 foreach ($self AS $attribute) {
102 if ($attribute->name == "href") {
103 $author["author-link"] = $attribute->textContent;
109 if (empty($author["author-link"])) {
110 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
112 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
114 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
116 if (empty($author["author-name"])) {
117 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
119 if (empty($author["author-name"])) {
120 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
122 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
124 $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;
139 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
141 $author["author-location"] = $value;
143 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
145 $author["author-about"] = $value;
147 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
148 if (is_object($avatar)) {
149 foreach ($avatar AS $attribute) {
150 if ($attribute->name == "href") {
151 $author["author-avatar"] = $attribute->textContent;
157 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
159 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
161 $entries = $xpath->query('/atom:feed/atom:entry');
165 if ($xpath->query('/rss/channel')->length > 0) {
166 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
168 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
169 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
171 if (empty($author["author-name"])) {
172 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
174 if (empty($author["author-name"])) {
175 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
177 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
179 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
181 $entries = $xpath->query('/rss/channel/item');
185 $author["author-link"] = $contact["url"];
187 if (empty($author["author-name"])) {
188 $author["author-name"] = $contact["name"];
190 $author["author-avatar"] = $contact["thumb"];
192 $author["owner-link"] = $contact["url"];
193 $author["owner-name"] = $contact["name"];
194 $author["owner-avatar"] = $contact["thumb"];
198 $header["uid"] = $importer["uid"];
199 $header["network"] = Protocol::FEED;
201 $header["origin"] = 0;
202 $header["gravity"] = GRAVITY_PARENT;
203 $header["private"] = 2;
204 $header["verb"] = Activity::POST;
205 $header["object-type"] = Activity\ObjectType::NOTE;
207 $header["contact-id"] = $contact["id"];
209 if (!is_object($entries)) {
210 Logger::log("There are no entries in this feed.", Logger::DEBUG);
215 // Importing older entries first
216 for($i = $entries->length - 1; $i >= 0;--$i) {
217 $entry = $entries->item($i);
219 $item = array_merge($header, $author);
221 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
222 if (!is_object($alternate)) {
223 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
225 if (is_object($alternate)) {
226 foreach ($alternate AS $attribute) {
227 if ($attribute->name == "href") {
228 $item["plink"] = $attribute->textContent;
232 if (empty($item["plink"])) {
233 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
235 if (empty($item["plink"])) {
236 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
239 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
241 if (empty($item["uri"])) {
242 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
244 if (empty($item["uri"])) {
245 $item["uri"] = $item["plink"];
248 $orig_plink = $item["plink"];
250 $item["plink"] = Network::finalUrl($item["plink"]);
252 $item["parent-uri"] = $item["uri"];
255 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
256 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
257 $previous = Item::selectFirst(['id'], $condition);
258 if (DBA::isResult($previous)) {
259 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$previous["id"], Logger::DEBUG);
264 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
266 if (empty($item["title"])) {
267 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
269 if (empty($item["title"])) {
270 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
273 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
275 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
277 if (empty($published)) {
278 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
280 if (empty($published)) {
281 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
283 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
285 if (empty($updated) && !empty($published)) {
286 $updated = $published;
289 if (empty($published) && !empty($updated)) {
290 $published = $updated;
293 if ($published != "") {
294 $item["created"] = $published;
296 if ($updated != "") {
297 $item["edited"] = $updated;
299 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
301 if (empty($creator)) {
302 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
304 if (empty($creator)) {
305 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
307 if ($creator != "") {
308 $item["author-name"] = $creator;
310 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
312 if ($creator != "") {
313 $item["author-name"] = $creator;
317 // <category>Ausland</category>
318 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
322 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
323 foreach ($enclosures AS $enclosure) {
328 foreach ($enclosure->attributes AS $attribute) {
329 if (in_array($attribute->name, ["url", "href"])) {
330 $href = $attribute->textContent;
331 } elseif ($attribute->name == "length") {
332 $length = $attribute->textContent;
333 } elseif ($attribute->name == "type") {
334 $type = $attribute->textContent;
337 if (!empty($item["attach"])) {
338 $item["attach"] .= ',';
340 $item["attach"] = '';
343 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
345 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'"[/attach]';
349 $categories = $xpath->query("category", $entry);
350 foreach ($categories AS $category) {
351 $hashtag = $category->nodeValue;
356 $taglink = "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
360 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
363 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
366 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
368 if (empty($summary)) {
369 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
377 if ($body == $summary) {
381 // remove the content of the title if it is identically to the body
382 // This helps with auto generated titles e.g. from tumblr
383 if (self::titleIsBody($item["title"], $body)) {
386 $item["body"] = HTML::toBBCode($body, $basepath);
388 if (($item["body"] == '') && ($item["title"] != '')) {
389 $item["body"] = $item["title"];
394 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
395 // Handle enclosures and treat them as preview picture
396 foreach ($attachments AS $attachment) {
397 if ($attachment["type"] == "image/jpeg") {
398 $preview = $attachment["link"];
402 // Remove a possible link to the item itself
403 $item["body"] = str_replace($item["plink"], '', $item["body"]);
404 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
406 // Replace the content when the title is longer than the body
407 $replace = (strlen($item["title"]) > strlen($item["body"]));
409 // Replace it, when there is an image in the body
410 if (strstr($item["body"], '[/img]')) {
414 // Replace it, when there is a link in the body
415 if (strstr($item["body"], '[/url]')) {
420 $item["body"] = trim($item["title"]);
423 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
424 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
425 // When the fetched page info text is longer than the body, we do try to enhance the body
426 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
427 // The body is not part of the fetched page info title or page info text. So we add the text to the body
428 $item['body'] .= "\n\n" . $data['text'];
430 // Else we replace the body with the page info text
431 $item['body'] = $data['text'];
435 // We always strip the title since it will be added in the page information
437 $item["body"] = $item["body"].add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
438 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
439 $item["object-type"] = Activity\ObjectType::BOOKMARK;
440 unset($item["attach"]);
442 if (!empty($summary)) {
443 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
446 if ($contact["fetch_further_information"] == 3) {
448 $item["tag"] = $tags;
450 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
451 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
453 $item["body"] .= "\n".$item['tag'];
455 // Add the link to the original feed entry if not present in feed
456 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
457 $item["body"] .= "[hr][url]".$item['plink']."[/url]";
462 Logger::log("Stored feed: ".print_r($item, true), Logger::DEBUG);
464 $notify = Item::isRemoteSelf($contact, $item);
466 // Distributed items should have a well formatted URI.
467 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
469 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
471 unset($item['parent-uri']);
473 // Set the delivery priority for "remote self" to "medium"
474 $notify = PRIORITY_MEDIUM;
477 $id = Item::insert($item, false, $notify);
479 Logger::log("Feed for contact ".$contact["url"]." stored under id ".$id);
489 return ["header" => $author, "items" => $items];
493 private static function titleIsBody($title, $body)
495 $title = strip_tags($title);
496 $title = trim($title);
497 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
498 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
500 $body = strip_tags($body);
502 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
503 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
505 if (strlen($title) < strlen($body)) {
506 $body = substr($body, 0, strlen($title));
509 if (($title != $body) && (substr($title, -3) == "...")) {
510 $pos = strrpos($title, "...");
512 $title = substr($title, 0, $pos);
513 $body = substr($body, 0, $pos);
516 return ($title == $body);