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\Database\DBA;
16 use Friendica\Model\Item;
17 use Friendica\Util\ParseUrl;
18 use Friendica\Util\Network;
19 use Friendica\Util\XML;
22 * @brief This class contain functions to import feeds
27 * @brief 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
32 * @param string $hub Unused dummy value for compatibility reasons
33 * @param bool $simulate If enabled, no data is imported
35 * @return array In simulation mode it returns the header and the first item
36 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
38 public static function import($xml, $importer, &$contact, &$hub, $simulate = false) {
43 Logger::log("Import Atom/RSS feed '".$contact["name"]."' (Contact ".$contact["id"].") for user ".$importer["uid"], Logger::DEBUG);
45 Logger::log("Test Atom/RSS feed", Logger::DEBUG);
48 Logger::log('XML is empty.', Logger::DEBUG);
52 if (!empty($contact['poll'])) {
53 $basepath = $contact['poll'];
54 } elseif (!empty($contact['url'])) {
55 $basepath = $contact['url'];
60 $doc = new DOMDocument();
61 @$doc->loadXML(trim($xml));
62 $xpath = new DOMXPath($doc);
63 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
64 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
65 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
66 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
67 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
68 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
69 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
75 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
76 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
77 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
79 if (empty($author["author-name"])) {
80 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
82 $entries = $xpath->query('/rdf:RDF/rss:item');
86 if ($xpath->query('/atom:feed')->length > 0) {
87 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
88 if (is_object($alternate)) {
89 foreach ($alternate AS $attribute) {
90 if ($attribute->name == "href") {
91 $author["author-link"] = $attribute->textContent;
96 if (empty($author["author-link"])) {
97 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
98 if (is_object($self)) {
99 foreach ($self AS $attribute) {
100 if ($attribute->name == "href") {
101 $author["author-link"] = $attribute->textContent;
107 if (empty($author["author-link"])) {
108 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
110 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
112 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
114 if (empty($author["author-name"])) {
115 $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()');
120 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
122 $author["author-name"] = $value;
125 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
127 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
128 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
130 $author["author-link"] = $value;
133 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
135 $author["author-nick"] = $value;
137 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
139 $author["author-location"] = $value;
141 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
143 $author["author-about"] = $value;
145 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
146 if (is_object($avatar)) {
147 foreach ($avatar AS $attribute) {
148 if ($attribute->name == "href") {
149 $author["author-avatar"] = $attribute->textContent;
155 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
157 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
159 $entries = $xpath->query('/atom:feed/atom:entry');
163 if ($xpath->query('/rss/channel')->length > 0) {
164 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
166 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
167 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
169 if (empty($author["author-name"])) {
170 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
172 if (empty($author["author-name"])) {
173 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
175 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
177 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
179 $entries = $xpath->query('/rss/channel/item');
183 $author["author-link"] = $contact["url"];
185 if (empty($author["author-name"])) {
186 $author["author-name"] = $contact["name"];
188 $author["author-avatar"] = $contact["thumb"];
190 $author["owner-link"] = $contact["url"];
191 $author["owner-name"] = $contact["name"];
192 $author["owner-avatar"] = $contact["thumb"];
196 $header["uid"] = $importer["uid"];
197 $header["network"] = Protocol::FEED;
199 $header["origin"] = 0;
200 $header["gravity"] = GRAVITY_PARENT;
201 $header["private"] = 2;
202 $header["verb"] = Activity::POST;
203 $header["object-type"] = Activity\ObjectType::NOTE;
205 $header["contact-id"] = $contact["id"];
207 if (!is_object($entries)) {
208 Logger::log("There are no entries in this feed.", Logger::DEBUG);
213 // Importing older entries first
214 for($i = $entries->length - 1; $i >= 0;--$i) {
215 $entry = $entries->item($i);
217 $item = array_merge($header, $author);
219 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
220 if (!is_object($alternate)) {
221 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
223 if (is_object($alternate)) {
224 foreach ($alternate AS $attribute) {
225 if ($attribute->name == "href") {
226 $item["plink"] = $attribute->textContent;
230 if (empty($item["plink"])) {
231 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
233 if (empty($item["plink"])) {
234 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
237 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
239 if (empty($item["uri"])) {
240 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
242 if (empty($item["uri"])) {
243 $item["uri"] = $item["plink"];
246 $orig_plink = $item["plink"];
248 $item["plink"] = Network::finalUrl($item["plink"]);
250 $item["parent-uri"] = $item["uri"];
253 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
254 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
255 $previous = Item::selectFirst(['id'], $condition);
256 if (DBA::isResult($previous)) {
257 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$previous["id"], Logger::DEBUG);
262 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
264 if (empty($item["title"])) {
265 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
267 if (empty($item["title"])) {
268 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
271 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
273 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
275 if (empty($published)) {
276 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
278 if (empty($published)) {
279 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
281 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
283 if (empty($updated) && !empty($published)) {
284 $updated = $published;
287 if (empty($published) && !empty($updated)) {
288 $published = $updated;
291 if ($published != "") {
292 $item["created"] = $published;
294 if ($updated != "") {
295 $item["edited"] = $updated;
297 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
299 if (empty($creator)) {
300 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
302 if (empty($creator)) {
303 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
305 if ($creator != "") {
306 $item["author-name"] = $creator;
308 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
310 if ($creator != "") {
311 $item["author-name"] = $creator;
315 // <category>Ausland</category>
316 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
320 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
321 foreach ($enclosures AS $enclosure) {
326 foreach ($enclosure->attributes AS $attribute) {
327 if (in_array($attribute->name, ["url", "href"])) {
328 $href = $attribute->textContent;
329 } elseif ($attribute->name == "length") {
330 $length = $attribute->textContent;
331 } elseif ($attribute->name == "type") {
332 $type = $attribute->textContent;
335 if (!empty($item["attach"])) {
336 $item["attach"] .= ',';
338 $item["attach"] = '';
341 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
343 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'"[/attach]';
347 $categories = $xpath->query("category", $entry);
348 foreach ($categories AS $category) {
349 $hashtag = $category->nodeValue;
354 $taglink = "#[url=" . DI::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
358 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
361 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
364 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
366 if (empty($summary)) {
367 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
375 if ($body == $summary) {
379 // remove the content of the title if it is identically to the body
380 // This helps with auto generated titles e.g. from tumblr
381 if (self::titleIsBody($item["title"], $body)) {
384 $item["body"] = HTML::toBBCode($body, $basepath);
386 if (($item["body"] == '') && ($item["title"] != '')) {
387 $item["body"] = $item["title"];
392 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
393 // Handle enclosures and treat them as preview picture
394 foreach ($attachments AS $attachment) {
395 if ($attachment["type"] == "image/jpeg") {
396 $preview = $attachment["link"];
400 // Remove a possible link to the item itself
401 $item["body"] = str_replace($item["plink"], '', $item["body"]);
402 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
404 // Replace the content when the title is longer than the body
405 $replace = (strlen($item["title"]) > strlen($item["body"]));
407 // Replace it, when there is an image in the body
408 if (strstr($item["body"], '[/img]')) {
412 // Replace it, when there is a link in the body
413 if (strstr($item["body"], '[/url]')) {
418 $item["body"] = trim($item["title"]);
421 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
422 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
423 // When the fetched page info text is longer than the body, we do try to enhance the body
424 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
425 // The body is not part of the fetched page info title or page info text. So we add the text to the body
426 $item['body'] .= "\n\n" . $data['text'];
428 // Else we replace the body with the page info text
429 $item['body'] = $data['text'];
433 // We always strip the title since it will be added in the page information
435 $item["body"] = $item["body"].add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
436 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
437 $item["object-type"] = Activity\ObjectType::BOOKMARK;
438 unset($item["attach"]);
440 if (!empty($summary)) {
441 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
444 if ($contact["fetch_further_information"] == 3) {
446 $item["tag"] = $tags;
448 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
449 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
451 $item["body"] .= "\n".$item['tag'];
453 // Add the link to the original feed entry if not present in feed
454 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
455 $item["body"] .= "[hr][url]".$item['plink']."[/url]";
460 Logger::log("Stored feed: ".print_r($item, true), Logger::DEBUG);
462 $notify = Item::isRemoteSelf($contact, $item);
464 // Distributed items should have a well formatted URI.
465 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
467 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
469 unset($item['parent-uri']);
471 // Set the delivery priority for "remote self" to "medium"
472 $notify = PRIORITY_MEDIUM;
475 $id = Item::insert($item, false, $notify);
477 Logger::log("Feed for contact ".$contact["url"]." stored under id ".$id);
487 return ["header" => $author, "items" => $items];
491 private static function titleIsBody($title, $body)
493 $title = strip_tags($title);
494 $title = trim($title);
495 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
496 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
498 $body = strip_tags($body);
500 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
501 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
503 if (strlen($title) < strlen($body)) {
504 $body = substr($body, 0, strlen($title));
507 if (($title != $body) && (substr($title, -3) == "...")) {
508 $pos = strrpos($title, "...");
510 $title = substr($title, 0, $pos);
511 $body = substr($body, 0, $pos);
514 return ($title == $body);