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