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