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