]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
Merge branch '2023.03-rc' into stable
[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 = [
388                                         "`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
389                                         $importer['uid'], $item['uri'], Protocol::FEED, Protocol::DFRN
390                                 ];
391                                 $previous = Post::selectFirst(['id', 'created'], $condition);
392                                 if (DBA::isResult($previous)) {
393                                         // Use the creation date when the post had been stored. It can happen this date changes in the feed.
394                                         $creation_dates[] = $previous['created'];
395                                         Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']);
396                                         continue;
397                                 }
398                                 $creation_dates[] = DateTimeFormat::utc($item['created']);
399                         }
400
401                         $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
402
403                         if (empty($creator)) {
404                                 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
405                         }
406
407                         if (empty($creator)) {
408                                 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
409                         }
410
411                         if ($creator != '') {
412                                 $item['author-name'] = $creator;
413                         }
414
415                         $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
416
417                         if ($creator != '') {
418                                 $item['author-name'] = $creator;
419                         }
420
421                         /// @TODO ?
422                         // <category>Ausland</category>
423                         // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
424
425                         $attachments = [];
426
427                         $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
428                         foreach ($enclosures as $enclosure) {
429                                 $href = '';
430                                 $length = null;
431                                 $type = null;
432
433                                 foreach ($enclosure->attributes as $attribute) {
434                                         if (in_array($attribute->name, ['url', 'href'])) {
435                                                 $href = $attribute->textContent;
436                                         } elseif ($attribute->name == 'length') {
437                                                 $length = (int)$attribute->textContent;
438                                         } elseif ($attribute->name == 'type') {
439                                                 $type = $attribute->textContent;
440                                         }
441                                 }
442
443                                 if (!empty($href)) {
444                                         $attachment = ['uri-id' => -1, 'type' => Post\Media::UNKNOWN, 'url' => $href, 'mimetype' => $type, 'size' => $length];
445
446                                         $attachment = Post\Media::fetchAdditionalData($attachment);
447
448                                         // By now we separate the visible media types (audio, video, image) from the rest
449                                         // In the future we should try to avoid the DOCUMENT type and only use the real one - but not in the RC phase.
450                                         if (!in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO])) {
451                                                 $attachment['type'] = Post\Media::DOCUMENT;
452                                         }
453                                         $attachments[] = $attachment;
454                                 }
455                         }
456
457                         $taglist = [];
458                         $categories = $xpath->query('category', $entry);
459                         foreach ($categories as $category) {
460                                 $taglist[] = $category->nodeValue;
461                         }
462
463                         $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
464
465                         if (empty($body)) {
466                                 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
467                         }
468
469                         $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
470
471                         if (empty($summary)) {
472                                 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
473                         }
474
475                         if (empty($body)) {
476                                 $body = $summary;
477                                 $summary = '';
478                         }
479
480                         if ($body == $summary) {
481                                 $summary = '';
482                         }
483
484                         // remove the content of the title if it is identically to the body
485                         // This helps with auto generated titles e.g. from tumblr
486                         if (self::titleIsBody($item['title'], $body)) {
487                                 $item['title'] = '';
488                         }
489                         $item['body'] = HTML::toBBCode($body, $basepath);
490
491                         // Remove tracking pixels
492                         $item['body'] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item['body']);
493
494                         if (($item['body'] == '') && ($item['title'] != '')) {
495                                 $item['body'] = $item['title'];
496                                 $item['title'] = '';
497                         }
498
499                         if ($dryRun) {
500                                 $item['attachments'] = $attachments;
501                                 $items[] = $item;
502                                 break;
503                         } elseif (!Item::isValid($item)) {
504                                 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
505                                 continue;
506                         } elseif (Item::isTooOld($item)) {
507                                 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
508                                 continue;
509                         }
510
511                         $preview = '';
512                         if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] < 3)) {
513                                 // Handle enclosures and treat them as preview picture
514                                 foreach ($attachments as $attachment) {
515                                         if ($attachment['mimetype'] == 'image/jpeg') {
516                                                 $preview = $attachment['url'];
517                                         }
518                                 }
519
520                                 // Remove a possible link to the item itself
521                                 $item['body'] = str_replace($item['plink'], '', $item['body']);
522                                 $item['body'] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item['body']));
523
524                                 // Replace the content when the title is longer than the body
525                                 $replace = (strlen($item['title']) > strlen($item['body']));
526
527                                 // Replace it, when there is an image in the body
528                                 if (strstr($item['body'], '[/img]')) {
529                                         $replace = true;
530                                 }
531
532                                 // Replace it, when there is a link in the body
533                                 if (strstr($item['body'], '[/url]')) {
534                                         $replace = true;
535                                 }
536
537                                 $saved_body = $item['body'];
538                                 $saved_title = $item['title'];
539
540                                 if ($replace) {
541                                         $item['body'] = trim($item['title']);
542                                 }
543
544                                 $data = ParseUrl::getSiteinfoCached($item['plink']);
545                                 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
546                                         // When the fetched page info text is longer than the body, we do try to enhance the body
547                                         if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
548                                                 // The body is not part of the fetched page info title or page info text. So we add the text to the body
549                                                 $item['body'] .= "\n\n" . $data['text'];
550                                         } else {
551                                                 // Else we replace the body with the page info text
552                                                 $item['body'] = $data['text'];
553                                         }
554                                 }
555
556                                 $data = PageInfo::queryUrl($item['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_denylist'] ?? '');
557
558                                 if (!empty($data)) {
559                                         // Take the data that was provided by the feed if the query is empty
560                                         if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
561                                                 $data['title'] = $saved_title;
562                                                 $item['body'] = $saved_body;
563                                         }
564
565                                         $data_text = strip_tags(trim($data['text'] ?? ''));
566                                         $item_body = strip_tags(trim($item['body'] ?? ''));
567
568                                         if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
569                                                 $data['text'] = '';
570                                         }
571
572                                         // We always strip the title since it will be added in the page information
573                                         $item['title'] = '';
574                                         $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false);
575                                         $taglist = $contact['fetch_further_information'] == 2 ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : [];
576                                         $item['object-type'] = Activity\ObjectType::BOOKMARK;
577                                         $attachments = [];
578
579                                         foreach (['audio', 'video'] as $elementname) {
580                                                 if (!empty($data[$elementname])) {
581                                                         foreach ($data[$elementname] as $element) {
582                                                                 if (!empty($element['src'])) {
583                                                                         $src = $element['src'];
584                                                                 } elseif (!empty($element['content'])) {
585                                                                         $src = $element['content'];
586                                                                 } else {
587                                                                         continue;
588                                                                 }
589
590                                                                 $attachments[] = [
591                                                                         'type'        => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
592                                                                         'url'         => $src,
593                                                                         'preview'     => $element['image']       ?? null,
594                                                                         'mimetype'    => $element['contenttype'] ?? null,
595                                                                         'name'        => $element['name']        ?? null,
596                                                                         'description' => $element['description'] ?? null,
597                                                                 ];
598                                                         }
599                                                 }
600                                         }
601                                 }
602                         } else {
603                                 if (!empty($summary)) {
604                                         $item['body'] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item['body'];
605                                 }
606
607                                 if (!empty($contact['fetch_further_information']) && ($contact['fetch_further_information'] == 3)) {
608                                         if (empty($taglist)) {
609                                                 $taglist = PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '');
610                                         }
611                                         $item['body'] .= "\n" . self::tagToString($taglist);
612                                 } else {
613                                         $taglist = [];
614                                 }
615
616                                 // Add the link to the original feed entry if not present in feed
617                                 if (($item['plink'] != '') && !strstr($item['body'], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
618                                         $item['body'] .= '[hr][url]' . $item['plink'] . '[/url]';
619                                 }
620                         }
621
622                         if (empty($item['title'])) {
623                                 $item['post-type'] = Item::PT_NOTE;
624                         }
625
626                         Logger::info('Stored feed', ['item' => $item]);
627
628                         $notify = Item::isRemoteSelf($contact, $item);
629                         $item['wall'] = (bool)$notify;
630
631                         // Distributed items should have a well-formatted URI.
632                         // Additionally, we have to avoid conflicts with identical URI between imported feeds and these items.
633                         if ($notify) {
634                                 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHost());
635                                 $item['uri']  = Item::newURI($item['guid']);
636                                 unset($item['plink']);
637                                 unset($item['thr-parent']);
638                                 unset($item['parent-uri']);
639
640                                 // Set the delivery priority for "remote self" to "medium"
641                                 $notify = Worker::PRIORITY_MEDIUM;
642                         }
643
644                         $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
645                         if (!Post::exists($condition) && !Post\Delayed::exists($item['uri'], $item['uid'])) {
646                                 if (!$notify) {
647                                         Post\Delayed::publish($item, $notify, $taglist, $attachments);
648                                 } else {
649                                         $postings[] = [
650                                                 'item' => $item, 'notify' => $notify,
651                                                 'taglist' => $taglist, 'attachments' => $attachments
652                                         ];
653                                 }
654                         } else {
655                                 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]);
656                         }
657                 }
658
659                 if (!empty($postings)) {
660                         $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
661                         $total = count($postings);
662                         if ($total > 1) {
663                                 // Posts shouldn't be delayed more than a day
664                                 $interval = min(1440, self::getPollInterval($contact));
665                                 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
666                                 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
667                         } else {
668                                 $delay = 0;
669                         }
670
671                         $post_delay = 0;
672
673                         foreach ($postings as $posting) {
674                                 if ($delay > 0) {
675                                         $publish_time = time() + $post_delay;
676                                         $post_delay += $delay;
677                                 } else {
678                                         $publish_time = time();
679                                 }
680
681                                 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
682                                 $next_publish = max($last_publish + (60 * $min_posting), time());
683                                 if ($publish_time < $next_publish) {
684                                         $publish_time = $next_publish;
685                                 }
686                                 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
687
688                                 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
689                                         DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
690                                 }
691                         }
692                 }
693
694                 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
695                         self::adjustPollFrequency($contact, $creation_dates);
696                 }
697
698                 return ['header' => $author, 'items' => $items];
699         }
700
701         /**
702          * Automatically adjust the poll frequency according to the post frequency
703          *
704          * @param array $contact Contact array
705          * @param array $creation_dates
706          * @return void
707          */
708         private static function adjustPollFrequency(array $contact, array $creation_dates)
709         {
710                 if ($contact['network'] != Protocol::FEED) {
711                         Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
712                         return;
713                 }
714
715                 if (!empty($creation_dates)) {
716                         // Count the post frequency and the earliest and latest post date
717                         $frequency = [];
718                         $oldest = time();
719                         $newest = 0;
720                         $oldest_date = $newest_date = '';
721
722                         foreach ($creation_dates as $date) {
723                                 $timestamp = strtotime($date);
724                                 $day = intdiv($timestamp, 86400);
725                                 $hour = $timestamp % 86400;
726
727                                 // Only have a look at values from the last seven days
728                                 if (((time() / 86400) - $day) < 7) {
729                                         if (empty($frequency[$day])) {
730                                                 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
731                                         } else {
732                                                 ++$frequency[$day]['count'];
733                                                 if ($frequency[$day]['low'] > $hour) {
734                                                         $frequency[$day]['low'] = $hour;
735                                                 }
736                                                 if ($frequency[$day]['high'] < $hour) {
737                                                         $frequency[$day]['high'] = $hour;
738                                                 }
739                                         }
740                                 }
741                                 if ($oldest > $day) {
742                                         $oldest = $day;
743                                         $oldest_date = $date;
744                                 }
745
746                                 if ($newest < $day) {
747                                         $newest = $day;
748                                         $newest_date = $date;
749                                 }
750                         }
751
752                         if (count($creation_dates) == 1) {
753                                 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
754                                 $priority = 8; // Poll once a day
755                         }
756
757                         if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
758                                 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']]);
759                                 $priority = 10; // Poll every month
760                         }
761
762                         if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
763                                 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']]);
764                                 $priority = 9; // Poll every week
765                         }
766
767                         if (empty($priority) && empty($frequency)) {
768                                 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']]);
769                                 $priority = 8; // Poll once a day
770                         }
771
772                         if (empty($priority)) {
773                                 // Calculate the highest "posts per day" value
774                                 $max = 0;
775                                 foreach ($frequency as $entry) {
776                                         if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
777                                                 continue;
778                                         }
779
780                                         // We take the earliest and latest post day and interpolate the number of post per day
781                                         // that would had been created with this post frequency
782
783                                         // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
784                                         $duration = max($entry['high'] - $entry['low'], 14400);
785                                         $ppd = (86400 / $duration) * $entry['count'];
786                                         if ($ppd > $max) {
787                                                 $max = $ppd;
788                                         }
789                                 }
790                                 if ($max > 48) {
791                                         $priority = 1; // Poll every quarter hour
792                                 } elseif ($max > 24) {
793                                         $priority = 2; // Poll half an hour
794                                 } elseif ($max > 12) {
795                                         $priority = 3; // Poll hourly
796                                 } elseif ($max > 8) {
797                                         $priority = 4; // Poll every two hours
798                                 } elseif ($max > 4) {
799                                         $priority = 5; // Poll every three hours
800                                 } elseif ($max > 2) {
801                                         $priority = 6; // Poll every six hours
802                                 } else {
803                                         $priority = 7; // Poll twice a day
804                                 }
805                                 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
806                         }
807                 } else {
808                         Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
809                         $priority = 8; // Poll once a day
810                 }
811
812                 if ($contact['rating'] != $priority) {
813                         Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
814                         Contact::update(['rating' => $priority], ['id' => $contact['id']]);
815                 }
816         }
817
818         /**
819          * Get the poll interval for the given contact array
820          *
821          * @param array $contact
822          * @return int Poll interval in minutes
823          */
824         public static function getPollInterval(array $contact): int
825         {
826                 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
827                         $ratings = [0, 3, 7, 8, 9, 10];
828                         if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
829                                 $rating = $contact['rating'];
830                         } elseif (array_key_exists($contact['priority'], $ratings)) {
831                                 $rating = $ratings[$contact['priority']];
832                         } else {
833                                 $rating = -1;
834                         }
835                 } else {
836                         // Check once a week per default for all other networks
837                         $rating = 9;
838                 }
839
840                 // Friendica and OStatus are checked once a day
841                 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
842                         $rating = 8;
843                 }
844
845                 // Check archived contacts or contacts with unsupported protocols once a month
846                 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
847                         $rating = 10;
848                 }
849
850                 if ($rating < 0) {
851                         return 0;
852                 }
853                 /*
854                  * Based on $contact['priority'], should we poll this site now? Or later?
855                  */
856
857                 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
858
859                 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720, 1440, 10080, 43200];
860
861                 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
862                 //      '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
863
864                 return $poll_intervals[$rating];
865         }
866
867         /**
868          * Convert a tag array to a tag string
869          *
870          * @param array $tags
871          * @return string tag string
872          */
873         private static function tagToString(array $tags): string
874         {
875                 $tagstr = '';
876
877                 foreach ($tags as $tag) {
878                         if ($tagstr != '') {
879                                 $tagstr .= ', ';
880                         }
881
882                         $tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
883                 }
884
885                 return $tagstr;
886         }
887
888         private static function titleIsBody(string $title, string $body): bool
889         {
890                 $title = strip_tags($title);
891                 $title = trim($title);
892                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
893                 $title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
894
895                 $body = strip_tags($body);
896                 $body = trim($body);
897                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
898                 $body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
899
900                 if (strlen($title) < strlen($body)) {
901                         $body = substr($body, 0, strlen($title));
902                 }
903
904                 if (($title != $body) && (substr($title, -3) == '...')) {
905                         $pos = strrpos($title, '...');
906                         if ($pos > 0) {
907                                 $title = substr($title, 0, $pos);
908                                 $body = substr($body, 0, $pos);
909                         }
910                 }
911                 return ($title == $body);
912         }
913
914         /**
915          * Creates the Atom feed for a given nickname
916          *
917          * Supported filters:
918          * - activity (default): all the public posts
919          * - posts: all the public top-level posts
920          * - comments: all the public replies
921          *
922          * Updates the provided last_update parameter if the result comes from the
923          * cache or it is empty
924          *
925          * @param array   $owner       owner-view record of the feed owner
926          * @param string  $last_update Date of the last update
927          * @param integer $max_items   Number of maximum items to fetch
928          * @param string  $filter      Feed items filter (activity, posts or comments)
929          * @param boolean $nocache     Wether to bypass caching
930          *
931          * @return string Atom feed
932          * @throws HTTPException\InternalServerErrorException
933          * @throws \ImagickException
934          */
935         public static function atom(array $owner, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
936         {
937                 $stamp = microtime(true);
938
939                 $cachekey = 'feed:feed:' . $owner['nickname'] . ':' . $filter . ':' . $last_update;
940
941                 // Display events in the user's timezone
942                 if (strlen($owner['timezone'])) {
943                         DI::app()->setTimeZone($owner['timezone']);
944                 }
945
946                 $previous_created = $last_update;
947
948                 // Don't cache when the last item was posted less than 15 minutes ago (Cache duration)
949                 if ((time() - strtotime($owner['last-item'])) < 15 * 60) {
950                         $result = DI::cache()->get($cachekey);
951                         if (!$nocache && !is_null($result)) {
952                                 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
953                                 return $result['feed'];
954                         }
955                 }
956
957                 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
958                 $authorid = Contact::getIdForURL($owner['url']);
959
960                 $condition = [
961                         "`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
962                         AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
963                         $owner['uid'], $check_date, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT,
964                         Item::PRIVATE, Protocol::ACTIVITYPUB,
965                         Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA
966                 ];
967
968                 if ($filter === 'comments') {
969                         $condition[0] .= " AND `gravity` = ? ";
970                         $condition[] = Item::GRAVITY_COMMENT;
971                 }
972
973                 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
974                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
975                         $condition[] = $owner['id'];
976                         $condition[] = $authorid;
977                 }
978
979                 $params = ['order' => ['received' => true], 'limit' => $max_items];
980
981                 if ($filter === 'posts') {
982                         $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
983                 } else {
984                         $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
985                 }
986
987                 $items = Post::toArray($ret);
988
989                 $doc = new DOMDocument('1.0', 'utf-8');
990                 $doc->formatOutput = true;
991
992                 $root = self::addHeader($doc, $owner, $filter);
993
994                 foreach ($items as $item) {
995                         $entry = self::noteEntry($doc, $item, $owner);
996                         $root->appendChild($entry);
997
998                         if ($last_update < $item['created']) {
999                                 $last_update = $item['created'];
1000                         }
1001                 }
1002
1003                 $feeddata = trim($doc->saveXML());
1004
1005                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
1006                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1007
1008                 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
1009
1010                 return $feeddata;
1011         }
1012
1013         /**
1014          * Adds the header elements to the XML document
1015          *
1016          * @param DOMDocument $doc       XML document
1017          * @param array       $owner     Contact data of the poster
1018          * @param string      $filter    The related feed filter (activity, posts or comments)
1019          *
1020          * @return DOMElement Header root element
1021          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1022          */
1023         private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1024         {
1025                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1026                 $doc->appendChild($root);
1027
1028                 $title = '';
1029                 $selfUri = '/feed/' . $owner['nick'] . '/';
1030                 switch ($filter) {
1031                         case 'activity':
1032                                 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1033                                 $selfUri .= $filter;
1034                                 break;
1035                         case 'posts':
1036                                 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1037                                 break;
1038                         case 'comments':
1039                                 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1040                                 $selfUri .= $filter;
1041                                 break;
1042                 }
1043
1044                 $attributes = ['uri' => 'https://friendi.ca', 'version' => App::VERSION . '-' . DB_UPDATE_VERSION];
1045                 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1046                 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1047                 XML::addElement($doc, $root, 'title', $title);
1048                 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1049                 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1050                 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1051
1052                 $author = self::addAuthor($doc, $owner);
1053                 $root->appendChild($author);
1054
1055                 $attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
1056                 XML::addElement($doc, $root, 'link', '', $attributes);
1057
1058                 OStatus::addHubLink($doc, $root, $owner['nick']);
1059
1060                 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1061                 XML::addElement($doc, $root, 'link', '', $attributes);
1062
1063                 return $root;
1064         }
1065
1066         /**
1067          * Adds the author element to the XML document
1068          *
1069          * @param DOMDocument $doc          XML document
1070          * @param array       $owner        Contact data of the poster
1071          * @return DOMElement author element
1072          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1073          */
1074         private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
1075         {
1076                 $author = $doc->createElement('author');
1077                 XML::addElement($doc, $author, 'uri', $owner['url']);
1078                 XML::addElement($doc, $author, 'name', $owner['nick']);
1079                 XML::addElement($doc, $author, 'email', $owner['addr']);
1080
1081                 return $author;
1082         }
1083
1084         /**
1085          * Adds a regular entry element
1086          *
1087          * @param DOMDocument $doc       XML document
1088          * @param array       $item      Data of the item that is to be posted
1089          * @param array       $owner     Contact data of the poster
1090          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
1091          * @return DOMElement Entry element
1092          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1093          * @throws \ImagickException
1094          */
1095         private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
1096         {
1097                 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1098                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
1099                 }
1100
1101                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1102
1103                 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1104
1105                 self::entryFooter($doc, $entry, $item, $owner);
1106
1107                 return $entry;
1108         }
1109
1110         /**
1111          * Adds elements to the XML document
1112          *
1113          * @param DOMDocument $doc       XML document
1114          * @param \DOMElement $entry     Entry element where the content is added
1115          * @param array       $item      Data of the item that is to be posted
1116          * @param array       $owner     Contact data of the poster
1117          * @param string      $title     Title for the post
1118          * @param string      $verb      The activity verb
1119          * @param bool        $complete  Add the "status_net" element?
1120          * @return void
1121          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1122          */
1123         private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
1124         {
1125                 if ($verb == '') {
1126                         $verb = OStatus::constructVerb($item);
1127                 }
1128
1129                 XML::addElement($doc, $entry, 'id', $item['uri']);
1130                 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1131
1132                 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
1133                 $body = Post\Media::addHTMLLinkToBody($item['uri-id'], $body);
1134
1135                 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1136
1137                 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1138
1139                 XML::addElement(
1140                         $doc,
1141                         $entry,
1142                         'link',
1143                         '',
1144                         [
1145                                 'rel' => 'alternate', 'type' => 'text/html',
1146                                 'href' => DI::baseUrl() . '/display/' . $item['guid']
1147                         ]
1148                 );
1149
1150                 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1151                 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1152         }
1153
1154         /**
1155          * Adds the elements at the foot of an entry to the XML document
1156          *
1157          * @param DOMDocument $doc       XML document
1158          * @param object      $entry     The entry element where the elements are added
1159          * @param array       $item      Data of the item that is to be posted
1160          * @param array       $owner     Contact data of the poster
1161          * @param bool        $complete  default true
1162          * @return void
1163          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1164          */
1165         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1166         {
1167                 $mentioned = [];
1168
1169                 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1170                         $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1171
1172                         $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1173
1174                         if (DBA::isResult($thrparent)) {
1175                                 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1176                                 $mentioned[$thrparent['owner-link']]  = $thrparent['owner-link'];
1177                                 $parent_plink                         = $thrparent['plink'];
1178                         } elseif (DBA::isResult($parent)) {
1179                                 $mentioned[$parent['author-link']] = $parent['author-link'];
1180                                 $mentioned[$parent['owner-link']]  = $parent['owner-link'];
1181                                 $parent_plink                      = DI::baseUrl() . '/display/' . $parent['guid'];
1182                         } else {
1183                                 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1184                         }
1185
1186                         if (isset($parent_plink)) {
1187                                 $attributes = [
1188                                         'ref'  => $item['thr-parent'],
1189                                         'href' => $parent_plink
1190                                 ];
1191                                 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1192
1193                                 $attributes = [
1194                                         'rel'  => 'related',
1195                                         'href' => $parent_plink
1196                                 ];
1197                                 XML::addElement($doc, $entry, 'link', '', $attributes);
1198                         }
1199                 }
1200
1201                 // uri-id isn't present for follow entry pseudo-items
1202                 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1203                 foreach ($tags as $tag) {
1204                         $mentioned[$tag['url']] = $tag['url'];
1205                 }
1206
1207                 foreach ($tags as $tag) {
1208                         if ($tag['type'] == Tag::HASHTAG) {
1209                                 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1210                         }
1211                 }
1212
1213                 OStatus::getAttachment($doc, $entry, $item);
1214         }
1215
1216         /**
1217          * Fetch or create title for feed entry
1218          *
1219          * @param array $item
1220          * @return string title
1221          */
1222         private static function getTitle(array $item): string
1223         {
1224                 if ($item['title'] != '') {
1225                         return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1226                 }
1227
1228                 // Fetch information about the post
1229                 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1230                 if (!empty($media) && !empty($media[0]['name']) && ($media[0]['name'] != $media[0]['url'])) {
1231                         return $media[0]['name'];
1232                 }
1233
1234                 // If no bookmark is found then take the first line
1235                 // Remove the share element before fetching the first line
1236                 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
1237
1238                 $title = BBCode::toPlaintext($title) . "\n";
1239                 $pos = strpos($title, "\n");
1240                 $trailer = '';
1241                 if (($pos == 0) || ($pos > 100)) {
1242                         $pos = 100;
1243                         $trailer = '...';
1244                 }
1245
1246                 return substr($title, 0, $pos) . $trailer;
1247         }
1248 }