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\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Database\DBA;
15 use Friendica\Model\Item;
16 use Friendica\Util\Network;
17 use Friendica\Util\XML;
19 require_once 'include/dba.php';
20 require_once 'include/items.php';
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
38 public static function import($xml, $importer, &$contact, &$hub, $simulate = false) {
43 logger("Import Atom/RSS feed '".$contact["name"]."' (Contact ".$contact["id"].") for user ".$importer["uid"], LOGGER_DEBUG);
45 logger("Test Atom/RSS feed", LOGGER_DEBUG);
48 logger('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', NAMESPACE_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', NAMESPACE_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:uri/text()');
127 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
129 $author["author-nick"] = $value;
131 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
133 $author["author-location"] = $value;
135 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
137 $author["author-about"] = $value;
139 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
140 if (is_object($avatar)) {
141 foreach ($avatar AS $attribute) {
142 if ($attribute->name == "href") {
143 $author["author-avatar"] = $attribute->textContent;
149 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
151 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
153 $entries = $xpath->query('/atom:feed/atom:entry');
157 if ($xpath->query('/rss/channel')->length > 0) {
158 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
160 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
161 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
163 if (empty($author["author-name"])) {
164 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
166 if (empty($author["author-name"])) {
167 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
169 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
171 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
173 $entries = $xpath->query('/rss/channel/item');
177 $author["author-link"] = $contact["url"];
179 if (empty($author["author-name"])) {
180 $author["author-name"] = $contact["name"];
182 $author["author-avatar"] = $contact["thumb"];
184 $author["owner-link"] = $contact["url"];
185 $author["owner-name"] = $contact["name"];
186 $author["owner-avatar"] = $contact["thumb"];
190 $header["uid"] = $importer["uid"];
191 $header["network"] = Protocol::FEED;
193 $header["origin"] = 0;
194 $header["gravity"] = GRAVITY_PARENT;
195 $header["private"] = 2;
196 $header["verb"] = ACTIVITY_POST;
197 $header["object-type"] = ACTIVITY_OBJ_NOTE;
199 $header["contact-id"] = $contact["id"];
201 if (!is_object($entries)) {
202 logger("There are no entries in this feed.", LOGGER_DEBUG);
207 // Importing older entries first
208 for($i = $entries->length - 1; $i >= 0;--$i) {
209 $entry = $entries->item($i);
211 $item = array_merge($header, $author);
213 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
214 if (!is_object($alternate)) {
215 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
217 if (is_object($alternate)) {
218 foreach ($alternate AS $attribute) {
219 if ($attribute->name == "href") {
220 $item["plink"] = $attribute->textContent;
224 if (empty($item["plink"])) {
225 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
227 if (empty($item["plink"])) {
228 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
231 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
233 if (empty($item["uri"])) {
234 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
236 if (empty($item["uri"])) {
237 $item["uri"] = $item["plink"];
240 $orig_plink = $item["plink"];
242 $item["plink"] = Network::finalUrl($item["plink"]);
244 $item["parent-uri"] = $item["uri"];
247 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
248 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
249 $previous = Item::selectFirst(['id'], $condition);
250 if (DBA::isResult($previous)) {
251 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$previous["id"], LOGGER_DEBUG);
256 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
258 if (empty($item["title"])) {
259 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
261 if (empty($item["title"])) {
262 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
264 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
266 if (empty($published)) {
267 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
269 if (empty($published)) {
270 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
272 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
274 if (empty($updated)) {
275 $updated = $published;
277 if ($published != "") {
278 $item["created"] = $published;
280 if ($updated != "") {
281 $item["edited"] = $updated;
283 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
285 if (empty($creator)) {
286 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
288 if (empty($creator)) {
289 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
291 if ($creator != "") {
292 $item["author-name"] = $creator;
294 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
296 if ($creator != "") {
297 $item["author-name"] = $creator;
301 // <category>Ausland</category>
302 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
306 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
307 foreach ($enclosures AS $enclosure) {
313 foreach ($enclosure->attributes AS $attribute) {
314 if (in_array($attribute->name, ["url", "href"])) {
315 $href = $attribute->textContent;
316 } elseif ($attribute->name == "length") {
317 $length = $attribute->textContent;
318 } elseif ($attribute->name == "type") {
319 $type = $attribute->textContent;
322 if (!empty($item["attach"])) {
323 $item["attach"] .= ',';
325 $item["attach"] = '';
328 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
330 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'"[/attach]';
334 $categories = $xpath->query("category", $entry);
335 foreach ($categories AS $category) {
336 $hashtag = $category->nodeValue;
341 $taglink = "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
345 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
348 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
351 $body = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
354 $body = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
357 // remove the content of the title if it is identically to the body
358 // This helps with auto generated titles e.g. from tumblr
359 if (self::titleIsBody($item["title"], $body)) {
362 $item["body"] = HTML::toBBCode($body, $basepath);
364 if (($item["body"] == '') && ($item["title"] != '')) {
365 $item["body"] = $item["title"];
370 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
371 // Handle enclosures and treat them as preview picture
372 foreach ($attachments AS $attachment) {
373 if ($attachment["type"] == "image/jpeg") {
374 $preview = $attachment["link"];
378 // Remove a possible link to the item itself
379 $item["body"] = str_replace($item["plink"], '', $item["body"]);
380 $item["body"] = preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]);
382 // Replace the content when the title is longer than the body
383 $replace = (strlen($item["title"]) > strlen($item["body"]));
385 // Replace it, when there is an image in the body
386 if (strstr($item["body"], '[/img]')) {
390 // Replace it, when there is a link in the body
391 if (strstr($item["body"], '[/url]')) {
396 $item["body"] = $item["title"];
398 // We always strip the title since it will be added in the page information
400 $item["body"] = $item["body"].add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
401 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
402 $item["object-type"] = ACTIVITY_OBJ_BOOKMARK;
403 unset($item["attach"]);
405 if ($contact["fetch_further_information"] == 3) {
407 $item["tag"] = $tags;
409 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
410 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
412 $item["body"] .= "\n".$item['tag'];
414 // Add the link to the original feed entry if not present in feed
415 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
416 $item["body"] .= "[hr][url]".$item['plink']."[/url]";
421 logger("Stored feed: ".print_r($item, true), LOGGER_DEBUG);
423 $notify = Item::isRemoteSelf($contact, $item);
425 // Distributed items should have a well formatted URI.
426 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
428 $item['guid'] = Item::guidFromUri($orig_plink, $a->get_hostname());
430 unset($item['parent-uri']);
432 // Set the delivery priority for "remote self" to "medium"
433 $notify = PRIORITY_MEDIUM;
436 $id = Item::insert($item, false, $notify);
438 logger("Feed for contact ".$contact["url"]." stored under id ".$id);
448 return ["header" => $author, "items" => $items];
452 private static function titleIsBody($title, $body)
454 $title = strip_tags($title);
455 $title = trim($title);
456 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
457 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
459 $body = strip_tags($body);
461 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
462 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
464 if (strlen($title) < strlen($body)) {
465 $body = substr($body, 0, strlen($title));
468 if (($title != $body) && (substr($title, -3) == "...")) {
469 $pos = strrpos($title, "...");
471 $title = substr($title, 0, $pos);
472 $body = substr($body, 0, $pos);
475 return ($title == $body);