]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
Merge pull request #9017 from annando/issue-9015
[friendica.git] / src / Protocol / Feed.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Friendica\Content\PageInfo;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Cache\Duration;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Tag;
37 use Friendica\Model\User;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Network;
40 use Friendica\Util\ParseUrl;
41 use Friendica\Util\Strings;
42 use Friendica\Util\XML;
43
44 /**
45  * This class contain functions to import feeds (RSS/RDF/Atom)
46  */
47 class Feed
48 {
49         /**
50          * consume - process atom feed and update anything/everything we might need to update
51          *
52          * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
53          *
54          * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
55          *             It is this person's stuff that is going to be updated.
56          * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
57          *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST
58          *             have a contact record.
59          * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
60          *        might not) try and subscribe to it.
61          * $datedir sorts in reverse order
62          * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
63          *      imported prior to its children being seen in the stream unless we are certain
64          *      of how the feed is arranged/ordered.
65          * With $pass = 1, we only pull parent items out of the stream.
66          * With $pass = 2, we only pull children (comments/likes).
67          *
68          * So running this twice, first with pass 1 and then with pass 2 will do the right
69          * thing regardless of feed ordering. This won't be adequate in a fully-threaded
70          * model where comments can have sub-threads. That would require some massive sorting
71          * to get all the feed items into a mostly linear ordering, and might still require
72          * recursion.
73          *
74          * @param       $xml
75          * @param array $importer
76          * @param array $contact
77          * @param       $hub
78          * @throws ImagickException
79          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
80          */
81         public static function consume($xml, array $importer, array $contact, &$hub)
82         {
83                 if ($contact['network'] === Protocol::OSTATUS) {
84                         Logger::info('Consume OStatus messages');
85                         OStatus::import($xml, $importer, $contact, $hub);
86
87                         return;
88                 }
89
90                 if ($contact['network'] === Protocol::FEED) {
91                         Logger::info('Consume feeds');
92                         self::import($xml, $importer, $contact);
93
94                         return;
95                 }
96
97                 if ($contact['network'] === Protocol::DFRN) {
98                         Logger::info('Consume DFRN messages');
99                         $dfrn_importer = DFRN::getImporter($contact['id'], $importer['uid']);
100                         if (!empty($dfrn_importer)) {
101                                 Logger::info('Now import the DFRN feed');
102                                 DFRN::import($xml, $dfrn_importer, true);
103                                 return;
104                         }
105                 }
106         }
107
108         /**
109          * Read a RSS/RDF/Atom feed and create an item entry for it
110          *
111          * @param string $xml      The feed data
112          * @param array  $importer The user record of the importer
113          * @param array  $contact  The contact record of the feed
114          *
115          * @return array Returns the header and the first item in dry run mode
116          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
117          */
118         public static function import($xml, array $importer = [], array $contact = [])
119         {
120                 $dryRun = empty($importer) && empty($contact);
121
122                 if ($dryRun) {
123                         Logger::info("Test Atom/RSS feed");
124                 } else {
125                         Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
126                 }
127
128                 if (empty($xml)) {
129                         Logger::info('XML is empty.');
130                         return [];
131                 }
132
133                 if (!empty($contact['poll'])) {
134                         $basepath = $contact['poll'];
135                 } elseif (!empty($contact['url'])) {
136                         $basepath = $contact['url'];
137                 } else {
138                         $basepath = '';
139                 }
140
141                 $doc = new DOMDocument();
142                 @$doc->loadXML(trim($xml));
143                 $xpath = new DOMXPath($doc);
144                 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
145                 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
146                 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
147                 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
148                 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
149                 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
150                 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
151
152                 $author = [];
153                 $entries = null;
154
155                 // Is it RDF?
156                 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
157                         $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
158                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
159
160                         if (empty($author["author-name"])) {
161                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
162                         }
163                         $entries = $xpath->query('/rdf:RDF/rss:item');
164                 }
165
166                 // Is it Atom?
167                 if ($xpath->query('/atom:feed')->length > 0) {
168                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
169                         if (is_object($alternate)) {
170                                 foreach ($alternate AS $attribute) {
171                                         if ($attribute->name == "href") {
172                                                 $author["author-link"] = $attribute->textContent;
173                                         }
174                                 }
175                         }
176
177                         if (empty($author["author-link"])) {
178                                 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
179                                 if (is_object($self)) {
180                                         foreach ($self AS $attribute) {
181                                                 if ($attribute->name == "href") {
182                                                         $author["author-link"] = $attribute->textContent;
183                                                 }
184                                         }
185                                 }
186                         }
187
188                         if (empty($author["author-link"])) {
189                                 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
190                         }
191                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
192
193                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
194
195                         if (empty($author["author-name"])) {
196                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
197                         }
198
199                         if (empty($author["author-name"])) {
200                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
201                         }
202
203                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
204                         if ($value != "") {
205                                 $author["author-name"] = $value;
206                         }
207
208                         if ($dryRun) {
209                                 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
210
211                                 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
212                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
213                                 if ($value != "") {
214                                         $author["author-link"] = $value;
215                                 }
216
217                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
218                                 if ($value != "") {
219                                         $author["author-nick"] = $value;
220                                 }
221
222                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
223                                 if ($value != "") {
224                                         $author["author-location"] = $value;
225                                 }
226
227                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
228                                 if ($value != "") {
229                                         $author["author-about"] = $value;
230                                 }
231
232                                 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
233                                 if (is_object($avatar)) {
234                                         foreach ($avatar AS $attribute) {
235                                                 if ($attribute->name == "href") {
236                                                         $author["author-avatar"] = $attribute->textContent;
237                                                 }
238                                         }
239                                 }
240                         }
241
242                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
243
244                         $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
245
246                         $entries = $xpath->query('/atom:feed/atom:entry');
247                 }
248
249                 // Is it RSS?
250                 if ($xpath->query('/rss/channel')->length > 0) {
251                         $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
252
253                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
254                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
255
256                         if (empty($author["author-name"])) {
257                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
258                         }
259
260                         if (empty($author["author-name"])) {
261                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
262                         }
263
264                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
265
266                         $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
267
268                         $entries = $xpath->query('/rss/channel/item');
269                 }
270
271                 if (!$dryRun) {
272                         $author["author-link"] = $contact["url"];
273
274                         if (empty($author["author-name"])) {
275                                 $author["author-name"] = $contact["name"];
276                         }
277
278                         $author["author-avatar"] = $contact["thumb"];
279
280                         $author["owner-link"] = $contact["url"];
281                         $author["owner-name"] = $contact["name"];
282                         $author["owner-avatar"] = $contact["thumb"];
283                 }
284
285                 $header = [];
286                 $header["uid"] = $importer["uid"] ?? 0;
287                 $header["network"] = Protocol::FEED;
288                 $header["wall"] = 0;
289                 $header["origin"] = 0;
290                 $header["gravity"] = GRAVITY_PARENT;
291                 $header["private"] = Item::PUBLIC;
292                 $header["verb"] = Activity::POST;
293                 $header["object-type"] = Activity\ObjectType::NOTE;
294
295                 $header["contact-id"] = $contact["id"] ?? 0;
296
297                 if (!is_object($entries)) {
298                         Logger::info("There are no entries in this feed.");
299                         return [];
300                 }
301
302                 $items = [];
303
304                 // Limit the number of items that are about to be fetched
305                 $total_items = ($entries->length - 1);
306                 $max_items = DI::config()->get('system', 'max_feed_items');
307                 if (($max_items > 0) && ($total_items > $max_items)) {
308                         $total_items = $max_items;
309                 }
310
311                 // Importing older entries first
312                 for ($i = $total_items; $i >= 0; --$i) {
313                         $entry = $entries->item($i);
314
315                         $item = array_merge($header, $author);
316
317                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
318                         if (!is_object($alternate)) {
319                                 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
320                         }
321                         if (is_object($alternate)) {
322                                 foreach ($alternate AS $attribute) {
323                                         if ($attribute->name == "href") {
324                                                 $item["plink"] = $attribute->textContent;
325                                         }
326                                 }
327                         }
328
329                         if (empty($item["plink"])) {
330                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
331                         }
332
333                         if (empty($item["plink"])) {
334                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
335                         }
336
337                         $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
338
339                         if (empty($item["uri"])) {
340                                 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
341                         }
342
343                         if (empty($item["uri"])) {
344                                 $item["uri"] = $item["plink"];
345                         }
346
347                         // Add the base path if missing
348                         $item["uri"] = Network::addBasePath($item["uri"], $basepath);
349                         $item["plink"] = Network::addBasePath($item["plink"], $basepath);
350
351                         $orig_plink = $item["plink"];
352
353                         $item["plink"] = DI::httpRequest()->finalUrl($item["plink"]);
354
355                         $item["parent-uri"] = $item["uri"];
356
357                         if (!$dryRun) {
358                                 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
359                                         $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
360                                 $previous = Item::selectFirst(['id'], $condition);
361                                 if (DBA::isResult($previous)) {
362                                         Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
363                                         continue;
364                                 }
365                         }
366
367                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
368
369                         if (empty($item["title"])) {
370                                 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
371                         }
372                         if (empty($item["title"])) {
373                                 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
374                         }
375
376                         $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
377
378                         $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
379
380                         if (empty($published)) {
381                                 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
382                         }
383
384                         if (empty($published)) {
385                                 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
386                         }
387
388                         $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
389
390                         if (empty($updated) && !empty($published)) {
391                                 $updated = $published;
392                         }
393
394                         if (empty($published) && !empty($updated)) {
395                                 $published = $updated;
396                         }
397
398                         if ($published != "") {
399                                 $item["created"] = $published;
400                         }
401
402                         if ($updated != "") {
403                                 $item["edited"] = $updated;
404                         }
405
406                         $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
407
408                         if (empty($creator)) {
409                                 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
410                         }
411
412                         if (empty($creator)) {
413                                 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
414                         }
415
416                         if ($creator != "") {
417                                 $item["author-name"] = $creator;
418                         }
419
420                         $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
421
422                         if ($creator != "") {
423                                 $item["author-name"] = $creator;
424                         }
425
426                         /// @TODO ?
427                         // <category>Ausland</category>
428                         // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
429
430                         $attachments = [];
431
432                         $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
433                         foreach ($enclosures AS $enclosure) {
434                                 $href = "";
435                                 $length = "";
436                                 $type = "";
437
438                                 foreach ($enclosure->attributes AS $attribute) {
439                                         if (in_array($attribute->name, ["url", "href"])) {
440                                                 $href = $attribute->textContent;
441                                         } elseif ($attribute->name == "length") {
442                                                 $length = $attribute->textContent;
443                                         } elseif ($attribute->name == "type") {
444                                                 $type = $attribute->textContent;
445                                         }
446                                 }
447
448                                 if (!empty($item["attach"])) {
449                                         $item["attach"] .= ',';
450                                 } else {
451                                         $item["attach"] = '';
452                                 }
453
454                                 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
455
456                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
457                         }
458
459                         $taglist = [];
460                         $categories = $xpath->query("category", $entry);
461                         foreach ($categories AS $category) {
462                                 $taglist[] = $category->nodeValue;
463                         }
464
465                         $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
466
467                         if (empty($body)) {
468                                 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
469                         }
470
471                         $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
472
473                         if (empty($summary)) {
474                                 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
475                         }
476
477                         if (empty($body)) {
478                                 $body = $summary;
479                                 $summary = '';
480                         }
481
482                         if ($body == $summary) {
483                                 $summary = '';
484                         }
485
486                         // remove the content of the title if it is identically to the body
487                         // This helps with auto generated titles e.g. from tumblr
488                         if (self::titleIsBody($item["title"], $body)) {
489                                 $item["title"] = "";
490                         }
491                         $item["body"] = HTML::toBBCode($body, $basepath);
492
493                         if (($item["body"] == '') && ($item["title"] != '')) {
494                                 $item["body"] = $item["title"];
495                                 $item["title"] = '';
496                         }
497
498                         if ($dryRun) {
499                                 $items[] = $item;
500                                 break;
501                         } elseif (!Item::isValid($item)) {
502                                 Logger::info('Feed is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
503                                 continue;
504                         }
505
506                         $preview = '';
507                         if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
508                                 // Handle enclosures and treat them as preview picture
509                                 foreach ($attachments AS $attachment) {
510                                         if ($attachment["type"] == "image/jpeg") {
511                                                 $preview = $attachment["link"];
512                                         }
513                                 }
514
515                                 // Remove a possible link to the item itself
516                                 $item["body"] = str_replace($item["plink"], '', $item["body"]);
517                                 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
518
519                                 // Replace the content when the title is longer than the body
520                                 $replace = (strlen($item["title"]) > strlen($item["body"]));
521
522                                 // Replace it, when there is an image in the body
523                                 if (strstr($item["body"], '[/img]')) {
524                                         $replace = true;
525                                 }
526
527                                 // Replace it, when there is a link in the body
528                                 if (strstr($item["body"], '[/url]')) {
529                                         $replace = true;
530                                 }
531
532                                 if ($replace) {
533                                         $item["body"] = trim($item["title"]);
534                                 }
535
536                                 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
537                                 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
538                                         // When the fetched page info text is longer than the body, we do try to enhance the body
539                                         if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
540                                                 // The body is not part of the fetched page info title or page info text. So we add the text to the body
541                                                 $item['body'] .= "\n\n" . $data['text'];
542                                         } else {
543                                                 // Else we replace the body with the page info text
544                                                 $item['body'] = $data['text'];
545                                         }
546                                 }
547
548                                 // We always strip the title since it will be added in the page information
549                                 $item["title"] = "";
550                                 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
551                                 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
552                                 $item["object-type"] = Activity\ObjectType::BOOKMARK;
553                                 unset($item["attach"]);
554                         } else {
555                                 if (!empty($summary)) {
556                                         $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
557                                 }
558
559                                 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
560                                         if (empty($taglist)) {
561                                                 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
562                                         }
563                                         $item["body"] .= "\n" . self::tagToString($taglist);
564                                 } else {
565                                         $taglist = [];
566                                 }
567
568                                 // Add the link to the original feed entry if not present in feed
569                                 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
570                                         $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
571                                 }
572                         }
573
574                         Logger::info('Stored feed', ['item' => $item]);
575
576                         $notify = Item::isRemoteSelf($contact, $item);
577
578                         // Distributed items should have a well formatted URI.
579                         // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
580                         if ($notify) {
581                                 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
582                                 unset($item['uri']);
583                                 unset($item['parent-uri']);
584
585                                 // Set the delivery priority for "remote self" to "medium"
586                                 $notify = PRIORITY_MEDIUM;
587                         }
588
589                         $id = Item::insert($item, $notify);
590
591                         Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
592
593                         if (!empty($id) && !empty($taglist)) {
594                                 $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
595                                 foreach ($taglist as $tag) {
596                                         Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
597                                 }
598                         }
599                 }
600
601                 return ["header" => $author, "items" => $items];
602         }
603
604         /**
605          * Convert a tag array to a tag string
606          *
607          * @param array $tags
608          * @return string tag string
609          */
610         private static function tagToString(array $tags)
611         {
612                 $tagstr = '';
613
614                 foreach ($tags as $tag) {
615                         if ($tagstr != "") {
616                                 $tagstr .= ", ";
617                         }
618         
619                         $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
620                 }
621
622                 return $tagstr;
623         }
624
625         private static function titleIsBody($title, $body)
626         {
627                 $title = strip_tags($title);
628                 $title = trim($title);
629                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
630                 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
631
632                 $body = strip_tags($body);
633                 $body = trim($body);
634                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
635                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
636
637                 if (strlen($title) < strlen($body)) {
638                         $body = substr($body, 0, strlen($title));
639                 }
640
641                 if (($title != $body) && (substr($title, -3) == "...")) {
642                         $pos = strrpos($title, "...");
643                         if ($pos > 0) {
644                                 $title = substr($title, 0, $pos);
645                                 $body = substr($body, 0, $pos);
646                         }
647                 }
648                 return ($title == $body);
649         }
650
651         /**
652          * Creates the Atom feed for a given nickname
653          *
654          * Supported filters:
655          * - activity (default): all the public posts
656          * - posts: all the public top-level posts
657          * - comments: all the public replies
658          *
659          * Updates the provided last_update parameter if the result comes from the
660          * cache or it is empty
661          *
662          * @param string  $owner_nick  Nickname of the feed owner
663          * @param string  $last_update Date of the last update
664          * @param integer $max_items   Number of maximum items to fetch
665          * @param string  $filter      Feed items filter (activity, posts or comments)
666          * @param boolean $nocache     Wether to bypass caching
667          *
668          * @return string Atom feed
669          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
670          * @throws \ImagickException
671          */
672         public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
673         {
674                 $stamp = microtime(true);
675
676                 $owner = User::getOwnerDataByNick($owner_nick);
677                 if (!$owner) {
678                         return;
679                 }
680
681                 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
682
683                 $previous_created = $last_update;
684
685                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
686                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
687                         $result = DI::cache()->get($cachekey);
688                         if (!$nocache && !is_null($result)) {
689                                 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
690                                 return $result['feed'];
691                         }
692                 }
693
694                 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
695                 $authorid = Contact::getIdForURL($owner["url"]);
696
697                 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
698                         AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
699                         $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
700                         Item::PRIVATE, Protocol::ACTIVITYPUB,
701                         Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
702
703                 if ($filter === 'comments') {
704                         $condition[0] .= " AND `object-type` = ? ";
705                         $condition[] = Activity\ObjectType::COMMENT;
706                 }
707
708                 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
709                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
710                         $condition[] = $owner["id"];
711                         $condition[] = $authorid;
712                 }
713
714                 $params = ['order' => ['received' => true], 'limit' => $max_items];
715
716                 if ($filter === 'posts') {
717                         $ret = Item::selectThread([], $condition, $params);
718                 } else {
719                         $ret = Item::select([], $condition, $params);
720                 }
721
722                 $items = Item::inArray($ret);
723
724                 $doc = new DOMDocument('1.0', 'utf-8');
725                 $doc->formatOutput = true;
726
727                 $root = self::addHeader($doc, $owner, $filter);
728
729                 foreach ($items as $item) {
730                         $entry = self::entry($doc, $item, $owner);
731                         $root->appendChild($entry);
732
733                         if ($last_update < $item['created']) {
734                                 $last_update = $item['created'];
735                         }
736                 }
737
738                 $feeddata = trim($doc->saveXML());
739
740                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
741                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
742
743                 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
744
745                 return $feeddata;
746         }
747
748         /**
749          * Adds the header elements to the XML document
750          *
751          * @param DOMDocument $doc       XML document
752          * @param array       $owner     Contact data of the poster
753          * @param string      $filter    The related feed filter (activity, posts or comments)
754          *
755          * @return object header root element
756          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
757          */
758         private static function addHeader(DOMDocument $doc, array $owner, $filter)
759         {
760                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
761                 $doc->appendChild($root);
762
763                 $title = '';
764                 $selfUri = '/feed/' . $owner["nick"] . '/';
765                 switch ($filter) {
766                         case 'activity':
767                                 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
768                                 $selfUri .= $filter;
769                                 break;
770                         case 'posts':
771                                 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
772                                 break;
773                         case 'comments':
774                                 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
775                                 $selfUri .= $filter;
776                                 break;
777                 }
778
779                 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
780                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
781                 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
782                 XML::addElement($doc, $root, "title", $title);
783                 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
784                 XML::addElement($doc, $root, "logo", $owner["photo"]);
785                 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
786
787                 $author = self::addAuthor($doc, $owner);
788                 $root->appendChild($author);
789
790                 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
791                 XML::addElement($doc, $root, "link", "", $attributes);
792
793                 OStatus::hublinks($doc, $root, $owner["nick"]);
794
795                 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
796                 XML::addElement($doc, $root, "link", "", $attributes);
797
798                 return $root;
799         }
800
801         /**
802          * Adds the author element to the XML document
803          *
804          * @param DOMDocument $doc          XML document
805          * @param array       $owner        Contact data of the poster
806          *
807          * @return \DOMElement author element
808          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
809          */
810         private static function addAuthor(DOMDocument $doc, array $owner)
811         {
812                 $author = $doc->createElement("author");
813                 XML::addElement($doc, $author, "uri", $owner["url"]);
814                 XML::addElement($doc, $author, "name", $owner["nick"]);
815                 XML::addElement($doc, $author, "email", $owner["addr"]);
816
817                 return $author;
818         }
819
820         /**
821          * Adds an entry element to the XML document
822          *
823          * @param DOMDocument $doc       XML document
824          * @param array       $item      Data of the item that is to be posted
825          * @param array       $owner     Contact data of the poster
826          * @param bool        $toplevel  optional default false
827          *
828          * @return \DOMElement Entry element
829          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
830          * @throws \ImagickException
831          */
832         private static function entry(DOMDocument $doc, array $item, array $owner)
833         {
834                 $xml = null;
835
836                 $repeated_guid = OStatus::getResharedGuid($item);
837                 if ($repeated_guid != "") {
838                         $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
839                 }
840
841                 if ($xml) {
842                         return $xml;
843                 }
844
845                 return self::noteEntry($doc, $item, $owner);
846         }
847
848                 /**
849          * Adds an entry element with reshared content
850          *
851          * @param DOMDocument $doc           XML document
852          * @param array       $item          Data of the item that is to be posted
853          * @param array       $owner         Contact data of the poster
854          * @param string      $repeated_guid guid
855          * @param bool        $toplevel      Is it for en entry element (false) or a feed entry (true)?
856          *
857          * @return bool Entry element
858          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
859          * @throws \ImagickException
860          */
861         private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
862         {
863                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
864                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
865                 }
866
867                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
868
869                 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
870                         'network' => Protocol::FEDERATED];
871                 $repeated_item = Item::selectFirst([], $condition);
872                 if (!DBA::isResult($repeated_item)) {
873                         return false;
874                 }
875
876                 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
877
878                 self::entryFooter($doc, $entry, $item, $owner);
879
880                 return $entry;
881         }
882
883         /**
884          * Adds a regular entry element
885          *
886          * @param DOMDocument $doc       XML document
887          * @param array       $item      Data of the item that is to be posted
888          * @param array       $owner     Contact data of the poster
889          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
890          *
891          * @return \DOMElement Entry element
892          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
893          * @throws \ImagickException
894          */
895         private static function noteEntry(DOMDocument $doc, array $item, array $owner)
896         {
897                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
898                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
899                 }
900
901                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
902
903                 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
904
905                 self::entryFooter($doc, $entry, $item, $owner);
906
907                 return $entry;
908         }
909
910         /**
911          * Adds elements to the XML document
912          *
913          * @param DOMDocument $doc       XML document
914          * @param \DOMElement $entry     Entry element where the content is added
915          * @param array       $item      Data of the item that is to be posted
916          * @param array       $owner     Contact data of the poster
917          * @param string      $title     Title for the post
918          * @param string      $verb      The activity verb
919          * @param bool        $complete  Add the "status_net" element?
920          * @param bool        $feed_mode Behave like a regular feed for users if true
921          * @return void
922          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
923          */
924         private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
925         {
926                 if ($verb == "") {
927                         $verb = OStatus::constructVerb($item);
928                 }
929
930                 XML::addElement($doc, $entry, "id", $item["uri"]);
931                 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
932
933                 $body = OStatus::formatPicturePost($item['body']);
934
935                 $body = BBCode::convert($body, false, BBCode::OSTATUS);
936
937                 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
938
939                 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
940                                                                 "href" => DI::baseUrl()."/display/".$item["guid"]]
941                 );
942
943                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
944                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
945         }
946
947         /**
948          * Adds the elements at the foot of an entry to the XML document
949          *
950          * @param DOMDocument $doc       XML document
951          * @param object      $entry     The entry element where the elements are added
952          * @param array       $item      Data of the item that is to be posted
953          * @param array       $owner     Contact data of the poster
954          * @param bool        $complete  default true
955          * @return void
956          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
957          */
958         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
959         {
960                 $mentioned = [];
961
962                 if ($item['gravity'] != GRAVITY_PARENT) {
963                         $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
964                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
965
966                         $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
967
968                         if (DBA::isResult($thrparent)) {
969                                 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
970                                 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
971                                 $parent_plink = $thrparent["plink"];
972                         } else {
973                                 $mentioned[$parent["author-link"]] = $parent["author-link"];
974                                 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
975                                 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
976                         }
977
978                         $attributes = [
979                                         "ref" => $parent_item,
980                                         "href" => $parent_plink];
981                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
982
983                         $attributes = [
984                                         "rel" => "related",
985                                         "href" => $parent_plink];
986                         XML::addElement($doc, $entry, "link", "", $attributes);
987                 }
988
989                 // uri-id isn't present for follow entry pseudo-items
990                 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
991                 foreach ($tags as $tag) {
992                         $mentioned[$tag['url']] = $tag['url'];
993                 }
994
995                 foreach ($tags as $tag) {
996                         if ($tag['type'] == Tag::HASHTAG) {
997                                 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
998                         }
999                 }
1000
1001                 OStatus::getAttachment($doc, $entry, $item);
1002         }
1003
1004         /**
1005          * Fetch or create title for feed entry
1006          *
1007          * @param array $item
1008          * @return string title
1009          */
1010         private static function getTitle(array $item)
1011         {
1012                 if ($item['title'] != '') {
1013                         return BBCode::convert($item['title'], false, BBCode::OSTATUS);
1014                 }
1015
1016                 // Fetch information about the post
1017                 $siteinfo = BBCode::getAttachedData($item["body"]);
1018                 if (isset($siteinfo["title"])) {
1019                         return $siteinfo["title"];
1020                 }
1021
1022                 // If no bookmark is found then take the first line
1023                 // Remove the share element before fetching the first line
1024                 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1025
1026                 $title = HTML::toPlaintext(BBCode::convert($title, false), 0, true)."\n";
1027                 $pos = strpos($title, "\n");
1028                 $trailer = "";
1029                 if (($pos == 0) || ($pos > 100)) {
1030                         $pos = 100;
1031                         $trailer = "...";
1032                 }
1033
1034                 return substr($title, 0, $pos) . $trailer;
1035         }
1036 }