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