3 * @file src/Protocol/Feed.php
4 * @brief Imports RSS/RDF/Atom feeds
7 namespace Friendica\Protocol;
9 use Friendica\Database\DBM;
10 use Friendica\Core\System;
11 use Friendica\Model\Item;
12 use Friendica\Util\Network;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Util\XML;
20 require_once 'include/dba.php';
21 require_once 'include/items.php';
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
39 public static function import($xml, $importer, &$contact, &$hub, $simulate = false) {
44 logger("Import Atom/RSS feed '".$contact["name"]."' (Contact ".$contact["id"].") for user ".$importer["uid"], LOGGER_DEBUG);
46 logger("Test Atom/RSS feed", LOGGER_DEBUG);
49 logger('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', NAMESPACE_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', NAMESPACE_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:uri/text()');
128 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
130 $author["author-nick"] = $value;
132 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
134 $author["author-location"] = $value;
136 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
138 $author["author-about"] = $value;
140 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
141 if (is_object($avatar)) {
142 foreach ($avatar AS $attribute) {
143 if ($attribute->name == "href") {
144 $author["author-avatar"] = $attribute->textContent;
150 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
152 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
154 $entries = $xpath->query('/atom:feed/atom:entry');
158 if ($xpath->query('/rss/channel')->length > 0) {
159 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
161 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
162 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
164 if (empty($author["author-name"])) {
165 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
167 if (empty($author["author-name"])) {
168 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
170 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
172 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
174 $entries = $xpath->query('/rss/channel/item');
178 $author["author-link"] = $contact["url"];
180 if (empty($author["author-name"])) {
181 $author["author-name"] = $contact["name"];
183 $author["author-avatar"] = $contact["thumb"];
185 $author["owner-link"] = $contact["url"];
186 $author["owner-name"] = $contact["name"];
187 $author["owner-avatar"] = $contact["thumb"];
191 $header["uid"] = $importer["uid"];
192 $header["network"] = NETWORK_FEED;
194 $header["origin"] = 0;
195 $header["gravity"] = GRAVITY_PARENT;
196 $header["private"] = 2;
197 $header["verb"] = ACTIVITY_POST;
198 $header["object-type"] = ACTIVITY_OBJ_NOTE;
200 $header["contact-id"] = $contact["id"];
202 if (!is_object($entries)) {
203 logger("There are no entries in this feed.", LOGGER_DEBUG);
208 // Importing older entries first
209 for($i = $entries->length - 1; $i >= 0;--$i) {
210 $entry = $entries->item($i);
212 $item = array_merge($header, $author);
214 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
215 if (!is_object($alternate)) {
216 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
218 if (is_object($alternate)) {
219 foreach ($alternate AS $attribute) {
220 if ($attribute->name == "href") {
221 $item["plink"] = $attribute->textContent;
225 if (empty($item["plink"])) {
226 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
228 if (empty($item["plink"])) {
229 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
232 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
234 if (empty($item["uri"])) {
235 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
237 if (empty($item["uri"])) {
238 $item["uri"] = $item["plink"];
241 $orig_plink = $item["plink"];
243 $item["plink"] = Network::finalUrl($item["plink"]);
245 $item["parent-uri"] = $item["uri"];
248 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
249 $importer["uid"], $item["uri"], NETWORK_FEED, NETWORK_DFRN];
250 $previous = Item::selectFirst(['id'], $condition);
251 if (DBM::is_result($previous)) {
252 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$previous["id"], LOGGER_DEBUG);
257 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
259 if (empty($item["title"])) {
260 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
262 if (empty($item["title"])) {
263 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
265 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
267 if (empty($published)) {
268 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
270 if (empty($published)) {
271 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
273 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
275 if (empty($updated)) {
276 $updated = $published;
278 if ($published != "") {
279 $item["created"] = $published;
281 if ($updated != "") {
282 $item["edited"] = $updated;
284 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
286 if (empty($creator)) {
287 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
289 if (empty($creator)) {
290 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
292 if ($creator != "") {
293 $item["author-name"] = $creator;
295 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
297 if ($creator != "") {
298 $item["author-name"] = $creator;
302 // <category>Ausland</category>
303 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
307 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
308 foreach ($enclosures AS $enclosure) {
314 foreach ($enclosure->attributes AS $attribute) {
315 if (in_array($attribute->name, ["url", "href"])) {
316 $href = $attribute->textContent;
317 } elseif ($attribute->name == "length") {
318 $length = $attribute->textContent;
319 } elseif ($attribute->name == "type") {
320 $type = $attribute->textContent;
323 if (!empty($item["attach"])) {
324 $item["attach"] .= ',';
326 $item["attach"] = '';
329 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
331 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'"[/attach]';
335 $categories = $xpath->query("category", $entry);
336 foreach ($categories AS $category) {
337 $hashtag = $category->nodeValue;
342 $taglink = "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
346 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
349 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
352 $body = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
355 $body = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
358 // remove the content of the title if it is identically to the body
359 // This helps with auto generated titles e.g. from tumblr
360 if (self::titleIsBody($item["title"], $body)) {
363 $item["body"] = HTML::toBBCode($body, $basepath);
365 if (($item["body"] == '') && ($item["title"] != '')) {
366 $item["body"] = $item["title"];
371 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
372 // Handle enclosures and treat them as preview picture
373 foreach ($attachments AS $attachment) {
374 if ($attachment["type"] == "image/jpeg") {
375 $preview = $attachment["link"];
379 // Remove a possible link to the item itself
380 $item["body"] = str_replace($item["plink"], '', $item["body"]);
381 $item["body"] = preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]);
383 // Replace the content when the title is longer than the body
384 $replace = (strlen($item["title"]) > strlen($item["body"]));
386 // Replace it, when there is an image in the body
387 if (strstr($item["body"], '[/img]')) {
391 // Replace it, when there is a link in the body
392 if (strstr($item["body"], '[/url]')) {
397 $item["body"] = $item["title"];
399 // We always strip the title since it will be added in the page information
401 $item["body"] = $item["body"].add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
402 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
403 $item["object-type"] = ACTIVITY_OBJ_BOOKMARK;
404 unset($item["attach"]);
406 if ($contact["fetch_further_information"] == 3) {
408 $item["tag"] = $tags;
410 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
411 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
413 $item["body"] .= "\n".$item['tag'];
415 // Add the link to the original feed entry if not present in feed
416 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
417 $item["body"] .= "[hr][url]".$item['plink']."[/url]";
422 logger("Stored feed: ".print_r($item, true), LOGGER_DEBUG);
424 $notify = Item::isRemoteSelf($contact, $item);
426 // Distributed items should have a well formatted URI.
427 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
429 $item['guid'] = Item::guidFromUri($orig_plink, $a->get_hostname());
431 unset($item['parent-uri']);
433 // Set the delivery priority for "remote self" to "medium"
434 $notify = PRIORITY_MEDIUM;
437 $id = Item::insert($item, false, $notify);
439 logger("Feed for contact ".$contact["url"]." stored under id ".$id);
449 return ["header" => $author, "items" => $items];
453 private static function titleIsBody($title, $body)
455 $title = strip_tags($title);
456 $title = trim($title);
457 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
458 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
460 $body = strip_tags($body);
462 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
463 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
465 if (strlen($title) < strlen($body)) {
466 $body = substr($body, 0, strlen($title));
469 if (($title != $body) && (substr($title, -3) == "...")) {
470 $pos = strrpos($title, "...");
472 $title = substr($title, 0, $pos);
473 $body = substr($body, 0, $pos);
476 return ($title == $body);