]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
be58b9aa8ffa504cf587bc5059beee990efb0bf7
[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()->getHostname());
633                                 $item['uri'] = Item::newURI($item['guid']);
634                                 unset($item['thr-parent']);
635                                 unset($item['parent-uri']);
636
637                                 // Set the delivery priority for "remote self" to "medium"
638                                 $notify = Worker::PRIORITY_MEDIUM;
639                         }
640
641                         $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
642                         if (!Post::exists($condition) && !Post\Delayed::exists($item['uri'], $item['uid'])) {
643                                 if (!$notify) {
644                                         Post\Delayed::publish($item, $notify, $taglist, $attachments);
645                                 } else {
646                                         $postings[] = ['item' => $item, 'notify' => $notify,
647                                                 'taglist' => $taglist, 'attachments' => $attachments];
648                                 }
649                         } else {
650                                 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]);
651                         }
652                 }
653
654                 if (!empty($postings)) {
655                         $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
656                         $total = count($postings);
657                         if ($total > 1) {
658                                 // Posts shouldn't be delayed more than a day
659                                 $interval = min(1440, self::getPollInterval($contact));
660                                 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
661                                 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
662                         } else {
663                                 $delay = 0;
664                         }
665
666                         $post_delay = 0;
667
668                         foreach ($postings as $posting) {
669                                 if ($delay > 0) {
670                                         $publish_time = time() + $post_delay;
671                                         $post_delay += $delay;
672                                 } else {
673                                         $publish_time = time();
674                                 }
675
676                                 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
677                                 $next_publish = max($last_publish + (60 * $min_posting), time());
678                                 if ($publish_time < $next_publish) {
679                                         $publish_time = $next_publish;
680                                 }
681                                 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
682
683                                 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
684                                         DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
685                                 }
686                         }
687                 }
688
689                 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
690                         self::adjustPollFrequency($contact, $creation_dates);
691                 }
692
693                 return ['header' => $author, 'items' => $items];
694         }
695
696         /**
697          * Automatically adjust the poll frequency according to the post frequency
698          *
699          * @param array $contact Contact array
700          * @param array $creation_dates
701          * @return void
702          */
703         private static function adjustPollFrequency(array $contact, array $creation_dates)
704         {
705                 if ($contact['network'] != Protocol::FEED) {
706                         Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
707                         return;
708                 }
709
710                 if (!empty($creation_dates)) {
711                         // Count the post frequency and the earliest and latest post date
712                         $frequency = [];
713                         $oldest = time();
714                         $newest = 0;
715                         $oldest_date = $newest_date = '';
716
717                         foreach ($creation_dates as $date) {
718                                 $timestamp = strtotime($date);
719                                 $day = intdiv($timestamp, 86400);
720                                 $hour = $timestamp % 86400;
721
722                                 // Only have a look at values from the last seven days
723                                 if (((time() / 86400) - $day) < 7) {
724                                         if (empty($frequency[$day])) {
725                                                 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
726                                         } else {
727                                                 ++$frequency[$day]['count'];
728                                                 if ($frequency[$day]['low'] > $hour) {
729                                                         $frequency[$day]['low'] = $hour;
730                                                 }
731                                                 if ($frequency[$day]['high'] < $hour) {
732                                                         $frequency[$day]['high'] = $hour;
733                                                 }
734                                         }
735                                 }
736                                 if ($oldest > $day) {
737                                         $oldest = $day;
738                                         $oldest_date = $date;
739                                 }
740
741                                 if ($newest < $day) {
742                                         $newest = $day;
743                                         $newest_date = $date;
744                                 }
745                         }
746
747                         if (count($creation_dates) == 1) {
748                                 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
749                                 $priority = 8; // Poll once a day
750                         }
751
752                         if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
753                                 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']]);
754                                 $priority = 10; // Poll every month
755                         }
756
757                         if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
758                                 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']]);
759                                 $priority = 9; // Poll every week
760                         }
761
762                         if (empty($priority) && empty($frequency)) {
763                                 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']]);
764                                 $priority = 8; // Poll once a day
765                         }
766
767                         if (empty($priority)) {
768                                 // Calculate the highest "posts per day" value
769                                 $max = 0;
770                                 foreach ($frequency as $entry) {
771                                         if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
772                                                 continue;
773                                         }
774
775                                         // We take the earliest and latest post day and interpolate the number of post per day
776                                         // that would had been created with this post frequency
777
778                                         // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
779                                         $duration = max($entry['high'] - $entry['low'], 14400);
780                                         $ppd = (86400 / $duration) * $entry['count'];
781                                         if ($ppd > $max) {
782                                                 $max = $ppd;
783                                         }
784                                 }
785                                 if ($max > 48) {
786                                         $priority = 1; // Poll every quarter hour
787                                 } elseif ($max > 24) {
788                                         $priority = 2; // Poll half an hour
789                                 } elseif ($max > 12) {
790                                         $priority = 3; // Poll hourly
791                                 } elseif ($max > 8) {
792                                         $priority = 4; // Poll every two hours
793                                 } elseif ($max > 4) {
794                                         $priority = 5; // Poll every three hours
795                                 } elseif ($max > 2) {
796                                         $priority = 6; // Poll every six hours
797                                 } else {
798                                         $priority = 7; // Poll twice a day
799                                 }
800                                 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
801                         }
802                 } else {
803                         Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
804                         $priority = 8; // Poll once a day
805                 }
806
807                 if ($contact['rating'] != $priority) {
808                         Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
809                         Contact::update(['rating' => $priority], ['id' => $contact['id']]);
810                 }
811         }
812
813         /**
814          * Get the poll interval for the given contact array
815          *
816          * @param array $contact
817          * @return int Poll interval in minutes
818          */
819         public static function getPollInterval(array $contact): int
820         {
821                 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
822                         $ratings = [0, 3, 7, 8, 9, 10];
823                         if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
824                                 $rating = $contact['rating'];
825                         } elseif (array_key_exists($contact['priority'], $ratings)) {
826                                 $rating = $ratings[$contact['priority']];
827                         } else {
828                                 $rating = -1;
829                         }
830                 } else {
831                         // Check once a week per default for all other networks
832                         $rating = 9;
833                 }
834
835                 // Friendica and OStatus are checked once a day
836                 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
837                         $rating = 8;
838                 }
839
840                 // Check archived contacts or contacts with unsupported protocols once a month
841                 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
842                         $rating = 10;
843                 }
844
845                 if ($rating < 0) {
846                         return 0;
847                 }
848                 /*
849                  * Based on $contact['priority'], should we poll this site now? Or later?
850                  */
851
852                 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
853
854                 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
855
856                 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
857                 //      '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
858
859                 return $poll_intervals[$rating];
860         }
861
862         /**
863          * Convert a tag array to a tag string
864          *
865          * @param array $tags
866          * @return string tag string
867          */
868         private static function tagToString(array $tags): string
869         {
870                 $tagstr = '';
871
872                 foreach ($tags as $tag) {
873                         if ($tagstr != '') {
874                                 $tagstr .= ', ';
875                         }
876
877                         $tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
878                 }
879
880                 return $tagstr;
881         }
882
883         private static function titleIsBody(string $title, string $body): bool
884         {
885                 $title = strip_tags($title);
886                 $title = trim($title);
887                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
888                 $title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
889
890                 $body = strip_tags($body);
891                 $body = trim($body);
892                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
893                 $body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
894
895                 if (strlen($title) < strlen($body)) {
896                         $body = substr($body, 0, strlen($title));
897                 }
898
899                 if (($title != $body) && (substr($title, -3) == '...')) {
900                         $pos = strrpos($title, '...');
901                         if ($pos > 0) {
902                                 $title = substr($title, 0, $pos);
903                                 $body = substr($body, 0, $pos);
904                         }
905                 }
906                 return ($title == $body);
907         }
908
909         /**
910          * Creates the Atom feed for a given nickname
911          *
912          * Supported filters:
913          * - activity (default): all the public posts
914          * - posts: all the public top-level posts
915          * - comments: all the public replies
916          *
917          * Updates the provided last_update parameter if the result comes from the
918          * cache or it is empty
919          *
920          * @param array   $owner       owner-view record of the feed owner
921          * @param string  $last_update Date of the last update
922          * @param integer $max_items   Number of maximum items to fetch
923          * @param string  $filter      Feed items filter (activity, posts or comments)
924          * @param boolean $nocache     Wether to bypass caching
925          *
926          * @return string Atom feed
927          * @throws HTTPException\InternalServerErrorException
928          * @throws \ImagickException
929          */
930         public static function atom(array $owner, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
931         {
932                 $stamp = microtime(true);
933
934                 $cachekey = 'feed:feed:' . $owner['nickname'] . ':' . $filter . ':' . $last_update;
935
936                 // Display events in the user's timezone
937                 if (strlen($owner['timezone'])) {
938                         DI::app()->setTimeZone($owner['timezone']);
939                 }
940
941                 $previous_created = $last_update;
942
943                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
944                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
945                         $result = DI::cache()->get($cachekey);
946                         if (!$nocache && !is_null($result)) {
947                                 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
948                                 return $result['feed'];
949                         }
950                 }
951
952                 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
953                 $authorid = Contact::getIdForURL($owner['url']);
954
955                 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
956                         AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
957                         $owner['uid'], $check_date, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT,
958                         Item::PRIVATE, Protocol::ACTIVITYPUB,
959                         Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
960
961                 if ($filter === 'comments') {
962                         $condition[0] .= " AND `gravity` = ? ";
963                         $condition[] = Item::GRAVITY_COMMENT;
964                 }
965
966                 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
967                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
968                         $condition[] = $owner['id'];
969                         $condition[] = $authorid;
970                 }
971
972                 $params = ['order' => ['received' => true], 'limit' => $max_items];
973
974                 if ($filter === 'posts') {
975                         $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
976                 } else {
977                         $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
978                 }
979
980                 $items = Post::toArray($ret);
981
982                 $doc = new DOMDocument('1.0', 'utf-8');
983                 $doc->formatOutput = true;
984
985                 $root = self::addHeader($doc, $owner, $filter);
986
987                 foreach ($items as $item) {
988                         $entry = self::noteEntry($doc, $item, $owner);
989                         $root->appendChild($entry);
990
991                         if ($last_update < $item['created']) {
992                                 $last_update = $item['created'];
993                         }
994                 }
995
996                 $feeddata = trim($doc->saveXML());
997
998                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
999                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1000
1001                 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
1002
1003                 return $feeddata;
1004         }
1005
1006         /**
1007          * Adds the header elements to the XML document
1008          *
1009          * @param DOMDocument $doc       XML document
1010          * @param array       $owner     Contact data of the poster
1011          * @param string      $filter    The related feed filter (activity, posts or comments)
1012          *
1013          * @return DOMElement Header root element
1014          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1015          */
1016         private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1017         {
1018                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1019                 $doc->appendChild($root);
1020
1021                 $title = '';
1022                 $selfUri = '/feed/' . $owner['nick'] . '/';
1023                 switch ($filter) {
1024                         case 'activity':
1025                                 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1026                                 $selfUri .= $filter;
1027                                 break;
1028                         case 'posts':
1029                                 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1030                                 break;
1031                         case 'comments':
1032                                 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1033                                 $selfUri .= $filter;
1034                                 break;
1035                 }
1036
1037                 $attributes = ['uri' => 'https://friendi.ca', 'version' => App::VERSION . '-' . DB_UPDATE_VERSION];
1038                 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1039                 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1040                 XML::addElement($doc, $root, 'title', $title);
1041                 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1042                 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1043                 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1044
1045                 $author = self::addAuthor($doc, $owner);
1046                 $root->appendChild($author);
1047
1048                 $attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
1049                 XML::addElement($doc, $root, 'link', '', $attributes);
1050
1051                 OStatus::addHubLink($doc, $root, $owner['nick']);
1052
1053                 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1054                 XML::addElement($doc, $root, 'link', '', $attributes);
1055
1056                 return $root;
1057         }
1058
1059         /**
1060          * Adds the author element to the XML document
1061          *
1062          * @param DOMDocument $doc          XML document
1063          * @param array       $owner        Contact data of the poster
1064          * @return DOMElement author element
1065          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1066          */
1067         private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
1068         {
1069                 $author = $doc->createElement('author');
1070                 XML::addElement($doc, $author, 'uri', $owner['url']);
1071                 XML::addElement($doc, $author, 'name', $owner['nick']);
1072                 XML::addElement($doc, $author, 'email', $owner['addr']);
1073
1074                 return $author;
1075         }
1076
1077         /**
1078          * Adds a regular entry element
1079          *
1080          * @param DOMDocument $doc       XML document
1081          * @param array       $item      Data of the item that is to be posted
1082          * @param array       $owner     Contact data of the poster
1083          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
1084          * @return DOMElement Entry element
1085          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1086          * @throws \ImagickException
1087          */
1088         private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
1089         {
1090                 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1091                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
1092                 }
1093
1094                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1095
1096                 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1097
1098                 self::entryFooter($doc, $entry, $item, $owner);
1099
1100                 return $entry;
1101         }
1102
1103         /**
1104          * Adds elements to the XML document
1105          *
1106          * @param DOMDocument $doc       XML document
1107          * @param \DOMElement $entry     Entry element where the content is added
1108          * @param array       $item      Data of the item that is to be posted
1109          * @param array       $owner     Contact data of the poster
1110          * @param string      $title     Title for the post
1111          * @param string      $verb      The activity verb
1112          * @param bool        $complete  Add the "status_net" element?
1113          * @return void
1114          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1115          */
1116         private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
1117         {
1118                 if ($verb == '') {
1119                         $verb = OStatus::constructVerb($item);
1120                 }
1121
1122                 XML::addElement($doc, $entry, 'id', $item['uri']);
1123                 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1124
1125                 $body = OStatus::formatPicturePost($item['body'], $item['uri-id']);
1126
1127                 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1128
1129                 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1130
1131                 XML::addElement($doc, $entry, 'link', '', ['rel' => 'alternate', 'type' => 'text/html',
1132                                                                 'href' => DI::baseUrl() . '/display/' . $item['guid']]
1133                 );
1134
1135                 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1136                 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1137         }
1138
1139         /**
1140          * Adds the elements at the foot of an entry to the XML document
1141          *
1142          * @param DOMDocument $doc       XML document
1143          * @param object      $entry     The entry element where the elements are added
1144          * @param array       $item      Data of the item that is to be posted
1145          * @param array       $owner     Contact data of the poster
1146          * @param bool        $complete  default true
1147          * @return void
1148          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1149          */
1150         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1151         {
1152                 $mentioned = [];
1153
1154                 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1155                         $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1156
1157                         $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1158
1159                         if (DBA::isResult($thrparent)) {
1160                                 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1161                                 $mentioned[$thrparent['owner-link']]  = $thrparent['owner-link'];
1162                                 $parent_plink                         = $thrparent['plink'];
1163                         } elseif (DBA::isResult($parent)) {
1164                                 $mentioned[$parent['author-link']] = $parent['author-link'];
1165                                 $mentioned[$parent['owner-link']]  = $parent['owner-link'];
1166                                 $parent_plink                      = DI::baseUrl() . '/display/' . $parent['guid'];
1167                         } else {
1168                                 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1169                         }
1170
1171                         if (isset($parent_plink)) {
1172                                 $attributes = [
1173                                         'ref'  => $item['thr-parent'],
1174                                         'href' => $parent_plink];
1175                                 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1176
1177                                 $attributes = [
1178                                         'rel'  => 'related',
1179                                         'href' => $parent_plink];
1180                                 XML::addElement($doc, $entry, 'link', '', $attributes);
1181                         }
1182                 }
1183
1184                 // uri-id isn't present for follow entry pseudo-items
1185                 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1186                 foreach ($tags as $tag) {
1187                         $mentioned[$tag['url']] = $tag['url'];
1188                 }
1189
1190                 foreach ($tags as $tag) {
1191                         if ($tag['type'] == Tag::HASHTAG) {
1192                                 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1193                         }
1194                 }
1195
1196                 OStatus::getAttachment($doc, $entry, $item);
1197         }
1198
1199         /**
1200          * Fetch or create title for feed entry
1201          *
1202          * @param array $item
1203          * @return string title
1204          */
1205         private static function getTitle(array $item): string
1206         {
1207                 if ($item['title'] != '') {
1208                         return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1209                 }
1210
1211                 // Fetch information about the post
1212                 $siteinfo = BBCode::getAttachedData($item['body']);
1213                 if (isset($siteinfo['title'])) {
1214                         return $siteinfo['title'];
1215                 }
1216
1217                 // If no bookmark is found then take the first line
1218                 // Remove the share element before fetching the first line
1219                 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
1220
1221                 $title = BBCode::toPlaintext($title)."\n";
1222                 $pos = strpos($title, "\n");
1223                 $trailer = '';
1224                 if (($pos == 0) || ($pos > 100)) {
1225                         $pos = 100;
1226                         $trailer = '...';
1227                 }
1228
1229                 return substr($title, 0, $pos) . $trailer;
1230         }
1231 }