]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
a665b7c85a98f11ae2decb938cc3fb64119ecc71
[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"] = Network::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                         $preview = '';
499                         if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
500                                 // Handle enclosures and treat them as preview picture
501                                 foreach ($attachments AS $attachment) {
502                                         if ($attachment["type"] == "image/jpeg") {
503                                                 $preview = $attachment["link"];
504                                         }
505                                 }
506
507                                 // Remove a possible link to the item itself
508                                 $item["body"] = str_replace($item["plink"], '', $item["body"]);
509                                 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
510
511                                 // Replace the content when the title is longer than the body
512                                 $replace = (strlen($item["title"]) > strlen($item["body"]));
513
514                                 // Replace it, when there is an image in the body
515                                 if (strstr($item["body"], '[/img]')) {
516                                         $replace = true;
517                                 }
518
519                                 // Replace it, when there is a link in the body
520                                 if (strstr($item["body"], '[/url]')) {
521                                         $replace = true;
522                                 }
523
524                                 if ($replace) {
525                                         $item["body"] = trim($item["title"]);
526                                 }
527
528                                 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
529                                 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
530                                         // When the fetched page info text is longer than the body, we do try to enhance the body
531                                         if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
532                                                 // The body is not part of the fetched page info title or page info text. So we add the text to the body
533                                                 $item['body'] .= "\n\n" . $data['text'];
534                                         } else {
535                                                 // Else we replace the body with the page info text
536                                                 $item['body'] = $data['text'];
537                                         }
538                                 }
539
540                                 // We always strip the title since it will be added in the page information
541                                 $item["title"] = "";
542                                 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
543                                 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
544                                 $item["object-type"] = Activity\ObjectType::BOOKMARK;
545                                 unset($item["attach"]);
546                         } else {
547                                 if (!empty($summary)) {
548                                         $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
549                                 }
550
551                                 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
552                                         if (empty($taglist)) {
553                                                 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
554                                         }
555                                         $item["body"] .= "\n" . self::tagToString($taglist);
556                                 } else {
557                                         $taglist = [];
558                                 }
559
560                                 // Add the link to the original feed entry if not present in feed
561                                 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
562                                         $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
563                                 }
564                         }
565
566                         if ($dryRun) {
567                                 $items[] = $item;
568                                 break;
569                         } else {
570                                 Logger::info('Stored feed', ['item' => $item]);
571
572                                 $notify = Item::isRemoteSelf($contact, $item);
573
574                                 // Distributed items should have a well formatted URI.
575                                 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
576                                 if ($notify) {
577                                         $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
578                                         unset($item['uri']);
579                                         unset($item['parent-uri']);
580
581                                         // Set the delivery priority for "remote self" to "medium"
582                                         $notify = PRIORITY_MEDIUM;
583                                 }
584
585                                 $id = Item::insert($item, $notify);
586
587                                 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
588
589                                 if (!empty($id) && !empty($taglist)) {
590                                         $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
591                                         foreach ($taglist as $tag) {
592                                                 Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
593                                         }                                       
594                                 }
595                         }
596                 }
597
598                 return ["header" => $author, "items" => $items];
599         }
600
601         /**
602          * Convert a tag array to a tag string
603          *
604          * @param array $tags
605          * @return string tag string
606          */
607         private static function tagToString(array $tags)
608         {
609                 $tagstr = '';
610
611                 foreach ($tags as $tag) {
612                         if ($tagstr != "") {
613                                 $tagstr .= ", ";
614                         }
615         
616                         $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
617                 }
618
619                 return $tagstr;
620         }
621
622         private static function titleIsBody($title, $body)
623         {
624                 $title = strip_tags($title);
625                 $title = trim($title);
626                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
627                 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
628
629                 $body = strip_tags($body);
630                 $body = trim($body);
631                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
632                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
633
634                 if (strlen($title) < strlen($body)) {
635                         $body = substr($body, 0, strlen($title));
636                 }
637
638                 if (($title != $body) && (substr($title, -3) == "...")) {
639                         $pos = strrpos($title, "...");
640                         if ($pos > 0) {
641                                 $title = substr($title, 0, $pos);
642                                 $body = substr($body, 0, $pos);
643                         }
644                 }
645                 return ($title == $body);
646         }
647
648         /**
649          * Creates the Atom feed for a given nickname
650          *
651          * Supported filters:
652          * - activity (default): all the public posts
653          * - posts: all the public top-level posts
654          * - comments: all the public replies
655          *
656          * Updates the provided last_update parameter if the result comes from the
657          * cache or it is empty
658          *
659          * @param string  $owner_nick  Nickname of the feed owner
660          * @param string  $last_update Date of the last update
661          * @param integer $max_items   Number of maximum items to fetch
662          * @param string  $filter      Feed items filter (activity, posts or comments)
663          * @param boolean $nocache     Wether to bypass caching
664          *
665          * @return string Atom feed
666          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
667          * @throws \ImagickException
668          */
669         public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
670         {
671                 $stamp = microtime(true);
672
673                 $owner = User::getOwnerDataByNick($owner_nick);
674                 if (!$owner) {
675                         return;
676                 }
677
678                 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
679
680                 $previous_created = $last_update;
681
682                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
683                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
684                         $result = DI::cache()->get($cachekey);
685                         if (!$nocache && !is_null($result)) {
686                                 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
687                                 return $result['feed'];
688                         }
689                 }
690
691                 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
692                 $authorid = Contact::getIdForURL($owner["url"], 0, false);
693
694                 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
695                         AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
696                         $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
697                         Item::PRIVATE, Protocol::ACTIVITYPUB,
698                         Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
699
700                 if ($filter === 'comments') {
701                         $condition[0] .= " AND `object-type` = ? ";
702                         $condition[] = Activity\ObjectType::COMMENT;
703                 }
704
705                 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
706                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
707                         $condition[] = $owner["id"];
708                         $condition[] = $authorid;
709                 }
710
711                 $params = ['order' => ['received' => true], 'limit' => $max_items];
712
713                 if ($filter === 'posts') {
714                         $ret = Item::selectThread([], $condition, $params);
715                 } else {
716                         $ret = Item::select([], $condition, $params);
717                 }
718
719                 $items = Item::inArray($ret);
720
721                 $doc = new DOMDocument('1.0', 'utf-8');
722                 $doc->formatOutput = true;
723
724                 $root = self::addHeader($doc, $owner, $filter);
725
726                 foreach ($items as $item) {
727                         $entry = self::entry($doc, $item, $owner);
728                         $root->appendChild($entry);
729
730                         if ($last_update < $item['created']) {
731                                 $last_update = $item['created'];
732                         }
733                 }
734
735                 $feeddata = trim($doc->saveXML());
736
737                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
738                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
739
740                 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
741
742                 return $feeddata;
743         }
744
745         /**
746          * Adds the header elements to the XML document
747          *
748          * @param DOMDocument $doc       XML document
749          * @param array       $owner     Contact data of the poster
750          * @param string      $filter    The related feed filter (activity, posts or comments)
751          *
752          * @return object header root element
753          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
754          */
755         private static function addHeader(DOMDocument $doc, array $owner, $filter)
756         {
757                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
758                 $doc->appendChild($root);
759
760                 $title = '';
761                 $selfUri = '/feed/' . $owner["nick"] . '/';
762                 switch ($filter) {
763                         case 'activity':
764                                 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
765                                 $selfUri .= $filter;
766                                 break;
767                         case 'posts':
768                                 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
769                                 break;
770                         case 'comments':
771                                 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
772                                 $selfUri .= $filter;
773                                 break;
774                 }
775
776                 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
777                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
778                 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
779                 XML::addElement($doc, $root, "title", $title);
780                 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
781                 XML::addElement($doc, $root, "logo", $owner["photo"]);
782                 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
783
784                 $author = self::addAuthor($doc, $owner);
785                 $root->appendChild($author);
786
787                 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
788                 XML::addElement($doc, $root, "link", "", $attributes);
789
790                 OStatus::hublinks($doc, $root, $owner["nick"]);
791
792                 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
793                 XML::addElement($doc, $root, "link", "", $attributes);
794
795                 return $root;
796         }
797
798         /**
799          * Adds the author element to the XML document
800          *
801          * @param DOMDocument $doc          XML document
802          * @param array       $owner        Contact data of the poster
803          *
804          * @return \DOMElement author element
805          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
806          */
807         private static function addAuthor(DOMDocument $doc, array $owner)
808         {
809                 $author = $doc->createElement("author");
810                 XML::addElement($doc, $author, "uri", $owner["url"]);
811                 XML::addElement($doc, $author, "name", $owner["nick"]);
812                 XML::addElement($doc, $author, "email", $owner["addr"]);
813
814                 return $author;
815         }
816
817         /**
818          * Adds an entry element to the XML document
819          *
820          * @param DOMDocument $doc       XML document
821          * @param array       $item      Data of the item that is to be posted
822          * @param array       $owner     Contact data of the poster
823          * @param bool        $toplevel  optional default false
824          *
825          * @return \DOMElement Entry element
826          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
827          * @throws \ImagickException
828          */
829         private static function entry(DOMDocument $doc, array $item, array $owner)
830         {
831                 $xml = null;
832
833                 $repeated_guid = OStatus::getResharedGuid($item);
834                 if ($repeated_guid != "") {
835                         $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
836                 }
837
838                 if ($xml) {
839                         return $xml;
840                 }
841
842                 return self::noteEntry($doc, $item, $owner);
843         }
844
845                 /**
846          * Adds an entry element with reshared content
847          *
848          * @param DOMDocument $doc           XML document
849          * @param array       $item          Data of the item that is to be posted
850          * @param array       $owner         Contact data of the poster
851          * @param string      $repeated_guid guid
852          * @param bool        $toplevel      Is it for en entry element (false) or a feed entry (true)?
853          *
854          * @return bool Entry element
855          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
856          * @throws \ImagickException
857          */
858         private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
859         {
860                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
861                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
862                 }
863
864                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
865
866                 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
867                         'network' => Protocol::FEDERATED];
868                 $repeated_item = Item::selectFirst([], $condition);
869                 if (!DBA::isResult($repeated_item)) {
870                         return false;
871                 }
872
873                 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
874
875                 self::entryFooter($doc, $entry, $item, $owner);
876
877                 return $entry;
878         }
879
880         /**
881          * Adds a regular entry element
882          *
883          * @param DOMDocument $doc       XML document
884          * @param array       $item      Data of the item that is to be posted
885          * @param array       $owner     Contact data of the poster
886          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
887          *
888          * @return \DOMElement Entry element
889          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
890          * @throws \ImagickException
891          */
892         private static function noteEntry(DOMDocument $doc, array $item, array $owner)
893         {
894                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
895                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
896                 }
897
898                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
899
900                 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
901
902                 self::entryFooter($doc, $entry, $item, $owner);
903
904                 return $entry;
905         }
906
907         /**
908          * Adds elements to the XML document
909          *
910          * @param DOMDocument $doc       XML document
911          * @param \DOMElement $entry     Entry element where the content is added
912          * @param array       $item      Data of the item that is to be posted
913          * @param array       $owner     Contact data of the poster
914          * @param string      $title     Title for the post
915          * @param string      $verb      The activity verb
916          * @param bool        $complete  Add the "status_net" element?
917          * @param bool        $feed_mode Behave like a regular feed for users if true
918          * @return void
919          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
920          */
921         private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
922         {
923                 if ($verb == "") {
924                         $verb = OStatus::constructVerb($item);
925                 }
926
927                 XML::addElement($doc, $entry, "id", $item["uri"]);
928                 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
929
930                 $body = OStatus::formatPicturePost($item['body']);
931
932                 $body = BBCode::convert($body, false, BBCode::OSTATUS);
933
934                 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
935
936                 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
937                                                                 "href" => DI::baseUrl()."/display/".$item["guid"]]
938                 );
939
940                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
941                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
942         }
943
944         /**
945          * Adds the elements at the foot of an entry to the XML document
946          *
947          * @param DOMDocument $doc       XML document
948          * @param object      $entry     The entry element where the elements are added
949          * @param array       $item      Data of the item that is to be posted
950          * @param array       $owner     Contact data of the poster
951          * @param bool        $complete  default true
952          * @return void
953          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
954          */
955         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
956         {
957                 $mentioned = [];
958
959                 if ($item['gravity'] != GRAVITY_PARENT) {
960                         $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
961                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
962
963                         $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
964
965                         if (DBA::isResult($thrparent)) {
966                                 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
967                                 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
968                                 $parent_plink = $thrparent["plink"];
969                         } else {
970                                 $mentioned[$parent["author-link"]] = $parent["author-link"];
971                                 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
972                                 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
973                         }
974
975                         $attributes = [
976                                         "ref" => $parent_item,
977                                         "href" => $parent_plink];
978                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
979
980                         $attributes = [
981                                         "rel" => "related",
982                                         "href" => $parent_plink];
983                         XML::addElement($doc, $entry, "link", "", $attributes);
984                 }
985
986                 // uri-id isn't present for follow entry pseudo-items
987                 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
988                 foreach ($tags as $tag) {
989                         $mentioned[$tag['url']] = $tag['url'];
990                 }
991
992                 foreach ($tags as $tag) {
993                         if ($tag['type'] == Tag::HASHTAG) {
994                                 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
995                         }
996                 }
997
998                 OStatus::getAttachment($doc, $entry, $item);
999         }
1000
1001         /**
1002          * Fetch or create title for feed entry
1003          *
1004          * @param array $item
1005          * @return string title
1006          */
1007         private static function getTitle(array $item)
1008         {
1009                 if ($item['title'] != '') {
1010                         return BBCode::convert($item['title'], false, BBCode::OSTATUS);
1011                 }
1012
1013                 // Fetch information about the post
1014                 $siteinfo = BBCode::getAttachedData($item["body"]);
1015                 if (isset($siteinfo["title"])) {
1016                         return $siteinfo["title"];
1017                 }
1018
1019                 // If no bookmark is found then take the first line
1020                 // Remove the share element before fetching the first line
1021                 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1022
1023                 $title = HTML::toPlaintext(BBCode::convert($title, false), 0, true)."\n";
1024                 $pos = strpos($title, "\n");
1025                 $trailer = "";
1026                 if (($pos == 0) || ($pos > 100)) {
1027                         $pos = 100;
1028                         $trailer = "...";
1029                 }
1030
1031                 return substr($title, 0, $pos) . $trailer;
1032         }
1033 }