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