]> git.mxchange.org Git - friendica.git/blob - Feed.php
c129c31b013a26a6727c6db8f65ba6b14aa16b7c
[friendica.git] / 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 dba;
13 use DOMDocument;
14 use DOMXPath;
15
16 require_once 'include/dba.php';
17 require_once 'include/html2bbcode.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
71                 // Is it RDF?
72                 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
73                         $author["author-link"] = $xpath->evaluate('/rdf:RDF/rss:channel/rss:link/text()')->item(0)->nodeValue;
74                         $author["author-name"] = $xpath->evaluate('/rdf:RDF/rss:channel/rss:title/text()')->item(0)->nodeValue;
75
76                         if ($author["author-name"] == "") {
77                                 $author["author-name"] = $xpath->evaluate('/rdf:RDF/rss:channel/rss:description/text()')->item(0)->nodeValue;
78                         }
79                         $entries = $xpath->query('/rdf:RDF/rss:item');
80                 }
81
82                 // Is it Atom?
83                 if ($xpath->query('/atom:feed')->length > 0) {
84                         $alternate = $xpath->query("atom:link[@rel='alternate']")->item(0)->attributes;
85                         if (is_object($alternate)) {
86                                 foreach ($alternate AS $attributes) {
87                                         if ($attributes->name == "href") {
88                                                 $author["author-link"] = $attributes->textContent;
89                                         }
90                                 }
91                         }
92
93                         if ($author["author-link"] == "") {
94                                 $author["author-link"] = $author["author-id"];
95                         }
96                         if ($author["author-link"] == "") {
97                                 $self = $xpath->query("atom:link[@rel='self']")->item(0)->attributes;
98                                 if (is_object($self)) {
99                                         foreach ($self AS $attributes) {
100                                                 if ($attributes->name == "href") {
101                                                         $author["author-link"] = $attributes->textContent;
102                                                 }
103                                         }
104                                 }
105                         }
106
107                         if ($author["author-link"] == "") {
108                                 $author["author-link"] = $xpath->evaluate('/atom:feed/atom:id/text()')->item(0)->nodeValue;
109                         }
110                         $author["author-avatar"] = $xpath->evaluate('/atom:feed/atom:logo/text()')->item(0)->nodeValue;
111
112                         $author["author-name"] = $xpath->evaluate('/atom:feed/atom:title/text()')->item(0)->nodeValue;
113
114                         if ($author["author-name"] == "") {
115                                 $author["author-name"] = $xpath->evaluate('/atom:feed/atom:subtitle/text()')->item(0)->nodeValue;
116                         }
117                         if ($author["author-name"] == "") {
118                                 $author["author-name"] = $xpath->evaluate('/atom:feed/atom:author/atom:name/text()')->item(0)->nodeValue;
119                         }
120                         $value = $xpath->evaluate('atom:author/poco:displayName/text()')->item(0)->nodeValue;
121                         if ($value != "") {
122                                 $author["author-name"] = $value;
123                         }
124                         if ($simulate) {
125                                 $author["author-id"] = $xpath->evaluate('/atom:feed/atom:author/atom:uri/text()')->item(0)->nodeValue;
126
127                                 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()')->item(0)->nodeValue;
128                                 if ($value != "") {
129                                         $author["author-nick"] = $value;
130                                 }
131                                 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()')->item(0)->nodeValue;
132                                 if ($value != "") {
133                                         $author["author-location"] = $value;
134                                 }
135                                 $value = $xpath->evaluate('atom:author/poco:note/text()')->item(0)->nodeValue;
136                                 if ($value != "") {
137                                         $author["author-about"] = $value;
138                                 }
139                                 $avatar = $xpath->evaluate("atom:author/atom:link[@rel='avatar']")->item(0)->attributes;
140                                 if (is_object($avatar)) {
141                                         foreach ($avatar AS $attributes) {
142                                                 if ($attributes->name == "href") {
143                                                         $author["author-avatar"] = $attributes->textContent;
144                                                 }
145                                         }
146                                 }
147                         }
148
149                         $author["edited"] = $author["created"] = $xpath->query('/atom:feed/atom:updated/text()')->item(0)->nodeValue;
150
151                         $author["app"] = $xpath->evaluate('/atom:feed/atom:generator/text()')->item(0)->nodeValue;
152
153                         $entries = $xpath->query('/atom:feed/atom:entry');
154                 }
155
156                 // Is it RSS?
157                 if ($xpath->query('/rss/channel')->length > 0) {
158                         $author["author-link"] = $xpath->evaluate('/rss/channel/link/text()')->item(0)->nodeValue;
159
160                         $author["author-name"] = $xpath->evaluate('/rss/channel/title/text()')->item(0)->nodeValue;
161                         $author["author-avatar"] = $xpath->evaluate('/rss/channel/image/url/text()')->item(0)->nodeValue;
162
163                         if ($author["author-name"] == "") {
164                                 $author["author-name"] = $xpath->evaluate('/rss/channel/copyright/text()')->item(0)->nodeValue;
165                         }
166                         if ($author["author-name"] == "") {
167                                 $author["author-name"] = $xpath->evaluate('/rss/channel/description/text()')->item(0)->nodeValue;
168                         }
169                         $author["edited"] = $author["created"] = $xpath->query('/rss/channel/pubDate/text()')->item(0)->nodeValue;
170
171                         $author["app"] = $xpath->evaluate('/rss/channel/generator/text()')->item(0)->nodeValue;
172
173                         $entries = $xpath->query('/rss/channel/item');
174                 }
175
176                 if (!$simulate) {
177                         $author["author-link"] = $contact["url"];
178
179                         if ($author["author-name"] == "") {
180                                 $author["author-name"] = $contact["name"];
181                         }
182                         $author["author-avatar"] = $contact["thumb"];
183
184                         $author["owner-link"] = $contact["url"];
185                         $author["owner-name"] = $contact["name"];
186                         $author["owner-avatar"] = $contact["thumb"];
187                 }
188
189                 $header = [];
190                 $header["uid"] = $importer["uid"];
191                 $header["network"] = NETWORK_FEED;
192                 $header["type"] = "remote";
193                 $header["wall"] = 0;
194                 $header["origin"] = 0;
195                 $header["gravity"] = GRAVITY_PARENT;
196                 $header["private"] = 2;
197                 $header["verb"] = ACTIVITY_POST;
198                 $header["object-type"] = ACTIVITY_OBJ_NOTE;
199
200                 $header["contact-id"] = $contact["id"];
201
202                 if (!is_object($entries)) {
203                         logger("There are no entries in this feed.", LOGGER_DEBUG);
204                         return;
205                 }
206
207                 $items = [];
208
209                 $entrylist = [];
210
211                 foreach ($entries AS $entry) {
212                         $entrylist[] = $entry;
213                 }
214                 foreach (array_reverse($entrylist) AS $entry) {
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 $attributes) {
223                                         if ($attributes->name == "href") {
224                                                 $item["plink"] = $attributes->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"] = original_url($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 = dba::selectFirst('item', ['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", $entry);
311                         foreach ($enclosures AS $enclosure) {
312                                 $href = "";
313                                 $length = "";
314                                 $type = "";
315                                 $title = "";
316
317                                 foreach ($enclosure->attributes AS $attributes) {
318                                         if ($attributes->name == "url") {
319                                                 $href = $attributes->textContent;
320                                         } elseif ($attributes->name == "length") {
321                                                 $length = $attributes->textContent;
322                                         } elseif ($attributes->name == "type") {
323                                                 $type = $attributes->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"] = html2bbcode($body, $basepath);
365
366                         if (($item["body"] == '') && ($item["title"] != '')) {
367                                 $item["body"] = $item["title"];
368                                 $item["title"] = '';
369                         }
370
371                         if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
372                                 $preview = "";
373
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"], false, $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                                                 $item["tag"] = add_page_keywords($item["plink"], false, $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 (!strstr($item["body"], $item['plink']) && ($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_is_remote_self($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
435                                 $id = item_store($item, false, $notify);
436
437                                 logger("Feed for contact ".$contact["url"]." stored under id ".$id);
438                         } else {
439                                 $items[] = $item;
440                         }
441                         if ($simulate) {
442                                 break;
443                         }
444                 }
445
446                 if ($simulate) {
447                         return ["header" => $author, "items" => $items];
448                 }
449         }
450
451         private static function titleIsBody($title, $body)
452         {
453                 $title = strip_tags($title);
454                 $title = trim($title);
455                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
456                 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
457
458                 $body = strip_tags($body);
459                 $body = trim($body);
460                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
461                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
462
463                 if (strlen($title) < strlen($body)) {
464                         $body = substr($body, 0, strlen($title));
465                 }
466
467                 if (($title != $body) && (substr($title, -3) == "...")) {
468                         $pos = strrpos($title, "...");
469                         if ($pos > 0) {
470                                 $title = substr($title, 0, $pos);
471                                 $body = substr($body, 0, $pos);
472                         }
473                 }
474                 return ($title == $body);
475         }
476 }