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