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