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