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