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;
16 use Friendica\Model\Item;
17 use Friendica\Protocol\ActivityNamespace;
18 use Friendica\Util\ParseUrl;
19 use Friendica\Util\Network;
20 use Friendica\Util\XML;
23 * @brief This class contain functions to import feeds
28 * @brief Read a RSS/RDF/Atom feed and create an item entry for it
30 * @param string $xml The feed data
31 * @param array $importer The user record of the importer
32 * @param array $contact The contact record of the feed
33 * @param string $hub Unused dummy value for compatibility reasons
34 * @param bool $simulate If enabled, no data is imported
36 * @return array In simulation mode it returns the header and the first item
37 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
39 public static function import($xml, $importer, &$contact, &$hub, $simulate = false) {
44 Logger::log("Import Atom/RSS feed '".$contact["name"]."' (Contact ".$contact["id"].") for user ".$importer["uid"], Logger::DEBUG);
46 Logger::log("Test Atom/RSS feed", Logger::DEBUG);
49 Logger::log('XML is empty.', Logger::DEBUG);
53 if (!empty($contact['poll'])) {
54 $basepath = $contact['poll'];
55 } elseif (!empty($contact['url'])) {
56 $basepath = $contact['url'];
61 $doc = new DOMDocument();
62 @$doc->loadXML(trim($xml));
63 $xpath = new DOMXPath($doc);
64 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
65 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
66 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
67 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
68 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
69 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
70 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
76 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
77 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
78 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
80 if (empty($author["author-name"])) {
81 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
83 $entries = $xpath->query('/rdf:RDF/rss:item');
87 if ($xpath->query('/atom:feed')->length > 0) {
88 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
89 if (is_object($alternate)) {
90 foreach ($alternate AS $attribute) {
91 if ($attribute->name == "href") {
92 $author["author-link"] = $attribute->textContent;
97 if (empty($author["author-link"])) {
98 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
99 if (is_object($self)) {
100 foreach ($self AS $attribute) {
101 if ($attribute->name == "href") {
102 $author["author-link"] = $attribute->textContent;
108 if (empty($author["author-link"])) {
109 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
111 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
113 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
115 if (empty($author["author-name"])) {
116 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
118 if (empty($author["author-name"])) {
119 $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;
126 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
128 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
129 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
131 $author["author-link"] = $value;
134 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
136 $author["author-nick"] = $value;
138 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
140 $author["author-location"] = $value;
142 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
144 $author["author-about"] = $value;
146 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
147 if (is_object($avatar)) {
148 foreach ($avatar AS $attribute) {
149 if ($attribute->name == "href") {
150 $author["author-avatar"] = $attribute->textContent;
156 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
158 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
160 $entries = $xpath->query('/atom:feed/atom:entry');
164 if ($xpath->query('/rss/channel')->length > 0) {
165 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
167 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
168 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
170 if (empty($author["author-name"])) {
171 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
173 if (empty($author["author-name"])) {
174 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
176 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
178 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
180 $entries = $xpath->query('/rss/channel/item');
184 $author["author-link"] = $contact["url"];
186 if (empty($author["author-name"])) {
187 $author["author-name"] = $contact["name"];
189 $author["author-avatar"] = $contact["thumb"];
191 $author["owner-link"] = $contact["url"];
192 $author["owner-name"] = $contact["name"];
193 $author["owner-avatar"] = $contact["thumb"];
197 $header["uid"] = $importer["uid"];
198 $header["network"] = Protocol::FEED;
200 $header["origin"] = 0;
201 $header["gravity"] = GRAVITY_PARENT;
202 $header["private"] = 2;
203 $header["verb"] = Activity::POST;
204 $header["object-type"] = Activity\ObjectType::NOTE;
206 $header["contact-id"] = $contact["id"];
208 if (!is_object($entries)) {
209 Logger::log("There are no entries in this feed.", Logger::DEBUG);
214 // Importing older entries first
215 for($i = $entries->length - 1; $i >= 0;--$i) {
216 $entry = $entries->item($i);
218 $item = array_merge($header, $author);
220 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
221 if (!is_object($alternate)) {
222 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
224 if (is_object($alternate)) {
225 foreach ($alternate AS $attribute) {
226 if ($attribute->name == "href") {
227 $item["plink"] = $attribute->textContent;
231 if (empty($item["plink"])) {
232 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
234 if (empty($item["plink"])) {
235 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
238 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
240 if (empty($item["uri"])) {
241 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
243 if (empty($item["uri"])) {
244 $item["uri"] = $item["plink"];
247 $orig_plink = $item["plink"];
249 $item["plink"] = Network::finalUrl($item["plink"]);
251 $item["parent-uri"] = $item["uri"];
254 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
255 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
256 $previous = Item::selectFirst(['id'], $condition);
257 if (DBA::isResult($previous)) {
258 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$previous["id"], Logger::DEBUG);
263 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
265 if (empty($item["title"])) {
266 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
268 if (empty($item["title"])) {
269 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
272 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
274 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
276 if (empty($published)) {
277 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
279 if (empty($published)) {
280 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
282 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
284 if (empty($updated) && !empty($published)) {
285 $updated = $published;
288 if (empty($published) && !empty($updated)) {
289 $published = $updated;
292 if ($published != "") {
293 $item["created"] = $published;
295 if ($updated != "") {
296 $item["edited"] = $updated;
298 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
300 if (empty($creator)) {
301 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
303 if (empty($creator)) {
304 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
306 if ($creator != "") {
307 $item["author-name"] = $creator;
309 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
311 if ($creator != "") {
312 $item["author-name"] = $creator;
316 // <category>Ausland</category>
317 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
321 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
322 foreach ($enclosures AS $enclosure) {
327 foreach ($enclosure->attributes AS $attribute) {
328 if (in_array($attribute->name, ["url", "href"])) {
329 $href = $attribute->textContent;
330 } elseif ($attribute->name == "length") {
331 $length = $attribute->textContent;
332 } elseif ($attribute->name == "type") {
333 $type = $attribute->textContent;
336 if (!empty($item["attach"])) {
337 $item["attach"] .= ',';
339 $item["attach"] = '';
342 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
344 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'"[/attach]';
348 $categories = $xpath->query("category", $entry);
349 foreach ($categories AS $category) {
350 $hashtag = $category->nodeValue;
355 $taglink = "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
359 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
362 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
365 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
367 if (empty($summary)) {
368 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
376 if ($body == $summary) {
380 // remove the content of the title if it is identically to the body
381 // This helps with auto generated titles e.g. from tumblr
382 if (self::titleIsBody($item["title"], $body)) {
385 $item["body"] = HTML::toBBCode($body, $basepath);
387 if (($item["body"] == '') && ($item["title"] != '')) {
388 $item["body"] = $item["title"];
393 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
394 // Handle enclosures and treat them as preview picture
395 foreach ($attachments AS $attachment) {
396 if ($attachment["type"] == "image/jpeg") {
397 $preview = $attachment["link"];
401 // Remove a possible link to the item itself
402 $item["body"] = str_replace($item["plink"], '', $item["body"]);
403 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
405 // Replace the content when the title is longer than the body
406 $replace = (strlen($item["title"]) > strlen($item["body"]));
408 // Replace it, when there is an image in the body
409 if (strstr($item["body"], '[/img]')) {
413 // Replace it, when there is a link in the body
414 if (strstr($item["body"], '[/url]')) {
419 $item["body"] = trim($item["title"]);
422 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
423 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
424 // When the fetched page info text is longer than the body, we do try to enhance the body
425 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
426 // The body is not part of the fetched page info title or page info text. So we add the text to the body
427 $item['body'] .= "\n\n" . $data['text'];
429 // Else we replace the body with the page info text
430 $item['body'] = $data['text'];
434 // We always strip the title since it will be added in the page information
436 $item["body"] = $item["body"].add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
437 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
438 $item["object-type"] = Activity\ObjectType::BOOKMARK;
439 unset($item["attach"]);
441 if (!empty($summary)) {
442 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
445 if ($contact["fetch_further_information"] == 3) {
447 $item["tag"] = $tags;
449 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
450 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
452 $item["body"] .= "\n".$item['tag'];
454 // Add the link to the original feed entry if not present in feed
455 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
456 $item["body"] .= "[hr][url]".$item['plink']."[/url]";
461 Logger::log("Stored feed: ".print_r($item, true), Logger::DEBUG);
463 $notify = Item::isRemoteSelf($contact, $item);
465 // Distributed items should have a well formatted URI.
466 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
468 $item['guid'] = Item::guidFromUri($orig_plink, $a->getHostName());
470 unset($item['parent-uri']);
472 // Set the delivery priority for "remote self" to "medium"
473 $notify = PRIORITY_MEDIUM;
476 $id = Item::insert($item, false, $notify);
478 Logger::log("Feed for contact ".$contact["url"]." stored under id ".$id);
488 return ["header" => $author, "items" => $items];
492 private static function titleIsBody($title, $body)
494 $title = strip_tags($title);
495 $title = trim($title);
496 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
497 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
499 $body = strip_tags($body);
501 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
502 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
504 if (strlen($title) < strlen($body)) {
505 $body = substr($body, 0, strlen($title));
508 if (($title != $body) && (substr($title, -3) == "...")) {
509 $pos = strrpos($title, "...");
511 $title = substr($title, 0, $pos);
512 $body = substr($body, 0, $pos);
515 return ($title == $body);