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