Merge pull request #6315 from MrPetovan/bug/6309-add-fulltext-index-profile
[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          */
36         public static function import($xml, $importer, &$contact, &$hub, $simulate = false) {
37
38                 $a = get_app();
39
40                 if (!$simulate) {
41                         Logger::log("Import Atom/RSS feed '".$contact["name"]."' (Contact ".$contact["id"].") for user ".$importer["uid"], Logger::DEBUG);
42                 } else {
43                         Logger::log("Test Atom/RSS feed", Logger::DEBUG);
44                 }
45                 if (empty($xml)) {
46                         Logger::log('XML is empty.', Logger::DEBUG);
47                         return;
48                 }
49
50                 if (!empty($contact['poll'])) {
51                         $basepath = $contact['poll'];
52                 } elseif (!empty($contact['url'])) {
53                         $basepath = $contact['url'];
54                 } else {
55                         $basepath = '';
56                 }
57
58                 $doc = new DOMDocument();
59                 @$doc->loadXML(trim($xml));
60                 $xpath = new DOMXPath($doc);
61                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
62                 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
63                 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
64                 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
65                 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
66                 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
67                 $xpath->registerNamespace('poco', NAMESPACE_POCO);
68
69                 $author = [];
70                 $entries = null;
71
72                 // Is it RDF?
73                 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
74                         $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
75                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
76
77                         if (empty($author["author-name"])) {
78                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
79                         }
80                         $entries = $xpath->query('/rdf:RDF/rss:item');
81                 }
82
83                 // Is it Atom?
84                 if ($xpath->query('/atom:feed')->length > 0) {
85                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
86                         if (is_object($alternate)) {
87                                 foreach ($alternate AS $attribute) {
88                                         if ($attribute->name == "href") {
89                                                 $author["author-link"] = $attribute->textContent;
90                                         }
91                                 }
92                         }
93
94                         if (empty($author["author-link"])) {
95                                 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
96                                 if (is_object($self)) {
97                                         foreach ($self AS $attribute) {
98                                                 if ($attribute->name == "href") {
99                                                         $author["author-link"] = $attribute->textContent;
100                                                 }
101                                         }
102                                 }
103                         }
104
105                         if (empty($author["author-link"])) {
106                                 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
107                         }
108                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
109
110                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
111
112                         if (empty($author["author-name"])) {
113                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
114                         }
115                         if (empty($author["author-name"])) {
116                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
117                         }
118                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
119                         if ($value != "") {
120                                 $author["author-name"] = $value;
121                         }
122                         if ($simulate) {
123                                 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
124
125                                 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
126                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
127                                 if ($value != "") {
128                                         $author["author-link"] = $value;
129                                 }
130
131                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
132                                 if ($value != "") {
133                                         $author["author-nick"] = $value;
134                                 }
135                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
136                                 if ($value != "") {
137                                         $author["author-location"] = $value;
138                                 }
139                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
140                                 if ($value != "") {
141                                         $author["author-about"] = $value;
142                                 }
143                                 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
144                                 if (is_object($avatar)) {
145                                         foreach ($avatar AS $attribute) {
146                                                 if ($attribute->name == "href") {
147                                                         $author["author-avatar"] = $attribute->textContent;
148                                                 }
149                                         }
150                                 }
151                         }
152
153                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
154
155                         $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
156
157                         $entries = $xpath->query('/atom:feed/atom:entry');
158                 }
159
160                 // Is it RSS?
161                 if ($xpath->query('/rss/channel')->length > 0) {
162                         $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
163
164                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
165                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
166
167                         if (empty($author["author-name"])) {
168                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
169                         }
170                         if (empty($author["author-name"])) {
171                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
172                         }
173                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
174
175                         $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
176
177                         $entries = $xpath->query('/rss/channel/item');
178                 }
179
180                 if (!$simulate) {
181                         $author["author-link"] = $contact["url"];
182
183                         if (empty($author["author-name"])) {
184                                 $author["author-name"] = $contact["name"];
185                         }
186                         $author["author-avatar"] = $contact["thumb"];
187
188                         $author["owner-link"] = $contact["url"];
189                         $author["owner-name"] = $contact["name"];
190                         $author["owner-avatar"] = $contact["thumb"];
191                 }
192
193                 $header = [];
194                 $header["uid"] = $importer["uid"];
195                 $header["network"] = Protocol::FEED;
196                 $header["wall"] = 0;
197                 $header["origin"] = 0;
198                 $header["gravity"] = GRAVITY_PARENT;
199                 $header["private"] = 2;
200                 $header["verb"] = ACTIVITY_POST;
201                 $header["object-type"] = ACTIVITY_OBJ_NOTE;
202
203                 $header["contact-id"] = $contact["id"];
204
205                 if (!is_object($entries)) {
206                         Logger::log("There are no entries in this feed.", Logger::DEBUG);
207                         return;
208                 }
209
210                 $items = [];
211                 // Importing older entries first
212                 for($i = $entries->length - 1; $i >= 0;--$i) {
213                         $entry = $entries->item($i);
214
215                         $item = array_merge($header, $author);
216
217                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
218                         if (!is_object($alternate)) {
219                                 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
220                         }
221                         if (is_object($alternate)) {
222                                 foreach ($alternate AS $attribute) {
223                                         if ($attribute->name == "href") {
224                                                 $item["plink"] = $attribute->textContent;
225                                         }
226                                 }
227                         }
228                         if (empty($item["plink"])) {
229                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
230                         }
231                         if (empty($item["plink"])) {
232                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
233                         }
234
235                         $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
236
237                         if (empty($item["uri"])) {
238                                 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
239                         }
240                         if (empty($item["uri"])) {
241                                 $item["uri"] = $item["plink"];
242                         }
243
244                         $orig_plink = $item["plink"];
245
246                         $item["plink"] = Network::finalUrl($item["plink"]);
247
248                         $item["parent-uri"] = $item["uri"];
249
250                         if (!$simulate) {
251                                 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
252                                         $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
253                                 $previous = Item::selectFirst(['id'], $condition);
254                                 if (DBA::isResult($previous)) {
255                                         Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$previous["id"], Logger::DEBUG);
256                                         continue;
257                                 }
258                         }
259
260                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
261
262                         if (empty($item["title"])) {
263                                 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
264                         }
265                         if (empty($item["title"])) {
266                                 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
267                         }
268                         $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
269
270                         if (empty($published)) {
271                                 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
272                         }
273                         if (empty($published)) {
274                                 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
275                         }
276                         $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
277
278                         if (empty($updated) && !empty($published)) {
279                                 $updated = $published;
280                         }
281
282                         if (empty($published) && !empty($updated)) {
283                                 $published = $updated;
284                         }
285
286                         if ($published != "") {
287                                 $item["created"] = $published;
288                         }
289                         if ($updated != "") {
290                                 $item["edited"] = $updated;
291                         }
292                         $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
293
294                         if (empty($creator)) {
295                                 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
296                         }
297                         if (empty($creator)) {
298                                 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
299                         }
300                         if ($creator != "") {
301                                 $item["author-name"] = $creator;
302                         }
303                         $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
304
305                         if ($creator != "") {
306                                 $item["author-name"] = $creator;
307                         }
308
309                         /// @TODO ?
310                         // <category>Ausland</category>
311                         // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
312
313                         $attachments = [];
314
315                         $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
316                         foreach ($enclosures AS $enclosure) {
317                                 $href = "";
318                                 $length = "";
319                                 $type = "";
320                                 $title = "";
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                         if (empty($body)) {
360                                 $body = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
361                         }
362                         if (empty($body)) {
363                                 $body = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
364                         }
365
366                         // remove the content of the title if it is identically to the body
367                         // This helps with auto generated titles e.g. from tumblr
368                         if (self::titleIsBody($item["title"], $body)) {
369                                 $item["title"] = "";
370                         }
371                         $item["body"] = HTML::toBBCode($body, $basepath);
372
373                         if (($item["body"] == '') && ($item["title"] != '')) {
374                                 $item["body"] = $item["title"];
375                                 $item["title"] = '';
376                         }
377
378                         $preview = '';
379                         if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
380                                 // Handle enclosures and treat them as preview picture
381                                 foreach ($attachments AS $attachment) {
382                                         if ($attachment["type"] == "image/jpeg") {
383                                                 $preview = $attachment["link"];
384                                         }
385                                 }
386
387                                 // Remove a possible link to the item itself
388                                 $item["body"] = str_replace($item["plink"], '', $item["body"]);
389                                 $item["body"] = preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]);
390
391                                 // Replace the content when the title is longer than the body
392                                 $replace = (strlen($item["title"]) > strlen($item["body"]));
393
394                                 // Replace it, when there is an image in the body
395                                 if (strstr($item["body"], '[/img]')) {
396                                         $replace = true;
397                                 }
398
399                                 // Replace it, when there is a link in the body
400                                 if (strstr($item["body"], '[/url]')) {
401                                         $replace = true;
402                                 }
403
404                                 if ($replace) {
405                                         $item["body"] = $item["title"];
406                                 }
407                                 // We always strip the title since it will be added in the page information
408                                 $item["title"] = "";
409                                 $item["body"] = $item["body"].add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
410                                 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
411                                 $item["object-type"] = ACTIVITY_OBJ_BOOKMARK;
412                                 unset($item["attach"]);
413                         } else {
414                                 if ($contact["fetch_further_information"] == 3) {
415                                         if (!empty($tags)) {
416                                                 $item["tag"] = $tags;
417                                         } else {
418                                                 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
419                                                 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
420                                         }
421                                         $item["body"] .= "\n".$item['tag'];
422                                 }
423                                 // Add the link to the original feed entry if not present in feed
424                                 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
425                                         $item["body"] .= "[hr][url]".$item['plink']."[/url]";
426                                 }
427                         }
428
429                         if (!$simulate) {
430                                 Logger::log("Stored feed: ".print_r($item, true), Logger::DEBUG);
431
432                                 $notify = Item::isRemoteSelf($contact, $item);
433
434                                 // Distributed items should have a well formatted URI.
435                                 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
436                                 if ($notify) {
437                                         $item['guid'] = Item::guidFromUri($orig_plink, $a->getHostName());
438                                         unset($item['uri']);
439                                         unset($item['parent-uri']);
440
441                                         // Set the delivery priority for "remote self" to "medium"
442                                         $notify = PRIORITY_MEDIUM;
443                                 }
444
445                                 $id = Item::insert($item, false, $notify);
446
447                                 Logger::log("Feed for contact ".$contact["url"]." stored under id ".$id);
448                         } else {
449                                 $items[] = $item;
450                         }
451                         if ($simulate) {
452                                 break;
453                         }
454                 }
455
456                 if ($simulate) {
457                         return ["header" => $author, "items" => $items];
458                 }
459         }
460
461         private static function titleIsBody($title, $body)
462         {
463                 $title = strip_tags($title);
464                 $title = trim($title);
465                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
466                 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
467
468                 $body = strip_tags($body);
469                 $body = trim($body);
470                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
471                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
472
473                 if (strlen($title) < strlen($body)) {
474                         $body = substr($body, 0, strlen($title));
475                 }
476
477                 if (($title != $body) && (substr($title, -3) == "...")) {
478                         $pos = strrpos($title, "...");
479                         if ($pos > 0) {
480                                 $title = substr($title, 0, $pos);
481                                 $body = substr($body, 0, $pos);
482                         }
483                 }
484                 return ($title == $body);
485         }
486 }