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