]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
Merge pull request #8265 from nupplaphil/task/add_license
[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"] = 2;
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                 // Importing older entries first
236                 for ($i = $entries->length - 1; $i >= 0; --$i) {
237                         $entry = $entries->item($i);
238
239                         $item = array_merge($header, $author);
240
241                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
242                         if (!is_object($alternate)) {
243                                 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
244                         }
245                         if (is_object($alternate)) {
246                                 foreach ($alternate AS $attribute) {
247                                         if ($attribute->name == "href") {
248                                                 $item["plink"] = $attribute->textContent;
249                                         }
250                                 }
251                         }
252
253                         if (empty($item["plink"])) {
254                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
255                         }
256
257                         if (empty($item["plink"])) {
258                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
259                         }
260
261                         $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
262
263                         if (empty($item["uri"])) {
264                                 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
265                         }
266
267                         if (empty($item["uri"])) {
268                                 $item["uri"] = $item["plink"];
269                         }
270
271                         $orig_plink = $item["plink"];
272
273                         $item["plink"] = Network::finalUrl($item["plink"]);
274
275                         $item["parent-uri"] = $item["uri"];
276
277                         if (!$dryRun) {
278                                 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
279                                         $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
280                                 $previous = Item::selectFirst(['id'], $condition);
281                                 if (DBA::isResult($previous)) {
282                                         Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
283                                         continue;
284                                 }
285                         }
286
287                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
288
289                         if (empty($item["title"])) {
290                                 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
291                         }
292                         if (empty($item["title"])) {
293                                 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
294                         }
295
296                         $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
297
298                         $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
299
300                         if (empty($published)) {
301                                 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
302                         }
303
304                         if (empty($published)) {
305                                 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
306                         }
307
308                         $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
309
310                         if (empty($updated) && !empty($published)) {
311                                 $updated = $published;
312                         }
313
314                         if (empty($published) && !empty($updated)) {
315                                 $published = $updated;
316                         }
317
318                         if ($published != "") {
319                                 $item["created"] = $published;
320                         }
321
322                         if ($updated != "") {
323                                 $item["edited"] = $updated;
324                         }
325
326                         $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
327
328                         if (empty($creator)) {
329                                 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
330                         }
331
332                         if (empty($creator)) {
333                                 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
334                         }
335
336                         if ($creator != "") {
337                                 $item["author-name"] = $creator;
338                         }
339
340                         $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
341
342                         if ($creator != "") {
343                                 $item["author-name"] = $creator;
344                         }
345
346                         /// @TODO ?
347                         // <category>Ausland</category>
348                         // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
349
350                         $attachments = [];
351
352                         $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
353                         foreach ($enclosures AS $enclosure) {
354                                 $href = "";
355                                 $length = "";
356                                 $type = "";
357
358                                 foreach ($enclosure->attributes AS $attribute) {
359                                         if (in_array($attribute->name, ["url", "href"])) {
360                                                 $href = $attribute->textContent;
361                                         } elseif ($attribute->name == "length") {
362                                                 $length = $attribute->textContent;
363                                         } elseif ($attribute->name == "type") {
364                                                 $type = $attribute->textContent;
365                                         }
366                                 }
367
368                                 if (!empty($item["attach"])) {
369                                         $item["attach"] .= ',';
370                                 } else {
371                                         $item["attach"] = '';
372                                 }
373
374                                 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
375
376                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
377                         }
378
379                         $tags = '';
380                         $categories = $xpath->query("category", $entry);
381                         foreach ($categories AS $category) {
382                                 $hashtag = $category->nodeValue;
383                                 if ($tags != '') {
384                                         $tags .= ', ';
385                                 }
386
387                                 $taglink = "#[url=" . DI::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
388                                 $tags .= $taglink;
389                         }
390
391                         $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
392
393                         if (empty($body)) {
394                                 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
395                         }
396
397                         $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
398
399                         if (empty($summary)) {
400                                 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
401                         }
402
403                         if (empty($body)) {
404                                 $body = $summary;
405                                 $summary = '';
406                         }
407
408                         if ($body == $summary) {
409                                 $summary = '';
410                         }
411
412                         // remove the content of the title if it is identically to the body
413                         // This helps with auto generated titles e.g. from tumblr
414                         if (self::titleIsBody($item["title"], $body)) {
415                                 $item["title"] = "";
416                         }
417                         $item["body"] = HTML::toBBCode($body, $basepath);
418
419                         if (($item["body"] == '') && ($item["title"] != '')) {
420                                 $item["body"] = $item["title"];
421                                 $item["title"] = '';
422                         }
423
424                         $preview = '';
425                         if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
426                                 // Handle enclosures and treat them as preview picture
427                                 foreach ($attachments AS $attachment) {
428                                         if ($attachment["type"] == "image/jpeg") {
429                                                 $preview = $attachment["link"];
430                                         }
431                                 }
432
433                                 // Remove a possible link to the item itself
434                                 $item["body"] = str_replace($item["plink"], '', $item["body"]);
435                                 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
436
437                                 // Replace the content when the title is longer than the body
438                                 $replace = (strlen($item["title"]) > strlen($item["body"]));
439
440                                 // Replace it, when there is an image in the body
441                                 if (strstr($item["body"], '[/img]')) {
442                                         $replace = true;
443                                 }
444
445                                 // Replace it, when there is a link in the body
446                                 if (strstr($item["body"], '[/url]')) {
447                                         $replace = true;
448                                 }
449
450                                 if ($replace) {
451                                         $item["body"] = trim($item["title"]);
452                                 }
453
454                                 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
455                                 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
456                                         // When the fetched page info text is longer than the body, we do try to enhance the body
457                                         if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
458                                                 // The body is not part of the fetched page info title or page info text. So we add the text to the body
459                                                 $item['body'] .= "\n\n" . $data['text'];
460                                         } else {
461                                                 // Else we replace the body with the page info text
462                                                 $item['body'] = $data['text'];
463                                         }
464                                 }
465
466                                 // We always strip the title since it will be added in the page information
467                                 $item["title"] = "";
468                                 $item["body"] = $item["body"] . add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
469                                 $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]);
470                                 $item["object-type"] = Activity\ObjectType::BOOKMARK;
471                                 unset($item["attach"]);
472                         } else {
473                                 if (!empty($summary)) {
474                                         $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
475                                 }
476
477                                 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
478                                         if (!empty($tags)) {
479                                                 $item["tag"] = $tags;
480                                         } else {
481                                                 // @todo $preview is never set in this case, is it intended? - @MrPetovan 2018-02-13
482                                                 $item["tag"] = add_page_keywords($item["plink"], $preview, true, $contact["ffi_keyword_blacklist"]);
483                                         }
484                                         $item["body"] .= "\n" . $item['tag'];
485                                 }
486
487                                 // Add the link to the original feed entry if not present in feed
488                                 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
489                                         $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
490                                 }
491                         }
492
493                         if ($dryRun) {
494                                 $items[] = $item;
495                                 break;
496                         } else {
497                                 Logger::info("Stored feed: " . print_r($item, true));
498
499                                 $notify = Item::isRemoteSelf($contact, $item);
500
501                                 // Distributed items should have a well formatted URI.
502                                 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
503                                 if ($notify) {
504                                         $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
505                                         unset($item['uri']);
506                                         unset($item['parent-uri']);
507
508                                         // Set the delivery priority for "remote self" to "medium"
509                                         $notify = PRIORITY_MEDIUM;
510                                 }
511
512                                 $id = Item::insert($item, false, $notify);
513
514                                 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
515                         }
516                 }
517
518                 return ["header" => $author, "items" => $items];
519         }
520
521         private static function titleIsBody($title, $body)
522         {
523                 $title = strip_tags($title);
524                 $title = trim($title);
525                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
526                 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
527
528                 $body = strip_tags($body);
529                 $body = trim($body);
530                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
531                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
532
533                 if (strlen($title) < strlen($body)) {
534                         $body = substr($body, 0, strlen($title));
535                 }
536
537                 if (($title != $body) && (substr($title, -3) == "...")) {
538                         $pos = strrpos($title, "...");
539                         if ($pos > 0) {
540                                 $title = substr($title, 0, $pos);
541                                 $body = substr($body, 0, $pos);
542                         }
543                 }
544                 return ($title == $body);
545         }
546 }