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\Util\Network;
18 use Friendica\Util\XML;
21 * @brief This class contain functions to import feeds
26 * @brief Read a RSS/RDF/Atom feed and create an item entry for it
28 * @param string $xml The feed data
29 * @param array $importer The user record of the importer
30 * @param array $contact The contact record of the feed
31 * @param string $hub Unused dummy value for compatibility reasons
32 * @param bool $simulate If enabled, no data is imported
34 * @return array In simulation mode it returns the header and the first item
35 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
37 public static function import($xml, $importer, &$contact, &$hub, $simulate = false) {
42 Logger::log("Import Atom/RSS feed '".$contact["name"]."' (Contact ".$contact["id"].") for user ".$importer["uid"], Logger::DEBUG);
44 Logger::log("Test Atom/RSS feed", Logger::DEBUG);
47 Logger::log('XML is empty.', Logger::DEBUG);
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', NAMESPACE_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', NAMESPACE_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()');
116 if (empty($author["author-name"])) {
117 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
119 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
121 $author["author-name"] = $value;
124 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
126 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
127 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
129 $author["author-link"] = $value;
132 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
134 $author["author-nick"] = $value;
136 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
138 $author["author-location"] = $value;
140 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
142 $author["author-about"] = $value;
144 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
145 if (is_object($avatar)) {
146 foreach ($avatar AS $attribute) {
147 if ($attribute->name == "href") {
148 $author["author-avatar"] = $attribute->textContent;
154 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
156 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
158 $entries = $xpath->query('/atom:feed/atom:entry');
162 if ($xpath->query('/rss/channel')->length > 0) {
163 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
165 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
166 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
168 if (empty($author["author-name"])) {
169 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
171 if (empty($author["author-name"])) {
172 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
174 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
176 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
178 $entries = $xpath->query('/rss/channel/item');
182 $author["author-link"] = $contact["url"];
184 if (empty($author["author-name"])) {
185 $author["author-name"] = $contact["name"];
187 $author["author-avatar"] = $contact["thumb"];
189 $author["owner-link"] = $contact["url"];
190 $author["owner-name"] = $contact["name"];
191 $author["owner-avatar"] = $contact["thumb"];
195 $header["uid"] = $importer["uid"];
196 $header["network"] = Protocol::FEED;
198 $header["origin"] = 0;
199 $header["gravity"] = GRAVITY_PARENT;
200 $header["private"] = 2;
201 $header["verb"] = ACTIVITY_POST;
202 $header["object-type"] = ACTIVITY_OBJ_NOTE;
204 $header["contact-id"] = $contact["id"];
206 if (!is_object($entries)) {
207 Logger::log("There are no entries in this feed.", Logger::DEBUG);
212 // Importing older entries first
213 for($i = $entries->length - 1; $i >= 0;--$i) {
214 $entry = $entries->item($i);
216 $item = array_merge($header, $author);
218 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
219 if (!is_object($alternate)) {
220 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
222 if (is_object($alternate)) {
223 foreach ($alternate AS $attribute) {
224 if ($attribute->name == "href") {
225 $item["plink"] = $attribute->textContent;
229 if (empty($item["plink"])) {
230 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
232 if (empty($item["plink"])) {
233 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
236 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
238 if (empty($item["uri"])) {
239 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
241 if (empty($item["uri"])) {
242 $item["uri"] = $item["plink"];
245 $orig_plink = $item["plink"];
247 $item["plink"] = Network::finalUrl($item["plink"]);
249 $item["parent-uri"] = $item["uri"];
252 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
253 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
254 $previous = Item::selectFirst(['id'], $condition);
255 if (DBA::isResult($previous)) {
256 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$previous["id"], Logger::DEBUG);
261 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
263 if (empty($item["title"])) {
264 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
266 if (empty($item["title"])) {
267 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
269 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
271 if (empty($published)) {
272 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
274 if (empty($published)) {
275 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
277 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
279 if (empty($updated) && !empty($published)) {
280 $updated = $published;
283 if (empty($published) && !empty($updated)) {
284 $published = $updated;
287 if ($published != "") {
288 $item["created"] = $published;
290 if ($updated != "") {
291 $item["edited"] = $updated;
293 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
295 if (empty($creator)) {
296 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
298 if (empty($creator)) {
299 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
301 if ($creator != "") {
302 $item["author-name"] = $creator;
304 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
306 if ($creator != "") {
307 $item["author-name"] = $creator;
311 // <category>Ausland</category>
312 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
316 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
317 foreach ($enclosures AS $enclosure) {
322 foreach ($enclosure->attributes AS $attribute) {
323 if (in_array($attribute->name, ["url", "href"])) {
324 $href = $attribute->textContent;
325 } elseif ($attribute->name == "length") {
326 $length = $attribute->textContent;
327 } elseif ($attribute->name == "type") {
328 $type = $attribute->textContent;
331 if (!empty($item["attach"])) {
332 $item["attach"] .= ',';
334 $item["attach"] = '';
337 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
339 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'"[/attach]';
343 $categories = $xpath->query("category", $entry);
344 foreach ($categories AS $category) {
345 $hashtag = $category->nodeValue;
350 $taglink = "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
354 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
357 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
360 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
362 if (empty($summary)) {
363 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
371 if ($body == $summary) {
375 // remove the content of the title if it is identically to the body
376 // This helps with auto generated titles e.g. from tumblr
377 if (self::titleIsBody($item["title"], $body)) {
380 $item["body"] = HTML::toBBCode($body, $basepath);
382 if (($item["body"] == '') && ($item["title"] != '')) {
383 $item["body"] = $item["title"];
388 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
389 // Handle enclosures and treat them as preview picture
390 foreach ($attachments AS $attachment) {
391 if ($attachment["type"] == "image/jpeg") {
392 $preview = $attachment["link"];
396 // Remove a possible link to the item itself
397 $item["body"] = str_replace($item["plink"], '', $item["body"]);
398 $item["body"] = preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]);
400 // Replace the content when the title is longer than the body
401 $replace = (strlen($item["title"]) > strlen($item["body"]));
403 // Replace it, when there is an image in the body
404 if (strstr($item["body"], '[/img]')) {
408 // Replace it, when there is a link in the body
409 if (strstr($item["body"], '[/url]')) {
414 $item["body"] = $item["title"];
416 // We always strip the title since it will be added in the page information
418 $item["body"] = $item["body"].add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
419 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
420 $item["object-type"] = ACTIVITY_OBJ_BOOKMARK;
421 unset($item["attach"]);
423 if (!empty($summary)) {
424 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
427 if ($contact["fetch_further_information"] == 3) {
429 $item["tag"] = $tags;
431 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
432 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
434 $item["body"] .= "\n".$item['tag'];
436 // Add the link to the original feed entry if not present in feed
437 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
438 $item["body"] .= "[hr][url]".$item['plink']."[/url]";
443 Logger::log("Stored feed: ".print_r($item, true), Logger::DEBUG);
445 $notify = Item::isRemoteSelf($contact, $item);
447 // Distributed items should have a well formatted URI.
448 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
450 $item['guid'] = Item::guidFromUri($orig_plink, $a->getHostName());
452 unset($item['parent-uri']);
454 // Set the delivery priority for "remote self" to "medium"
455 $notify = PRIORITY_MEDIUM;
458 $id = Item::insert($item, false, $notify);
460 Logger::log("Feed for contact ".$contact["url"]." stored under id ".$id);
470 return ["header" => $author, "items" => $items];
474 private static function titleIsBody($title, $body)
476 $title = strip_tags($title);
477 $title = trim($title);
478 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
479 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
481 $body = strip_tags($body);
483 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
484 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
486 if (strlen($title) < strlen($body)) {
487 $body = substr($body, 0, strlen($title));
490 if (($title != $body) && (substr($title, -3) == "...")) {
491 $pos = strrpos($title, "...");
493 $title = substr($title, 0, $pos);
494 $body = substr($body, 0, $pos);
497 return ($title == $body);