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