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