]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
Fix missing attached links in posts
[friendica.git] / src / Protocol / Feed.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
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 DOMElement;
26 use DOMXPath;
27 use Friendica\App;
28 use Friendica\Content\PageInfo;
29 use Friendica\Content\Text\BBCode;
30 use Friendica\Content\Text\HTML;
31 use Friendica\Core\Cache\Enum\Duration;
32 use Friendica\Core\Logger;
33 use Friendica\Core\Protocol;
34 use Friendica\Core\Worker;
35 use Friendica\Database\DBA;
36 use Friendica\DI;
37 use Friendica\Model\Contact;
38 use Friendica\Model\Conversation;
39 use Friendica\Model\Item;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Network\HTTPException;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Network;
46 use Friendica\Util\ParseUrl;
47 use Friendica\Util\Proxy;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
50 use GuzzleHttp\Exception\TransferException;
51
52 /**
53  * This class contain functions to import feeds (RSS/RDF/Atom)
54  */
55 class Feed
56 {
57         /**
58          * Read a RSS/RDF/Atom feed and create an item entry for it
59          *
60          * @param string $xml      The feed data
61          * @param array  $importer The user record of the importer
62          * @param array  $contact  The contact record of the feed
63          *
64          * @return array Returns the header and the first item in dry run mode
65          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
66          */
67         public static function import(string $xml, array $importer = [], array $contact = []): array
68         {
69                 $dryRun = empty($importer) && empty($contact);
70
71                 if ($dryRun) {
72                         Logger::info("Test Atom/RSS feed");
73                 } else {
74                         Logger::info('Import Atom/RSS feed "' . $contact['name'] . '" (Contact ' . $contact['id'] . ') for user ' . $importer['uid']);
75                 }
76
77                 $xml = trim($xml);
78
79                 if (empty($xml)) {
80                         Logger::info('XML is empty.');
81                         return [];
82                 }
83
84                 if (!empty($contact['poll'])) {
85                         $basepath = $contact['poll'];
86                 } elseif (!empty($contact['url'])) {
87                         $basepath = $contact['url'];
88                 } else {
89                         $basepath = '';
90                 }
91
92                 $doc = new DOMDocument();
93                 @$doc->loadXML($xml);
94                 $xpath = new DOMXPath($doc);
95                 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
96                 $xpath->registerNamespace('dc', 'http://purl.org/dc/elements/1.1/');
97                 $xpath->registerNamespace('content', 'http://purl.org/rss/1.0/modules/content/');
98                 $xpath->registerNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
99                 $xpath->registerNamespace('rss', 'http://purl.org/rss/1.0/');
100                 $xpath->registerNamespace('media', 'http://search.yahoo.com/mrss/');
101                 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
102
103                 $author = [];
104                 $entries = null;
105                 $protocol = Conversation::PARCEL_UNKNOWN;
106
107                 // Is it RDF?
108                 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
109                         $protocol = Conversation::PARCEL_RDF;
110                         $author['author-link'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
111                         $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
112
113                         if (empty($author['author-name'])) {
114                                 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
115                         }
116                         $entries = $xpath->query('/rdf:RDF/rss:item');
117                 }
118
119                 // Is it Atom?
120                 if ($xpath->query('/atom:feed')->length > 0) {
121                         $protocol = Conversation::PARCEL_ATOM;
122                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
123                         if (is_object($alternate)) {
124                                 foreach ($alternate as $attribute) {
125                                         if ($attribute->name == 'href') {
126                                                 $author['author-link'] = $attribute->textContent;
127                                         }
128                                 }
129                         }
130
131                         if (empty($author['author-link'])) {
132                                 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
133                                 if (is_object($self)) {
134                                         foreach ($self as $attribute) {
135                                                 if ($attribute->name == 'href') {
136                                                         $author['author-link'] = $attribute->textContent;
137                                                 }
138                                         }
139                                 }
140                         }
141
142                         if (empty($author['author-link'])) {
143                                 $author['author-link'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
144                         }
145                         $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
146
147                         $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
148
149                         if (empty($author['author-name'])) {
150                                 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
151                         }
152
153                         if (empty($author['author-name'])) {
154                                 $author['author-name'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
155                         }
156
157                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
158                         if ($value != '') {
159                                 $author['author-name'] = $value;
160                         }
161
162                         if ($dryRun) {
163                                 $author['author-id'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
164
165                                 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
166                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
167                                 if ($value != '') {
168                                         $author['author-link'] = $value;
169                                 }
170
171                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
172                                 if ($value != '') {
173                                         $author['author-nick'] = $value;
174                                 }
175
176                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
177                                 if ($value != '') {
178                                         $author['author-location'] = $value;
179                                 }
180
181                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
182                                 if ($value != '') {
183                                         $author['author-about'] = $value;
184                                 }
185
186                                 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
187                                 if (is_object($avatar)) {
188                                         foreach ($avatar as $attribute) {
189                                                 if ($attribute->name == 'href') {
190                                                         $author['author-avatar'] = $attribute->textContent;
191                                                 }
192                                         }
193                                 }
194                         }
195
196                         $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
197
198                         $author['app'] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
199
200                         $entries = $xpath->query('/atom:feed/atom:entry');
201                 }
202
203                 // Is it RSS?
204                 if ($xpath->query('/rss/channel')->length > 0) {
205                         $protocol = Conversation::PARCEL_RSS;
206                         $author['author-link'] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
207
208                         $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
209
210                         if (empty($author['author-name'])) {
211                                 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
212                         }
213
214                         if (empty($author['author-name'])) {
215                                 $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
216                         }
217
218                         $author['author-avatar'] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
219
220                         if (empty($author['author-avatar'])) {
221                                 $avatar = XML::getFirstAttributes($xpath, '/rss/channel/itunes:image');
222                                 if (is_object($avatar)) {
223                                         foreach ($avatar as $attribute) {
224                                                 if ($attribute->name == 'href') {
225                                                         $author['author-avatar'] = $attribute->textContent;
226                                                 }
227                                         }
228                                 }
229                         }
230
231                         $author['author-about'] = HTML::toBBCode(XML::getFirstNodeValue($xpath, '/rss/channel/description/text()'), $basepath);
232
233                         if (empty($author['author-about'])) {
234                                 $author['author-about'] = XML::getFirstNodeValue($xpath, '/rss/channel/itunes:summary/text()');
235                         }
236
237                         $author['edited'] = $author['created'] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
238
239                         $author['app'] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
240
241                         $entries = $xpath->query('/rss/channel/item');
242                 }
243
244                 if (!$dryRun) {
245                         $author['author-link'] = $contact['url'];
246
247                         if (empty($author['author-name'])) {
248                                 $author['author-name'] = $contact['name'];
249                         }
250
251                         $author['author-avatar'] = $contact['thumb'];
252
253                         $author['owner-link'] = $contact['url'];
254                         $author['owner-name'] = $contact['name'];
255                         $author['owner-avatar'] = $contact['thumb'];
256                 }
257
258                 $header = [
259                         'uid'         => $importer['uid'] ?? 0,
260                         'network'     => Protocol::FEED,
261                         'wall'        => 0,
262                         'origin'      => 0,
263                         'gravity'     => Item::GRAVITY_PARENT,
264                         'private'     => Item::PUBLIC,
265                         'verb'        => Activity::POST,
266                         'object-type' => Activity\ObjectType::NOTE,
267                         'post-type'   => Item::PT_ARTICLE,
268                         'contact-id'  => $contact['id'] ?? 0,
269                 ];
270
271                 $datarray['protocol'] = $protocol;
272                 $datarray['direction'] = Conversation::PULL;
273
274                 if (!is_object($entries)) {
275                         Logger::info("There are no entries in this feed.");
276                         return [];
277                 }
278
279                 $items = [];
280                 $creation_dates = [];
281
282                 // Limit the number of items that are about to be fetched
283                 $total_items = ($entries->length - 1);
284                 $max_items = DI::config()->get('system', 'max_feed_items');
285                 if (($max_items > 0) && ($total_items > $max_items)) {
286                         $total_items = $max_items;
287                 }
288
289                 $postings = [];
290
291                 // Importing older entries first
292                 for ($i = $total_items; $i >= 0; --$i) {
293                         $entry = $entries->item($i);
294
295                         $item = array_merge($header, $author);
296
297                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
298                         if (!is_object($alternate)) {
299                                 $alternate = XML::getFirstAttributes($xpath, 'atom:link', $entry);
300                         }
301                         if (is_object($alternate)) {
302                                 foreach ($alternate as $attribute) {
303                                         if ($attribute->name == 'href') {
304                                                 $item['plink'] = $attribute->textContent;
305                                         }
306                                 }
307                         }
308
309                         if (empty($item['plink'])) {
310                                 $item['plink'] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
311                         }
312
313                         if (empty($item['plink'])) {
314                                 $item['plink'] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
315                         }
316
317                         // Add the base path if missing
318                         $item['plink'] = Network::addBasePath($item['plink'], $basepath);
319
320                         $item['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
321
322                         $guid = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
323                         if (!empty($guid)) {
324                                 $item['uri'] = $guid;
325
326                                 // Don't use the GUID value directly but instead use it as a basis for the GUID
327                                 $item['guid'] = Item::guidFromUri($guid, parse_url($guid, PHP_URL_HOST) ?? parse_url($item['plink'], PHP_URL_HOST));
328                         }
329
330                         if (empty($item['uri'])) {
331                                 $item['uri'] = $item['plink'];
332                         }
333
334                         $orig_plink = $item['plink'];
335
336                         try {
337                                 $item['plink'] = DI::httpClient()->finalUrl($item['plink']);
338                         } catch (TransferException $exception) {
339                                 Logger::notice('Item URL couldn\'t get expanded', ['url' => $item['plink'], 'exception' => $exception]);
340                         }
341
342                         $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
343
344                         if (empty($item['title'])) {
345                                 $item['title'] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
346                         }
347
348                         if (empty($item['title'])) {
349                                 $item['title'] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
350                         }
351
352                         if (empty($item['title'])) {
353                                 $item['title'] = XML::getFirstNodeValue($xpath, 'itunes:title/text()', $entry);
354                         }
355
356                         $item['title'] = html_entity_decode($item['title'], ENT_QUOTES, 'UTF-8');
357
358                         $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
359
360                         if (empty($published)) {
361                                 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
362                         }
363
364                         if (empty($published)) {
365                                 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
366                         }
367
368                         $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
369
370                         if (empty($updated) && !empty($published)) {
371                                 $updated = $published;
372                         }
373
374                         if (empty($published) && !empty($updated)) {
375                                 $published = $updated;
376                         }
377
378                         if ($published != '') {
379                                 $item['created'] = trim($published);
380                         }
381
382                         if ($updated != '') {
383                                 $item['edited'] = trim($updated);
384                         }
385
386                         if (!$dryRun) {
387                                 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
388                                         $importer['uid'], $item['uri'], Protocol::FEED, Protocol::DFRN];
389                                 $previous = Post::selectFirst(['id', 'created'], $condition);
390                                 if (DBA::isResult($previous)) {
391                                         // Use the creation date when the post had been stored. It can happen this date changes in the feed.
392                                         $creation_dates[] = $previous['created'];
393                                         Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']);
394                                         continue;
395                                 }
396                                 $creation_dates[] = DateTimeFormat::utc($item['created']);
397                         }
398
399                         $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
400
401                         if (empty($creator)) {
402                                 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
403                         }
404
405                         if (empty($creator)) {
406                                 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
407                         }
408
409                         if ($creator != '') {
410                                 $item['author-name'] = $creator;
411                         }
412
413                         $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
414
415                         if ($creator != '') {
416                                 $item['author-name'] = $creator;
417                         }
418
419                         /// @TODO ?
420                         // <category>Ausland</category>
421                         // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
422
423                         $attachments = [];
424
425                         $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
426                         foreach ($enclosures as $enclosure) {
427                                 $href = '';
428                                 $length = null;
429                                 $type = null;
430
431                                 foreach ($enclosure->attributes as $attribute) {
432                                         if (in_array($attribute->name, ['url', 'href'])) {
433                                                 $href = $attribute->textContent;
434                                         } elseif ($attribute->name == 'length') {
435                                                 $length = (int)$attribute->textContent;
436                                         } elseif ($attribute->name == 'type') {
437                                                 $type = $attribute->textContent;
438                                         }
439                                 }
440
441                                 if (!empty($href)) {
442                                         $attachment = ['uri-id' => -1, 'type' => Post\Media::UNKNOWN, 'url' => $href, 'mimetype' => $type, 'size' => $length];
443
444                                         $attachment = Post\Media::fetchAdditionalData($attachment);
445
446                                         // By now we separate the visible media types (audio, video, image) from the rest
447                                         // In the future we should try to avoid the DOCUMENT type and only use the real one - but not in the RC phase.
448                                         if (!in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO])) {
449                                                 $attachment['type'] = Post\Media::DOCUMENT;
450                                         }
451                                         $attachments[] = $attachment;
452                                 }
453                         }
454
455                         $taglist = [];
456                         $categories = $xpath->query('category', $entry);
457                         foreach ($categories as $category) {
458                                 $taglist[] = $category->nodeValue;
459                         }
460
461                         $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
462
463                         if (empty($body)) {
464                                 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
465                         }
466
467                         $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
468
469                         if (empty($summary)) {
470                                 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
471                         }
472
473                         if (empty($body)) {
474                                 $body = $summary;
475                                 $summary = '';
476                         }
477
478                         if ($body == $summary) {
479                                 $summary = '';
480                         }
481
482                         // remove the content of the title if it is identically to the body
483                         // This helps with auto generated titles e.g. from tumblr
484                         if (self::titleIsBody($item['title'], $body)) {
485                                 $item['title'] = '';
486                         }
487                         $item['body'] = HTML::toBBCode($body, $basepath);
488
489                         // Remove tracking pixels
490                         $item['body'] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item['body']);
491
492                         if (($item['body'] == '') && ($item['title'] != '')) {
493                                 $item['body'] = $item['title'];
494                                 $item['title'] = '';
495                         }
496
497                         if ($dryRun) {
498                                 $item['attachments'] = $attachments;
499                                 $items[] = $item;
500                                 break;
501                         } elseif (!Item::isValid($item)) {
502                                 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
503                                 continue;
504                         } elseif (Item::isTooOld($item)) {
505                                 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
506                                 continue;
507                         }
508
509                         $preview = '';
510                         if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] < 3)) {
511                                 // Handle enclosures and treat them as preview picture
512                                 foreach ($attachments as $attachment) {
513                                         if ($attachment['mimetype'] == 'image/jpeg') {
514                                                 $preview = $attachment['url'];
515                                         }
516                                 }
517
518                                 // Remove a possible link to the item itself
519                                 $item['body'] = str_replace($item['plink'], '', $item['body']);
520                                 $item['body'] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item['body']));
521
522                                 // Replace the content when the title is longer than the body
523                                 $replace = (strlen($item['title']) > strlen($item['body']));
524
525                                 // Replace it, when there is an image in the body
526                                 if (strstr($item['body'], '[/img]')) {
527                                         $replace = true;
528                                 }
529
530                                 // Replace it, when there is a link in the body
531                                 if (strstr($item['body'], '[/url]')) {
532                                         $replace = true;
533                                 }
534
535                                 $saved_body = $item['body'];
536                                 $saved_title = $item['title'];
537
538                                 if ($replace) {
539                                         $item['body'] = trim($item['title']);
540                                 }
541
542                                 $data = ParseUrl::getSiteinfoCached($item['plink']);
543                                 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
544                                         // When the fetched page info text is longer than the body, we do try to enhance the body
545                                         if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
546                                                 // The body is not part of the fetched page info title or page info text. So we add the text to the body
547                                                 $item['body'] .= "\n\n" . $data['text'];
548                                         } else {
549                                                 // Else we replace the body with the page info text
550                                                 $item['body'] = $data['text'];
551                                         }
552                                 }
553
554                                 $data = PageInfo::queryUrl($item['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_denylist'] ?? '');
555
556                                 if (!empty($data)) {
557                                         // Take the data that was provided by the feed if the query is empty
558                                         if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
559                                                 $data['title'] = $saved_title;
560                                                 $item['body'] = $saved_body;
561                                         }
562
563                                         $data_text = strip_tags(trim($data['text'] ?? ''));
564                                         $item_body = strip_tags(trim($item['body'] ?? ''));
565
566                                         if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
567                                                 $data['text'] = '';
568                                         }
569
570                                         // We always strip the title since it will be added in the page information
571                                         $item['title'] = '';
572                                         $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false);
573                                         $taglist = $contact['fetch_further_information'] == 2 ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : [];
574                                         $item['object-type'] = Activity\ObjectType::BOOKMARK;
575                                         $attachments = [];
576
577                                         foreach (['audio', 'video'] as $elementname) {
578                                                 if (!empty($data[$elementname])) {
579                                                         foreach ($data[$elementname] as $element) {
580                                                                 if (!empty($element['src'])) {
581                                                                         $src = $element['src'];
582                                                                 } elseif (!empty($element['content'])) {
583                                                                         $src = $element['content'];
584                                                                 } else {
585                                                                         continue;
586                                                                 }
587
588                                                                 $attachments[] = [
589                                                                         'type'        => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
590                                                                         'url'         => $src,
591                                                                         'preview'     => $element['image']       ?? null,
592                                                                         'mimetype'    => $element['contenttype'] ?? null,
593                                                                         'name'        => $element['name']        ?? null,
594                                                                         'description' => $element['description'] ?? null,
595                                                                 ];
596                                                         }
597                                                 }
598                                         }
599                                 }
600                         } else {
601                                 if (!empty($summary)) {
602                                         $item['body'] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item['body'];
603                                 }
604
605                                 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] == 3)) {
606                                         if (empty($taglist)) {
607                                                 $taglist = PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '');
608                                         }
609                                         $item['body'] .= "\n" . self::tagToString($taglist);
610                                 } else {
611                                         $taglist = [];
612                                 }
613
614                                 // Add the link to the original feed entry if not present in feed
615                                 if (($item['plink'] != '') && !strstr($item['body'], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
616                                         $item['body'] .= '[hr][url]' . $item['plink'] . '[/url]';
617                                 }
618                         }
619
620                         if (empty($item['title'])) {
621                                 $item['post-type'] = Item::PT_NOTE;
622                         }
623
624                         Logger::info('Stored feed', ['item' => $item]);
625
626                         $notify = Item::isRemoteSelf($contact, $item);
627                         $item['wall'] = (bool)$notify;
628
629                         // Distributed items should have a well-formatted URI.
630                         // Additionally, we have to avoid conflicts with identical URI between imported feeds and these items.
631                         if ($notify) {
632                                 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHost());
633                                 $item['uri']  = Item::newURI($item['guid']);
634                                 unset($item['plink']);
635                                 unset($item['thr-parent']);
636                                 unset($item['parent-uri']);
637
638                                 // Set the delivery priority for "remote self" to "medium"
639                                 $notify = Worker::PRIORITY_MEDIUM;
640                         }
641
642                         $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
643                         if (!Post::exists($condition) && !Post\Delayed::exists($item['uri'], $item['uid'])) {
644                                 if (!$notify) {
645                                         Post\Delayed::publish($item, $notify, $taglist, $attachments);
646                                 } else {
647                                         $postings[] = ['item' => $item, 'notify' => $notify,
648                                                 'taglist' => $taglist, 'attachments' => $attachments];
649                                 }
650                         } else {
651                                 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]);
652                         }
653                 }
654
655                 if (!empty($postings)) {
656                         $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
657                         $total = count($postings);
658                         if ($total > 1) {
659                                 // Posts shouldn't be delayed more than a day
660                                 $interval = min(1440, self::getPollInterval($contact));
661                                 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
662                                 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
663                         } else {
664                                 $delay = 0;
665                         }
666
667                         $post_delay = 0;
668
669                         foreach ($postings as $posting) {
670                                 if ($delay > 0) {
671                                         $publish_time = time() + $post_delay;
672                                         $post_delay += $delay;
673                                 } else {
674                                         $publish_time = time();
675                                 }
676
677                                 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
678                                 $next_publish = max($last_publish + (60 * $min_posting), time());
679                                 if ($publish_time < $next_publish) {
680                                         $publish_time = $next_publish;
681                                 }
682                                 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
683
684                                 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
685                                         DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
686                                 }
687                         }
688                 }
689
690                 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
691                         self::adjustPollFrequency($contact, $creation_dates);
692                 }
693
694                 return ['header' => $author, 'items' => $items];
695         }
696
697         /**
698          * Automatically adjust the poll frequency according to the post frequency
699          *
700          * @param array $contact Contact array
701          * @param array $creation_dates
702          * @return void
703          */
704         private static function adjustPollFrequency(array $contact, array $creation_dates)
705         {
706                 if ($contact['network'] != Protocol::FEED) {
707                         Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
708                         return;
709                 }
710
711                 if (!empty($creation_dates)) {
712                         // Count the post frequency and the earliest and latest post date
713                         $frequency = [];
714                         $oldest = time();
715                         $newest = 0;
716                         $oldest_date = $newest_date = '';
717
718                         foreach ($creation_dates as $date) {
719                                 $timestamp = strtotime($date);
720                                 $day = intdiv($timestamp, 86400);
721                                 $hour = $timestamp % 86400;
722
723                                 // Only have a look at values from the last seven days
724                                 if (((time() / 86400) - $day) < 7) {
725                                         if (empty($frequency[$day])) {
726                                                 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
727                                         } else {
728                                                 ++$frequency[$day]['count'];
729                                                 if ($frequency[$day]['low'] > $hour) {
730                                                         $frequency[$day]['low'] = $hour;
731                                                 }
732                                                 if ($frequency[$day]['high'] < $hour) {
733                                                         $frequency[$day]['high'] = $hour;
734                                                 }
735                                         }
736                                 }
737                                 if ($oldest > $day) {
738                                         $oldest = $day;
739                                         $oldest_date = $date;
740                                 }
741
742                                 if ($newest < $day) {
743                                         $newest = $day;
744                                         $newest_date = $date;
745                                 }
746                         }
747
748                         if (count($creation_dates) == 1) {
749                                 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
750                                 $priority = 8; // Poll once a day
751                         }
752
753                         if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
754                                 Logger::info('Feed had not posted for two years, switching to monthly polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
755                                 $priority = 10; // Poll every month
756                         }
757
758                         if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
759                                 Logger::info('Feed had not posted for a year, switching to weekly polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
760                                 $priority = 9; // Poll every week
761                         }
762
763                         if (empty($priority) && empty($frequency)) {
764                                 Logger::info('Feed had not posted for at least a week, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
765                                 $priority = 8; // Poll once a day
766                         }
767
768                         if (empty($priority)) {
769                                 // Calculate the highest "posts per day" value
770                                 $max = 0;
771                                 foreach ($frequency as $entry) {
772                                         if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
773                                                 continue;
774                                         }
775
776                                         // We take the earliest and latest post day and interpolate the number of post per day
777                                         // that would had been created with this post frequency
778
779                                         // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
780                                         $duration = max($entry['high'] - $entry['low'], 14400);
781                                         $ppd = (86400 / $duration) * $entry['count'];
782                                         if ($ppd > $max) {
783                                                 $max = $ppd;
784                                         }
785                                 }
786                                 if ($max > 48) {
787                                         $priority = 1; // Poll every quarter hour
788                                 } elseif ($max > 24) {
789                                         $priority = 2; // Poll half an hour
790                                 } elseif ($max > 12) {
791                                         $priority = 3; // Poll hourly
792                                 } elseif ($max > 8) {
793                                         $priority = 4; // Poll every two hours
794                                 } elseif ($max > 4) {
795                                         $priority = 5; // Poll every three hours
796                                 } elseif ($max > 2) {
797                                         $priority = 6; // Poll every six hours
798                                 } else {
799                                         $priority = 7; // Poll twice a day
800                                 }
801                                 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
802                         }
803                 } else {
804                         Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
805                         $priority = 8; // Poll once a day
806                 }
807
808                 if ($contact['rating'] != $priority) {
809                         Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
810                         Contact::update(['rating' => $priority], ['id' => $contact['id']]);
811                 }
812         }
813
814         /**
815          * Get the poll interval for the given contact array
816          *
817          * @param array $contact
818          * @return int Poll interval in minutes
819          */
820         public static function getPollInterval(array $contact): int
821         {
822                 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
823                         $ratings = [0, 3, 7, 8, 9, 10];
824                         if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
825                                 $rating = $contact['rating'];
826                         } elseif (array_key_exists($contact['priority'], $ratings)) {
827                                 $rating = $ratings[$contact['priority']];
828                         } else {
829                                 $rating = -1;
830                         }
831                 } else {
832                         // Check once a week per default for all other networks
833                         $rating = 9;
834                 }
835
836                 // Friendica and OStatus are checked once a day
837                 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
838                         $rating = 8;
839                 }
840
841                 // Check archived contacts or contacts with unsupported protocols once a month
842                 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
843                         $rating = 10;
844                 }
845
846                 if ($rating < 0) {
847                         return 0;
848                 }
849                 /*
850                  * Based on $contact['priority'], should we poll this site now? Or later?
851                  */
852
853                 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
854
855                 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
856
857                 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
858                 //      '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
859
860                 return $poll_intervals[$rating];
861         }
862
863         /**
864          * Convert a tag array to a tag string
865          *
866          * @param array $tags
867          * @return string tag string
868          */
869         private static function tagToString(array $tags): string
870         {
871                 $tagstr = '';
872
873                 foreach ($tags as $tag) {
874                         if ($tagstr != '') {
875                                 $tagstr .= ', ';
876                         }
877
878                         $tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
879                 }
880
881                 return $tagstr;
882         }
883
884         private static function titleIsBody(string $title, string $body): bool
885         {
886                 $title = strip_tags($title);
887                 $title = trim($title);
888                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
889                 $title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
890
891                 $body = strip_tags($body);
892                 $body = trim($body);
893                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
894                 $body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
895
896                 if (strlen($title) < strlen($body)) {
897                         $body = substr($body, 0, strlen($title));
898                 }
899
900                 if (($title != $body) && (substr($title, -3) == '...')) {
901                         $pos = strrpos($title, '...');
902                         if ($pos > 0) {
903                                 $title = substr($title, 0, $pos);
904                                 $body = substr($body, 0, $pos);
905                         }
906                 }
907                 return ($title == $body);
908         }
909
910         /**
911          * Creates the Atom feed for a given nickname
912          *
913          * Supported filters:
914          * - activity (default): all the public posts
915          * - posts: all the public top-level posts
916          * - comments: all the public replies
917          *
918          * Updates the provided last_update parameter if the result comes from the
919          * cache or it is empty
920          *
921          * @param array   $owner       owner-view record of the feed owner
922          * @param string  $last_update Date of the last update
923          * @param integer $max_items   Number of maximum items to fetch
924          * @param string  $filter      Feed items filter (activity, posts or comments)
925          * @param boolean $nocache     Wether to bypass caching
926          *
927          * @return string Atom feed
928          * @throws HTTPException\InternalServerErrorException
929          * @throws \ImagickException
930          */
931         public static function atom(array $owner, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
932         {
933                 $stamp = microtime(true);
934
935                 $cachekey = 'feed:feed:' . $owner['nickname'] . ':' . $filter . ':' . $last_update;
936
937                 // Display events in the user's timezone
938                 if (strlen($owner['timezone'])) {
939                         DI::app()->setTimeZone($owner['timezone']);
940                 }
941
942                 $previous_created = $last_update;
943
944                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
945                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
946                         $result = DI::cache()->get($cachekey);
947                         if (!$nocache && !is_null($result)) {
948                                 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
949                                 return $result['feed'];
950                         }
951                 }
952
953                 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
954                 $authorid = Contact::getIdForURL($owner['url']);
955
956                 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
957                         AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
958                         $owner['uid'], $check_date, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT,
959                         Item::PRIVATE, Protocol::ACTIVITYPUB,
960                         Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
961
962                 if ($filter === 'comments') {
963                         $condition[0] .= " AND `gravity` = ? ";
964                         $condition[] = Item::GRAVITY_COMMENT;
965                 }
966
967                 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
968                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
969                         $condition[] = $owner['id'];
970                         $condition[] = $authorid;
971                 }
972
973                 $params = ['order' => ['received' => true], 'limit' => $max_items];
974
975                 if ($filter === 'posts') {
976                         $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
977                 } else {
978                         $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
979                 }
980
981                 $items = Post::toArray($ret);
982
983                 $doc = new DOMDocument('1.0', 'utf-8');
984                 $doc->formatOutput = true;
985
986                 $root = self::addHeader($doc, $owner, $filter);
987
988                 foreach ($items as $item) {
989                         $entry = self::noteEntry($doc, $item, $owner);
990                         $root->appendChild($entry);
991
992                         if ($last_update < $item['created']) {
993                                 $last_update = $item['created'];
994                         }
995                 }
996
997                 $feeddata = trim($doc->saveXML());
998
999                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
1000                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1001
1002                 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
1003
1004                 return $feeddata;
1005         }
1006
1007         /**
1008          * Adds the header elements to the XML document
1009          *
1010          * @param DOMDocument $doc       XML document
1011          * @param array       $owner     Contact data of the poster
1012          * @param string      $filter    The related feed filter (activity, posts or comments)
1013          *
1014          * @return DOMElement Header root element
1015          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1016          */
1017         private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1018         {
1019                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1020                 $doc->appendChild($root);
1021
1022                 $title = '';
1023                 $selfUri = '/feed/' . $owner['nick'] . '/';
1024                 switch ($filter) {
1025                         case 'activity':
1026                                 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1027                                 $selfUri .= $filter;
1028                                 break;
1029                         case 'posts':
1030                                 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1031                                 break;
1032                         case 'comments':
1033                                 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1034                                 $selfUri .= $filter;
1035                                 break;
1036                 }
1037
1038                 $attributes = ['uri' => 'https://friendi.ca', 'version' => App::VERSION . '-' . DB_UPDATE_VERSION];
1039                 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1040                 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1041                 XML::addElement($doc, $root, 'title', $title);
1042                 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1043                 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1044                 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1045
1046                 $author = self::addAuthor($doc, $owner);
1047                 $root->appendChild($author);
1048
1049                 $attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
1050                 XML::addElement($doc, $root, 'link', '', $attributes);
1051
1052                 OStatus::addHubLink($doc, $root, $owner['nick']);
1053
1054                 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1055                 XML::addElement($doc, $root, 'link', '', $attributes);
1056
1057                 return $root;
1058         }
1059
1060         /**
1061          * Adds the author element to the XML document
1062          *
1063          * @param DOMDocument $doc          XML document
1064          * @param array       $owner        Contact data of the poster
1065          * @return DOMElement author element
1066          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1067          */
1068         private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
1069         {
1070                 $author = $doc->createElement('author');
1071                 XML::addElement($doc, $author, 'uri', $owner['url']);
1072                 XML::addElement($doc, $author, 'name', $owner['nick']);
1073                 XML::addElement($doc, $author, 'email', $owner['addr']);
1074
1075                 return $author;
1076         }
1077
1078         /**
1079          * Adds a regular entry element
1080          *
1081          * @param DOMDocument $doc       XML document
1082          * @param array       $item      Data of the item that is to be posted
1083          * @param array       $owner     Contact data of the poster
1084          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
1085          * @return DOMElement Entry element
1086          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1087          * @throws \ImagickException
1088          */
1089         private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
1090         {
1091                 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1092                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
1093                 }
1094
1095                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1096
1097                 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1098
1099                 self::entryFooter($doc, $entry, $item, $owner);
1100
1101                 return $entry;
1102         }
1103
1104         /**
1105          * Adds elements to the XML document
1106          *
1107          * @param DOMDocument $doc       XML document
1108          * @param \DOMElement $entry     Entry element where the content is added
1109          * @param array       $item      Data of the item that is to be posted
1110          * @param array       $owner     Contact data of the poster
1111          * @param string      $title     Title for the post
1112          * @param string      $verb      The activity verb
1113          * @param bool        $complete  Add the "status_net" element?
1114          * @return void
1115          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1116          */
1117         private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
1118         {
1119                 if ($verb == '') {
1120                         $verb = OStatus::constructVerb($item);
1121                 }
1122
1123                 XML::addElement($doc, $entry, 'id', $item['uri']);
1124                 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1125
1126                 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
1127                 $body = Post\Media::addHTMLAttachmentToBody($item['uri-id'], $body);
1128
1129                 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1130
1131                 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1132
1133                 XML::addElement($doc, $entry, 'link', '', ['rel' => 'alternate', 'type' => 'text/html',
1134                                                                 'href' => DI::baseUrl() . '/display/' . $item['guid']]
1135                 );
1136
1137                 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1138                 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1139         }
1140
1141         /**
1142          * Adds the elements at the foot of an entry to the XML document
1143          *
1144          * @param DOMDocument $doc       XML document
1145          * @param object      $entry     The entry element where the elements are added
1146          * @param array       $item      Data of the item that is to be posted
1147          * @param array       $owner     Contact data of the poster
1148          * @param bool        $complete  default true
1149          * @return void
1150          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1151          */
1152         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1153         {
1154                 $mentioned = [];
1155
1156                 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1157                         $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1158
1159                         $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1160
1161                         if (DBA::isResult($thrparent)) {
1162                                 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1163                                 $mentioned[$thrparent['owner-link']]  = $thrparent['owner-link'];
1164                                 $parent_plink                         = $thrparent['plink'];
1165                         } elseif (DBA::isResult($parent)) {
1166                                 $mentioned[$parent['author-link']] = $parent['author-link'];
1167                                 $mentioned[$parent['owner-link']]  = $parent['owner-link'];
1168                                 $parent_plink                      = DI::baseUrl() . '/display/' . $parent['guid'];
1169                         } else {
1170                                 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1171                         }
1172
1173                         if (isset($parent_plink)) {
1174                                 $attributes = [
1175                                         'ref'  => $item['thr-parent'],
1176                                         'href' => $parent_plink];
1177                                 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1178
1179                                 $attributes = [
1180                                         'rel'  => 'related',
1181                                         'href' => $parent_plink];
1182                                 XML::addElement($doc, $entry, 'link', '', $attributes);
1183                         }
1184                 }
1185
1186                 // uri-id isn't present for follow entry pseudo-items
1187                 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1188                 foreach ($tags as $tag) {
1189                         $mentioned[$tag['url']] = $tag['url'];
1190                 }
1191
1192                 foreach ($tags as $tag) {
1193                         if ($tag['type'] == Tag::HASHTAG) {
1194                                 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1195                         }
1196                 }
1197
1198                 OStatus::getAttachment($doc, $entry, $item);
1199         }
1200
1201         /**
1202          * Fetch or create title for feed entry
1203          *
1204          * @param array $item
1205          * @return string title
1206          */
1207         private static function getTitle(array $item): string
1208         {
1209                 if ($item['title'] != '') {
1210                         return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1211                 }
1212
1213                 // Fetch information about the post
1214                 $siteinfo = BBCode::getAttachedData($item['body']);
1215                 if (isset($siteinfo['title'])) {
1216                         return $siteinfo['title'];
1217                 }
1218
1219                 // If no bookmark is found then take the first line
1220                 // Remove the share element before fetching the first line
1221                 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
1222
1223                 $title = BBCode::toPlaintext($title)."\n";
1224                 $pos = strpos($title, "\n");
1225                 $trailer = '';
1226                 if (($pos == 0) || ($pos > 100)) {
1227                         $pos = 100;
1228                         $trailer = '...';
1229                 }
1230
1231                 return substr($title, 0, $pos) . $trailer;
1232         }
1233 }