]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
Merge pull request #8631 from MrPetovan/task/remove-item-tag-field
[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                         $taglist = [];
389                         $categories = $xpath->query("category", $entry);
390                         foreach ($categories AS $category) {
391                                 $taglist[] = $category->nodeValue;
392                         }
393
394                         $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
395
396                         if (empty($body)) {
397                                 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
398                         }
399
400                         $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
401
402                         if (empty($summary)) {
403                                 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
404                         }
405
406                         if (empty($body)) {
407                                 $body = $summary;
408                                 $summary = '';
409                         }
410
411                         if ($body == $summary) {
412                                 $summary = '';
413                         }
414
415                         // remove the content of the title if it is identically to the body
416                         // This helps with auto generated titles e.g. from tumblr
417                         if (self::titleIsBody($item["title"], $body)) {
418                                 $item["title"] = "";
419                         }
420                         $item["body"] = HTML::toBBCode($body, $basepath);
421
422                         if (($item["body"] == '') && ($item["title"] != '')) {
423                                 $item["body"] = $item["title"];
424                                 $item["title"] = '';
425                         }
426
427                         $preview = '';
428                         if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
429                                 // Handle enclosures and treat them as preview picture
430                                 foreach ($attachments AS $attachment) {
431                                         if ($attachment["type"] == "image/jpeg") {
432                                                 $preview = $attachment["link"];
433                                         }
434                                 }
435
436                                 // Remove a possible link to the item itself
437                                 $item["body"] = str_replace($item["plink"], '', $item["body"]);
438                                 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
439
440                                 // Replace the content when the title is longer than the body
441                                 $replace = (strlen($item["title"]) > strlen($item["body"]));
442
443                                 // Replace it, when there is an image in the body
444                                 if (strstr($item["body"], '[/img]')) {
445                                         $replace = true;
446                                 }
447
448                                 // Replace it, when there is a link in the body
449                                 if (strstr($item["body"], '[/url]')) {
450                                         $replace = true;
451                                 }
452
453                                 if ($replace) {
454                                         $item["body"] = trim($item["title"]);
455                                 }
456
457                                 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
458                                 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
459                                         // When the fetched page info text is longer than the body, we do try to enhance the body
460                                         if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
461                                                 // The body is not part of the fetched page info title or page info text. So we add the text to the body
462                                                 $item['body'] .= "\n\n" . $data['text'];
463                                         } else {
464                                                 // Else we replace the body with the page info text
465                                                 $item['body'] = $data['text'];
466                                         }
467                                 }
468
469                                 // We always strip the title since it will be added in the page information
470                                 $item["title"] = "";
471                                 $item["body"] = $item["body"] . add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
472                                 $taglist = get_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
473                                 $item["object-type"] = Activity\ObjectType::BOOKMARK;
474                                 unset($item["attach"]);
475                         } else {
476                                 if (!empty($summary)) {
477                                         $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
478                                 }
479
480                                 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
481                                         if (empty($taglist)) {
482                                                 $taglist = get_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
483                                         }
484                                         $item["body"] .= "\n" . self::tagToString($taglist);
485                                 } else {
486                                         $taglist = [];
487                                 }
488
489                                 // Add the link to the original feed entry if not present in feed
490                                 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
491                                         $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
492                                 }
493                         }
494
495                         if ($dryRun) {
496                                 $items[] = $item;
497                                 break;
498                         } else {
499                                 Logger::info("Stored feed: " . print_r($item, true));
500
501                                 $notify = Item::isRemoteSelf($contact, $item);
502
503                                 // Distributed items should have a well formatted URI.
504                                 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
505                                 if ($notify) {
506                                         $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
507                                         unset($item['uri']);
508                                         unset($item['parent-uri']);
509
510                                         // Set the delivery priority for "remote self" to "medium"
511                                         $notify = PRIORITY_MEDIUM;
512                                 }
513
514                                 $id = Item::insert($item, $notify);
515
516                                 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
517
518                                 if (!empty($id) && !empty($taglist)) {
519                                         $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
520                                         foreach ($taglist as $tag) {
521                                                 Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
522                                         }                                       
523                                 }
524                         }
525                 }
526
527                 return ["header" => $author, "items" => $items];
528         }
529
530         /**
531          * Convert a tag array to a tag string
532          *
533          * @param array $tags
534          * @return string tag string
535          */
536         private static function tagToString(array $tags)
537         {
538                 $tagstr = '';
539
540                 foreach ($tags as $tag) {
541                         if ($tagstr != "") {
542                                 $tagstr .= ", ";
543                         }
544         
545                         $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
546                 }
547
548                 return $tagstr;
549         }
550
551         private static function titleIsBody($title, $body)
552         {
553                 $title = strip_tags($title);
554                 $title = trim($title);
555                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
556                 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
557
558                 $body = strip_tags($body);
559                 $body = trim($body);
560                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
561                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
562
563                 if (strlen($title) < strlen($body)) {
564                         $body = substr($body, 0, strlen($title));
565                 }
566
567                 if (($title != $body) && (substr($title, -3) == "...")) {
568                         $pos = strrpos($title, "...");
569                         if ($pos > 0) {
570                                 $title = substr($title, 0, $pos);
571                                 $body = substr($body, 0, $pos);
572                         }
573                 }
574                 return ($title == $body);
575         }
576 }