]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
Merge pull request #8472 from annando/prevent-loop
[friendica.git] / src / Protocol / Feed.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Database\DBA;
30 use Friendica\DI;
31 use Friendica\Model\Item;
32 use Friendica\Util\Network;
33 use Friendica\Util\ParseUrl;
34 use Friendica\Util\XML;
35
36 /**
37  * This class contain functions to import feeds (RSS/RDF/Atom)
38  */
39 class Feed {
40         /**
41          * Read a RSS/RDF/Atom feed and create an item entry for it
42          *
43          * @param string $xml      The feed data
44          * @param array  $importer The user record of the importer
45          * @param array  $contact  The contact record of the feed
46          *
47          * @return array Returns the header and the first item in dry run mode
48          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
49          */
50         public static function import($xml, array $importer = [], array $contact = [])
51         {
52                 $dryRun = empty($importer) && empty($contact);
53
54                 if ($dryRun) {
55                         Logger::info("Test Atom/RSS feed");
56                 } else {
57                         Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
58                 }
59
60                 if (empty($xml)) {
61                         Logger::info('XML is empty.');
62                         return [];
63                 }
64
65                 if (!empty($contact['poll'])) {
66                         $basepath = $contact['poll'];
67                 } elseif (!empty($contact['url'])) {
68                         $basepath = $contact['url'];
69                 } else {
70                         $basepath = '';
71                 }
72
73                 $doc = new DOMDocument();
74                 @$doc->loadXML(trim($xml));
75                 $xpath = new DOMXPath($doc);
76                 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
77                 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
78                 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
79                 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
80                 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
81                 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
82                 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
83
84                 $author = [];
85                 $entries = null;
86
87                 // Is it RDF?
88                 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
89                         $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
90                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
91
92                         if (empty($author["author-name"])) {
93                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
94                         }
95                         $entries = $xpath->query('/rdf:RDF/rss:item');
96                 }
97
98                 // Is it Atom?
99                 if ($xpath->query('/atom:feed')->length > 0) {
100                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
101                         if (is_object($alternate)) {
102                                 foreach ($alternate AS $attribute) {
103                                         if ($attribute->name == "href") {
104                                                 $author["author-link"] = $attribute->textContent;
105                                         }
106                                 }
107                         }
108
109                         if (empty($author["author-link"])) {
110                                 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
111                                 if (is_object($self)) {
112                                         foreach ($self AS $attribute) {
113                                                 if ($attribute->name == "href") {
114                                                         $author["author-link"] = $attribute->textContent;
115                                                 }
116                                         }
117                                 }
118                         }
119
120                         if (empty($author["author-link"])) {
121                                 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
122                         }
123                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
124
125                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
126
127                         if (empty($author["author-name"])) {
128                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
129                         }
130
131                         if (empty($author["author-name"])) {
132                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
133                         }
134
135                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
136                         if ($value != "") {
137                                 $author["author-name"] = $value;
138                         }
139
140                         if ($dryRun) {
141                                 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
142
143                                 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
144                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
145                                 if ($value != "") {
146                                         $author["author-link"] = $value;
147                                 }
148
149                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
150                                 if ($value != "") {
151                                         $author["author-nick"] = $value;
152                                 }
153
154                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
155                                 if ($value != "") {
156                                         $author["author-location"] = $value;
157                                 }
158
159                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
160                                 if ($value != "") {
161                                         $author["author-about"] = $value;
162                                 }
163
164                                 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
165                                 if (is_object($avatar)) {
166                                         foreach ($avatar AS $attribute) {
167                                                 if ($attribute->name == "href") {
168                                                         $author["author-avatar"] = $attribute->textContent;
169                                                 }
170                                         }
171                                 }
172                         }
173
174                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
175
176                         $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
177
178                         $entries = $xpath->query('/atom:feed/atom:entry');
179                 }
180
181                 // Is it RSS?
182                 if ($xpath->query('/rss/channel')->length > 0) {
183                         $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
184
185                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
186                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
187
188                         if (empty($author["author-name"])) {
189                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
190                         }
191
192                         if (empty($author["author-name"])) {
193                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
194                         }
195
196                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
197
198                         $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
199
200                         $entries = $xpath->query('/rss/channel/item');
201                 }
202
203                 if (!$dryRun) {
204                         $author["author-link"] = $contact["url"];
205
206                         if (empty($author["author-name"])) {
207                                 $author["author-name"] = $contact["name"];
208                         }
209
210                         $author["author-avatar"] = $contact["thumb"];
211
212                         $author["owner-link"] = $contact["url"];
213                         $author["owner-name"] = $contact["name"];
214                         $author["owner-avatar"] = $contact["thumb"];
215                 }
216
217                 $header = [];
218                 $header["uid"] = $importer["uid"] ?? 0;
219                 $header["network"] = Protocol::FEED;
220                 $header["wall"] = 0;
221                 $header["origin"] = 0;
222                 $header["gravity"] = GRAVITY_PARENT;
223                 $header["private"] = Item::PUBLIC;
224                 $header["verb"] = Activity::POST;
225                 $header["object-type"] = Activity\ObjectType::NOTE;
226
227                 $header["contact-id"] = $contact["id"] ?? 0;
228
229                 if (!is_object($entries)) {
230                         Logger::info("There are no entries in this feed.");
231                         return [];
232                 }
233
234                 $items = [];
235
236                 // Limit the number of items that are about to be fetched
237                 $total_items = ($entries->length - 1);
238                 $max_items = DI::config()->get('system', 'max_feed_items');
239                 if (($max_items > 0) && ($total_items > $max_items)) {
240                         $total_items = $max_items;
241                 }
242
243                 // Importing older entries first
244                 for ($i = $total_items; $i >= 0; --$i) {
245                         $entry = $entries->item($i);
246
247                         $item = array_merge($header, $author);
248
249                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
250                         if (!is_object($alternate)) {
251                                 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
252                         }
253                         if (is_object($alternate)) {
254                                 foreach ($alternate AS $attribute) {
255                                         if ($attribute->name == "href") {
256                                                 $item["plink"] = $attribute->textContent;
257                                         }
258                                 }
259                         }
260
261                         if (empty($item["plink"])) {
262                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
263                         }
264
265                         if (empty($item["plink"])) {
266                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
267                         }
268
269                         $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
270
271                         if (empty($item["uri"])) {
272                                 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
273                         }
274
275                         if (empty($item["uri"])) {
276                                 $item["uri"] = $item["plink"];
277                         }
278
279                         $orig_plink = $item["plink"];
280
281                         $item["plink"] = Network::finalUrl($item["plink"]);
282
283                         $item["parent-uri"] = $item["uri"];
284
285                         if (!$dryRun) {
286                                 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
287                                         $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
288                                 $previous = Item::selectFirst(['id'], $condition);
289                                 if (DBA::isResult($previous)) {
290                                         Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
291                                         continue;
292                                 }
293                         }
294
295                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
296
297                         if (empty($item["title"])) {
298                                 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
299                         }
300                         if (empty($item["title"])) {
301                                 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
302                         }
303
304                         $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
305
306                         $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
307
308                         if (empty($published)) {
309                                 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
310                         }
311
312                         if (empty($published)) {
313                                 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
314                         }
315
316                         $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
317
318                         if (empty($updated) && !empty($published)) {
319                                 $updated = $published;
320                         }
321
322                         if (empty($published) && !empty($updated)) {
323                                 $published = $updated;
324                         }
325
326                         if ($published != "") {
327                                 $item["created"] = $published;
328                         }
329
330                         if ($updated != "") {
331                                 $item["edited"] = $updated;
332                         }
333
334                         $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
335
336                         if (empty($creator)) {
337                                 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
338                         }
339
340                         if (empty($creator)) {
341                                 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
342                         }
343
344                         if ($creator != "") {
345                                 $item["author-name"] = $creator;
346                         }
347
348                         $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
349
350                         if ($creator != "") {
351                                 $item["author-name"] = $creator;
352                         }
353
354                         /// @TODO ?
355                         // <category>Ausland</category>
356                         // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
357
358                         $attachments = [];
359
360                         $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
361                         foreach ($enclosures AS $enclosure) {
362                                 $href = "";
363                                 $length = "";
364                                 $type = "";
365
366                                 foreach ($enclosure->attributes AS $attribute) {
367                                         if (in_array($attribute->name, ["url", "href"])) {
368                                                 $href = $attribute->textContent;
369                                         } elseif ($attribute->name == "length") {
370                                                 $length = $attribute->textContent;
371                                         } elseif ($attribute->name == "type") {
372                                                 $type = $attribute->textContent;
373                                         }
374                                 }
375
376                                 if (!empty($item["attach"])) {
377                                         $item["attach"] .= ',';
378                                 } else {
379                                         $item["attach"] = '';
380                                 }
381
382                                 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
383
384                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
385                         }
386
387                         $tags = '';
388                         $categories = $xpath->query("category", $entry);
389                         foreach ($categories AS $category) {
390                                 $hashtag = $category->nodeValue;
391                                 if ($tags != '') {
392                                         $tags .= ', ';
393                                 }
394
395                                 $taglink = "#[url=" . DI::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
396                                 $tags .= $taglink;
397                         }
398
399                         $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
400
401                         if (empty($body)) {
402                                 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
403                         }
404
405                         $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
406
407                         if (empty($summary)) {
408                                 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
409                         }
410
411                         if (empty($body)) {
412                                 $body = $summary;
413                                 $summary = '';
414                         }
415
416                         if ($body == $summary) {
417                                 $summary = '';
418                         }
419
420                         // remove the content of the title if it is identically to the body
421                         // This helps with auto generated titles e.g. from tumblr
422                         if (self::titleIsBody($item["title"], $body)) {
423                                 $item["title"] = "";
424                         }
425                         $item["body"] = HTML::toBBCode($body, $basepath);
426
427                         if (($item["body"] == '') && ($item["title"] != '')) {
428                                 $item["body"] = $item["title"];
429                                 $item["title"] = '';
430                         }
431
432                         $preview = '';
433                         if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
434                                 // Handle enclosures and treat them as preview picture
435                                 foreach ($attachments AS $attachment) {
436                                         if ($attachment["type"] == "image/jpeg") {
437                                                 $preview = $attachment["link"];
438                                         }
439                                 }
440
441                                 // Remove a possible link to the item itself
442                                 $item["body"] = str_replace($item["plink"], '', $item["body"]);
443                                 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
444
445                                 // Replace the content when the title is longer than the body
446                                 $replace = (strlen($item["title"]) > strlen($item["body"]));
447
448                                 // Replace it, when there is an image in the body
449                                 if (strstr($item["body"], '[/img]')) {
450                                         $replace = true;
451                                 }
452
453                                 // Replace it, when there is a link in the body
454                                 if (strstr($item["body"], '[/url]')) {
455                                         $replace = true;
456                                 }
457
458                                 if ($replace) {
459                                         $item["body"] = trim($item["title"]);
460                                 }
461
462                                 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
463                                 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
464                                         // When the fetched page info text is longer than the body, we do try to enhance the body
465                                         if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
466                                                 // The body is not part of the fetched page info title or page info text. So we add the text to the body
467                                                 $item['body'] .= "\n\n" . $data['text'];
468                                         } else {
469                                                 // Else we replace the body with the page info text
470                                                 $item['body'] = $data['text'];
471                                         }
472                                 }
473
474                                 // We always strip the title since it will be added in the page information
475                                 $item["title"] = "";
476                                 $item["body"] = $item["body"] . add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
477                                 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
478                                 $item["object-type"] = Activity\ObjectType::BOOKMARK;
479                                 unset($item["attach"]);
480                         } else {
481                                 if (!empty($summary)) {
482                                         $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
483                                 }
484
485                                 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
486                                         if (!empty($tags)) {
487                                                 $item["tag"] = $tags;
488                                         } else {
489                                                 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
490                                                 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
491                                         }
492                                         $item["body"] .= "\n" . $item['tag'];
493                                 }
494
495                                 // Add the link to the original feed entry if not present in feed
496                                 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
497                                         $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
498                                 }
499                         }
500
501                         if ($dryRun) {
502                                 $items[] = $item;
503                                 break;
504                         } else {
505                                 Logger::info("Stored feed: " . print_r($item, true));
506
507                                 $notify = Item::isRemoteSelf($contact, $item);
508
509                                 // Distributed items should have a well formatted URI.
510                                 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
511                                 if ($notify) {
512                                         $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
513                                         unset($item['uri']);
514                                         unset($item['parent-uri']);
515
516                                         // Set the delivery priority for "remote self" to "medium"
517                                         $notify = PRIORITY_MEDIUM;
518                                 }
519
520                                 $id = Item::insert($item, false, $notify);
521
522                                 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
523                         }
524                 }
525
526                 return ["header" => $author, "items" => $items];
527         }
528
529         private static function titleIsBody($title, $body)
530         {
531                 $title = strip_tags($title);
532                 $title = trim($title);
533                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
534                 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
535
536                 $body = strip_tags($body);
537                 $body = trim($body);
538                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
539                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
540
541                 if (strlen($title) < strlen($body)) {
542                         $body = substr($body, 0, strlen($title));
543                 }
544
545                 if (($title != $body) && (substr($title, -3) == "...")) {
546                         $pos = strrpos($title, "...");
547                         if ($pos > 0) {
548                                 $title = substr($title, 0, $pos);
549                                 $body = substr($body, 0, $pos);
550                         }
551                 }
552                 return ($title == $body);
553         }
554 }