]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
Merge pull request #5574 from annando/issue-5436
[friendica.git] / src / Protocol / Feed.php
1 <?php
2 /**
3  * @file src/Protocol/Feed.php
4  * @brief Imports RSS/RDF/Atom feeds
5  *
6  */
7 namespace Friendica\Protocol;
8
9 use DOMDocument;
10 use DOMXPath;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Item;
15 use Friendica\Util\Network;
16 use Friendica\Util\XML;
17
18 require_once 'include/dba.php';
19 require_once 'include/items.php';
20
21 /**
22  * @brief This class contain functions to import feeds
23  *
24  */
25 class Feed {
26         /**
27          * @brief Read a RSS/RDF/Atom feed and create an item entry for it
28          *
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
34          *
35          * @return array In simulation mode it returns the header and the first item
36          */
37         public static function import($xml, $importer, &$contact, &$hub, $simulate = false) {
38
39                 $a = get_app();
40
41                 if (!$simulate) {
42                         logger("Import Atom/RSS feed '".$contact["name"]."' (Contact ".$contact["id"].") for user ".$importer["uid"], LOGGER_DEBUG);
43                 } else {
44                         logger("Test Atom/RSS feed", LOGGER_DEBUG);
45                 }
46                 if (empty($xml)) {
47                         logger('XML is empty.', LOGGER_DEBUG);
48                         return;
49                 }
50
51                 if (!empty($contact['poll'])) {
52                         $basepath = $contact['poll'];
53                 } elseif (!empty($contact['url'])) {
54                         $basepath = $contact['url'];
55                 } else {
56                         $basepath = '';
57                 }
58
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);
69
70                 $author = [];
71                 $entries = null;
72
73                 // Is it RDF?
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()');
77
78                         if (empty($author["author-name"])) {
79                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
80                         }
81                         $entries = $xpath->query('/rdf:RDF/rss:item');
82                 }
83
84                 // Is it Atom?
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;
91                                         }
92                                 }
93                         }
94
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;
101                                                 }
102                                         }
103                                 }
104                         }
105
106                         if (empty($author["author-link"])) {
107                                 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
108                         }
109                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
110
111                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
112
113                         if (empty($author["author-name"])) {
114                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
115                         }
116                         if (empty($author["author-name"])) {
117                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
118                         }
119                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
120                         if ($value != "") {
121                                 $author["author-name"] = $value;
122                         }
123                         if ($simulate) {
124                                 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:uri/text()');
125
126                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
127                                 if ($value != "") {
128                                         $author["author-nick"] = $value;
129                                 }
130                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
131                                 if ($value != "") {
132                                         $author["author-location"] = $value;
133                                 }
134                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
135                                 if ($value != "") {
136                                         $author["author-about"] = $value;
137                                 }
138                                 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
139                                 if (is_object($avatar)) {
140                                         foreach ($avatar AS $attribute) {
141                                                 if ($attribute->name == "href") {
142                                                         $author["author-avatar"] = $attribute->textContent;
143                                                 }
144                                         }
145                                 }
146                         }
147
148                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
149
150                         $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
151
152                         $entries = $xpath->query('/atom:feed/atom:entry');
153                 }
154
155                 // Is it RSS?
156                 if ($xpath->query('/rss/channel')->length > 0) {
157                         $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
158
159                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
160                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
161
162                         if (empty($author["author-name"])) {
163                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
164                         }
165                         if (empty($author["author-name"])) {
166                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
167                         }
168                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
169
170                         $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
171
172                         $entries = $xpath->query('/rss/channel/item');
173                 }
174
175                 if (!$simulate) {
176                         $author["author-link"] = $contact["url"];
177
178                         if (empty($author["author-name"])) {
179                                 $author["author-name"] = $contact["name"];
180                         }
181                         $author["author-avatar"] = $contact["thumb"];
182
183                         $author["owner-link"] = $contact["url"];
184                         $author["owner-name"] = $contact["name"];
185                         $author["owner-avatar"] = $contact["thumb"];
186                 }
187
188                 $header = [];
189                 $header["uid"] = $importer["uid"];
190                 $header["network"] = NETWORK_FEED;
191                 $header["wall"] = 0;
192                 $header["origin"] = 0;
193                 $header["gravity"] = GRAVITY_PARENT;
194                 $header["private"] = 2;
195                 $header["verb"] = ACTIVITY_POST;
196                 $header["object-type"] = ACTIVITY_OBJ_NOTE;
197
198                 $header["contact-id"] = $contact["id"];
199
200                 if (!is_object($entries)) {
201                         logger("There are no entries in this feed.", LOGGER_DEBUG);
202                         return;
203                 }
204
205                 $items = [];
206                 // Importing older entries first
207                 for($i = $entries->length - 1; $i >= 0;--$i) {
208                         $entry = $entries->item($i);
209
210                         $item = array_merge($header, $author);
211
212                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
213                         if (!is_object($alternate)) {
214                                 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
215                         }
216                         if (is_object($alternate)) {
217                                 foreach ($alternate AS $attribute) {
218                                         if ($attribute->name == "href") {
219                                                 $item["plink"] = $attribute->textContent;
220                                         }
221                                 }
222                         }
223                         if (empty($item["plink"])) {
224                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
225                         }
226                         if (empty($item["plink"])) {
227                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
228                         }
229
230                         $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
231
232                         if (empty($item["uri"])) {
233                                 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
234                         }
235                         if (empty($item["uri"])) {
236                                 $item["uri"] = $item["plink"];
237                         }
238
239                         $orig_plink = $item["plink"];
240
241                         $item["plink"] = Network::finalUrl($item["plink"]);
242
243                         $item["parent-uri"] = $item["uri"];
244
245                         if (!$simulate) {
246                                 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
247                                         $importer["uid"], $item["uri"], NETWORK_FEED, NETWORK_DFRN];
248                                 $previous = Item::selectFirst(['id'], $condition);
249                                 if (DBA::isResult($previous)) {
250                                         logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$previous["id"], LOGGER_DEBUG);
251                                         continue;
252                                 }
253                         }
254
255                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
256
257                         if (empty($item["title"])) {
258                                 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
259                         }
260                         if (empty($item["title"])) {
261                                 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
262                         }
263                         $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
264
265                         if (empty($published)) {
266                                 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
267                         }
268                         if (empty($published)) {
269                                 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
270                         }
271                         $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
272
273                         if (empty($updated)) {
274                                 $updated = $published;
275                         }
276                         if ($published != "") {
277                                 $item["created"] = $published;
278                         }
279                         if ($updated != "") {
280                                 $item["edited"] = $updated;
281                         }
282                         $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
283
284                         if (empty($creator)) {
285                                 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
286                         }
287                         if (empty($creator)) {
288                                 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
289                         }
290                         if ($creator != "") {
291                                 $item["author-name"] = $creator;
292                         }
293                         $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
294
295                         if ($creator != "") {
296                                 $item["author-name"] = $creator;
297                         }
298
299                         /// @TODO ?
300                         // <category>Ausland</category>
301                         // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
302
303                         $attachments = [];
304
305                         $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
306                         foreach ($enclosures AS $enclosure) {
307                                 $href = "";
308                                 $length = "";
309                                 $type = "";
310                                 $title = "";
311
312                                 foreach ($enclosure->attributes AS $attribute) {
313                                         if (in_array($attribute->name, ["url", "href"])) {
314                                                 $href = $attribute->textContent;
315                                         } elseif ($attribute->name == "length") {
316                                                 $length = $attribute->textContent;
317                                         } elseif ($attribute->name == "type") {
318                                                 $type = $attribute->textContent;
319                                         }
320                                 }
321                                 if (!empty($item["attach"])) {
322                                         $item["attach"] .= ',';
323                                 } else {
324                                         $item["attach"] = '';
325                                 }
326
327                                 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
328
329                                 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'"[/attach]';
330                         }
331
332                         $tags = '';
333                         $categories = $xpath->query("category", $entry);
334                         foreach ($categories AS $category) {
335                                 $hashtag = $category->nodeValue;
336                                 if ($tags != '') {
337                                         $tags .= ', ';
338                                 }
339
340                                 $taglink = "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
341                                 $tags .= $taglink;
342                         }
343
344                         $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
345
346                         if (empty($body)) {
347                                 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
348                         }
349                         if (empty($body)) {
350                                 $body = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
351                         }
352                         if (empty($body)) {
353                                 $body = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
354                         }
355
356                         // remove the content of the title if it is identically to the body
357                         // This helps with auto generated titles e.g. from tumblr
358                         if (self::titleIsBody($item["title"], $body)) {
359                                 $item["title"] = "";
360                         }
361                         $item["body"] = HTML::toBBCode($body, $basepath);
362
363                         if (($item["body"] == '') && ($item["title"] != '')) {
364                                 $item["body"] = $item["title"];
365                                 $item["title"] = '';
366                         }
367
368                         $preview = '';
369                         if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
370                                 // Handle enclosures and treat them as preview picture
371                                 foreach ($attachments AS $attachment) {
372                                         if ($attachment["type"] == "image/jpeg") {
373                                                 $preview = $attachment["link"];
374                                         }
375                                 }
376
377                                 // Remove a possible link to the item itself
378                                 $item["body"] = str_replace($item["plink"], '', $item["body"]);
379                                 $item["body"] = preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]);
380
381                                 // Replace the content when the title is longer than the body
382                                 $replace = (strlen($item["title"]) > strlen($item["body"]));
383
384                                 // Replace it, when there is an image in the body
385                                 if (strstr($item["body"], '[/img]')) {
386                                         $replace = true;
387                                 }
388
389                                 // Replace it, when there is a link in the body
390                                 if (strstr($item["body"], '[/url]')) {
391                                         $replace = true;
392                                 }
393
394                                 if ($replace) {
395                                         $item["body"] = $item["title"];
396                                 }
397                                 // We always strip the title since it will be added in the page information
398                                 $item["title"] = "";
399                                 $item["body"] = $item["body"].add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
400                                 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
401                                 $item["object-type"] = ACTIVITY_OBJ_BOOKMARK;
402                                 unset($item["attach"]);
403                         } else {
404                                 if ($contact["fetch_further_information"] == 3) {
405                                         if (!empty($tags)) {
406                                                 $item["tag"] = $tags;
407                                         } else {
408                                                 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
409                                                 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
410                                         }
411                                         $item["body"] .= "\n".$item['tag'];
412                                 }
413                                 // Add the link to the original feed entry if not present in feed
414                                 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
415                                         $item["body"] .= "[hr][url]".$item['plink']."[/url]";
416                                 }
417                         }
418
419                         if (!$simulate) {
420                                 logger("Stored feed: ".print_r($item, true), LOGGER_DEBUG);
421
422                                 $notify = Item::isRemoteSelf($contact, $item);
423
424                                 // Distributed items should have a well formatted URI.
425                                 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
426                                 if ($notify) {
427                                         $item['guid'] = Item::guidFromUri($orig_plink, $a->get_hostname());
428                                         unset($item['uri']);
429                                         unset($item['parent-uri']);
430
431                                         // Set the delivery priority for "remote self" to "medium"
432                                         $notify = PRIORITY_MEDIUM;
433                                 }
434
435                                 $id = Item::insert($item, false, $notify);
436
437                                 logger("Feed for contact ".$contact["url"]." stored under id ".$id);
438                         } else {
439                                 $items[] = $item;
440                         }
441                         if ($simulate) {
442                                 break;
443                         }
444                 }
445
446                 if ($simulate) {
447                         return ["header" => $author, "items" => $items];
448                 }
449         }
450
451         private static function titleIsBody($title, $body)
452         {
453                 $title = strip_tags($title);
454                 $title = trim($title);
455                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
456                 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
457
458                 $body = strip_tags($body);
459                 $body = trim($body);
460                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
461                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
462
463                 if (strlen($title) < strlen($body)) {
464                         $body = substr($body, 0, strlen($title));
465                 }
466
467                 if (($title != $body) && (substr($title, -3) == "...")) {
468                         $pos = strrpos($title, "...");
469                         if ($pos > 0) {
470                                 $title = substr($title, 0, $pos);
471                                 $body = substr($body, 0, $pos);
472                         }
473                 }
474                 return ($title == $body);
475         }
476 }