Adding a line feed looks nicer
[friendica.git/.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\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;
19
20 /**
21  * @brief This class contain functions to import feeds
22  *
23  */
24 class Feed {
25         /**
26          * @brief Read a RSS/RDF/Atom feed and create an item entry for it
27          *
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
33          *
34          * @return array In simulation mode it returns the header and the first item
35          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
36          */
37         public static function import($xml, $importer, &$contact, &$hub, $simulate = false) {
38
39                 $a = \get_app();
40
41                 if (!$simulate) {
42                         Logger::log("Import Atom/RSS feed '".$contact["name"]."' (Contact ".$contact["id"].") for user ".$importer["uid"], Logger::DEBUG);
43                 } else {
44                         Logger::log("Test Atom/RSS feed", Logger::DEBUG);
45                 }
46                 if (empty($xml)) {
47                         Logger::log('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:id/text()');
125
126                                 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
127                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
128                                 if ($value != "") {
129                                         $author["author-link"] = $value;
130                                 }
131
132                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
133                                 if ($value != "") {
134                                         $author["author-nick"] = $value;
135                                 }
136                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
137                                 if ($value != "") {
138                                         $author["author-location"] = $value;
139                                 }
140                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
141                                 if ($value != "") {
142                                         $author["author-about"] = $value;
143                                 }
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;
149                                                 }
150                                         }
151                                 }
152                         }
153
154                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
155
156                         $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
157
158                         $entries = $xpath->query('/atom:feed/atom:entry');
159                 }
160
161                 // Is it RSS?
162                 if ($xpath->query('/rss/channel')->length > 0) {
163                         $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
164
165                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
166                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
167
168                         if (empty($author["author-name"])) {
169                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
170                         }
171                         if (empty($author["author-name"])) {
172                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
173                         }
174                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
175
176                         $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
177
178                         $entries = $xpath->query('/rss/channel/item');
179                 }
180
181                 if (!$simulate) {
182                         $author["author-link"] = $contact["url"];
183
184                         if (empty($author["author-name"])) {
185                                 $author["author-name"] = $contact["name"];
186                         }
187                         $author["author-avatar"] = $contact["thumb"];
188
189                         $author["owner-link"] = $contact["url"];
190                         $author["owner-name"] = $contact["name"];
191                         $author["owner-avatar"] = $contact["thumb"];
192                 }
193
194                 $header = [];
195                 $header["uid"] = $importer["uid"];
196                 $header["network"] = Protocol::FEED;
197                 $header["wall"] = 0;
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;
203
204                 $header["contact-id"] = $contact["id"];
205
206                 if (!is_object($entries)) {
207                         Logger::log("There are no entries in this feed.", Logger::DEBUG);
208                         return;
209                 }
210
211                 $items = [];
212                 // Importing older entries first
213                 for($i = $entries->length - 1; $i >= 0;--$i) {
214                         $entry = $entries->item($i);
215
216                         $item = array_merge($header, $author);
217
218                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
219                         if (!is_object($alternate)) {
220                                 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
221                         }
222                         if (is_object($alternate)) {
223                                 foreach ($alternate AS $attribute) {
224                                         if ($attribute->name == "href") {
225                                                 $item["plink"] = $attribute->textContent;
226                                         }
227                                 }
228                         }
229                         if (empty($item["plink"])) {
230                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
231                         }
232                         if (empty($item["plink"])) {
233                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
234                         }
235
236                         $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
237
238                         if (empty($item["uri"])) {
239                                 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
240                         }
241                         if (empty($item["uri"])) {
242                                 $item["uri"] = $item["plink"];
243                         }
244
245                         $orig_plink = $item["plink"];
246
247                         $item["plink"] = Network::finalUrl($item["plink"]);
248
249                         $item["parent-uri"] = $item["uri"];
250
251                         if (!$simulate) {
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);
257                                         continue;
258                                 }
259                         }
260
261                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
262
263                         if (empty($item["title"])) {
264                                 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
265                         }
266                         if (empty($item["title"])) {
267                                 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
268                         }
269                         $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
270
271                         if (empty($published)) {
272                                 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
273                         }
274                         if (empty($published)) {
275                                 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
276                         }
277                         $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
278
279                         if (empty($updated) && !empty($published)) {
280                                 $updated = $published;
281                         }
282
283                         if (empty($published) && !empty($updated)) {
284                                 $published = $updated;
285                         }
286
287                         if ($published != "") {
288                                 $item["created"] = $published;
289                         }
290                         if ($updated != "") {
291                                 $item["edited"] = $updated;
292                         }
293                         $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
294
295                         if (empty($creator)) {
296                                 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
297                         }
298                         if (empty($creator)) {
299                                 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
300                         }
301                         if ($creator != "") {
302                                 $item["author-name"] = $creator;
303                         }
304                         $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
305
306                         if ($creator != "") {
307                                 $item["author-name"] = $creator;
308                         }
309
310                         /// @TODO ?
311                         // <category>Ausland</category>
312                         // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
313
314                         $attachments = [];
315
316                         $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
317                         foreach ($enclosures AS $enclosure) {
318                                 $href = "";
319                                 $length = "";
320                                 $type = "";
321
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;
329                                         }
330                                 }
331                                 if (!empty($item["attach"])) {
332                                         $item["attach"] .= ',';
333                                 } else {
334                                         $item["attach"] = '';
335                                 }
336
337                                 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
338
339                                 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'"[/attach]';
340                         }
341
342                         $tags = '';
343                         $categories = $xpath->query("category", $entry);
344                         foreach ($categories AS $category) {
345                                 $hashtag = $category->nodeValue;
346                                 if ($tags != '') {
347                                         $tags .= ', ';
348                                 }
349
350                                 $taglink = "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
351                                 $tags .= $taglink;
352                         }
353
354                         $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
355
356                         if (empty($body)) {
357                                 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
358                         }
359
360                         $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
361
362                         if (empty($summary)) {
363                                 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
364                         }
365
366                         if (empty($body)) {
367                                 $body = $summary;
368                                 $summary = '';
369                         }
370
371                         if ($body == $summary) {
372                                 $summary = '';
373                         }
374
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)) {
378                                 $item["title"] = "";
379                         }
380                         $item["body"] = HTML::toBBCode($body, $basepath);
381
382                         if (($item["body"] == '') && ($item["title"] != '')) {
383                                 $item["body"] = $item["title"];
384                                 $item["title"] = '';
385                         }
386
387                         $preview = '';
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"];
393                                         }
394                                 }
395
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"]);
399
400                                 // Replace the content when the title is longer than the body
401                                 $replace = (strlen($item["title"]) > strlen($item["body"]));
402
403                                 // Replace it, when there is an image in the body
404                                 if (strstr($item["body"], '[/img]')) {
405                                         $replace = true;
406                                 }
407
408                                 // Replace it, when there is a link in the body
409                                 if (strstr($item["body"], '[/url]')) {
410                                         $replace = true;
411                                 }
412
413                                 if ($replace) {
414                                         $item["body"] = $item["title"];
415                                 }
416                                 // We always strip the title since it will be added in the page information
417                                 $item["title"] = "";
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"]);
422                         } else {
423                                 if (!empty($summary)) {
424                                         $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
425                                 }
426
427                                 if ($contact["fetch_further_information"] == 3) {
428                                         if (!empty($tags)) {
429                                                 $item["tag"] = $tags;
430                                         } else {
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"]);
433                                         }
434                                         $item["body"] .= "\n".$item['tag'];
435                                 }
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]";
439                                 }
440                         }
441
442                         if (!$simulate) {
443                                 Logger::log("Stored feed: ".print_r($item, true), Logger::DEBUG);
444
445                                 $notify = Item::isRemoteSelf($contact, $item);
446
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.
449                                 if ($notify) {
450                                         $item['guid'] = Item::guidFromUri($orig_plink, $a->getHostName());
451                                         unset($item['uri']);
452                                         unset($item['parent-uri']);
453
454                                         // Set the delivery priority for "remote self" to "medium"
455                                         $notify = PRIORITY_MEDIUM;
456                                 }
457
458                                 $id = Item::insert($item, false, $notify);
459
460                                 Logger::log("Feed for contact ".$contact["url"]." stored under id ".$id);
461                         } else {
462                                 $items[] = $item;
463                         }
464                         if ($simulate) {
465                                 break;
466                         }
467                 }
468
469                 if ($simulate) {
470                         return ["header" => $author, "items" => $items];
471                 }
472         }
473
474         private static function titleIsBody($title, $body)
475         {
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);
480
481                 $body = strip_tags($body);
482                 $body = trim($body);
483                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
484                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
485
486                 if (strlen($title) < strlen($body)) {
487                         $body = substr($body, 0, strlen($title));
488                 }
489
490                 if (($title != $body) && (substr($title, -3) == "...")) {
491                         $pos = strrpos($title, "...");
492                         if ($pos > 0) {
493                                 $title = substr($title, 0, $pos);
494                                 $body = substr($body, 0, $pos);
495                         }
496                 }
497                 return ($title == $body);
498         }
499 }