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