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