]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
Merge pull request #13646 from annando/page-drop
[friendica.git] / src / Protocol / Feed.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol;
23
24 use DOMDocument;
25 use DOMElement;
26 use DOMXPath;
27 use Friendica\App;
28 use Friendica\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                                         $fetch_further_information == LocalRelationship::FFI_BOTH,
621                                         $contact['ffi_keyword_denylist'] ?? ''
622                                 );
623
624                                 if (!empty($data)) {
625                                         // Take the data that was provided by the feed if the query is empty
626                                         if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
627                                                 $data['title'] = $saved_title;
628                                                 $item['body'] = $saved_body;
629                                         }
630
631                                         $data_text = strip_tags(trim($data['text'] ?? ''));
632                                         $item_body = strip_tags(trim($item['body'] ?? ''));
633
634                                         if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
635                                                 $data['text'] = '';
636                                         }
637
638                                         // We always strip the title since it will be added in the page information
639                                         $item['title'] = '';
640                                         $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false);
641                                         $taglist = $fetch_further_information == LocalRelationship::FFI_BOTH ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : [];
642                                         $item['object-type'] = Activity\ObjectType::BOOKMARK;
643                                         $attachments = [];
644
645                                         foreach (['audio', 'video'] as $elementname) {
646                                                 if (!empty($data[$elementname])) {
647                                                         foreach ($data[$elementname] as $element) {
648                                                                 if (!empty($element['src'])) {
649                                                                         $src = $element['src'];
650                                                                 } elseif (!empty($element['content'])) {
651                                                                         $src = $element['content'];
652                                                                 } else {
653                                                                         continue;
654                                                                 }
655
656                                                                 $attachments[] = [
657                                                                         'type'        => ($elementname == 'audio') ? Post\Media::AUDIO : Post\Media::VIDEO,
658                                                                         'url'         => $src,
659                                                                         'preview'     => $element['image']       ?? null,
660                                                                         'mimetype'    => $element['contenttype'] ?? null,
661                                                                         'name'        => $element['name']        ?? null,
662                                                                         'description' => $element['description'] ?? null,
663                                                                 ];
664                                                         }
665                                                 }
666                                         }
667                                 }
668                         } else {
669                                 if (!empty($summary)) {
670                                         $item['body'] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item['body'];
671                                 }
672
673                                 if ($fetch_further_information == LocalRelationship::FFI_KEYWORD) {
674                                         if (empty($taglist)) {
675                                                 $taglist = PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '');
676                                         }
677                                         $item['body'] .= "\n" . self::tagToString($taglist);
678                                 } else {
679                                         $taglist = [];
680                                 }
681
682                                 // Add the link to the original feed entry if not present in feed
683                                 if (($item['plink'] != '') && !strstr($item['body'], $item['plink']) && !in_array($item['plink'], array_column($attachments, 'url'))) {
684                                         $item['body'] .= '[hr][url]' . $item['plink'] . '[/url]';
685                                 }
686                         }
687
688                         if (empty($item['title'])) {
689                                 $item['post-type'] = Item::PT_NOTE;
690                         }
691
692                         Logger::info('Stored feed', ['item' => $item]);
693
694                         $notify = Item::isRemoteSelf($contact, $item);
695                         $item['wall'] = (bool)$notify;
696
697                         // Distributed items should have a well-formatted URI.
698                         // Additionally, we have to avoid conflicts with identical URI between imported feeds and these items.
699                         if ($notify) {
700                                 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHost());
701                                 $item['uri']  = Item::newURI($item['guid']);
702                                 unset($item['plink']);
703                                 unset($item['thr-parent']);
704                                 unset($item['parent-uri']);
705
706                                 // Set the delivery priority for "remote self" to "medium"
707                                 $notify = Worker::PRIORITY_MEDIUM;
708                         }
709
710                         $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
711                         if (!Post::exists($condition) && !Post\Delayed::exists($item['uri'], $item['uid'])) {
712                                 if (!$notify) {
713                                         Post\Delayed::publish($item, $notify, $taglist, $attachments);
714                                 } else {
715                                         $postings[] = [
716                                                 'item' => $item, 'notify' => $notify,
717                                                 'taglist' => $taglist, 'attachments' => $attachments
718                                         ];
719                                 }
720                         } else {
721                                 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]);
722                         }
723                 }
724
725                 if (!empty($postings)) {
726                         $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
727                         $total = count($postings);
728                         if ($total > 1) {
729                                 // Posts shouldn't be delayed more than a day
730                                 $interval = min(1440, self::getPollInterval($contact));
731                                 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
732                                 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
733                         } else {
734                                 $delay = 0;
735                         }
736
737                         $post_delay = 0;
738
739                         foreach ($postings as $posting) {
740                                 if ($delay > 0) {
741                                         $publish_time = time() + $post_delay;
742                                         $post_delay += $delay;
743                                 } else {
744                                         $publish_time = time();
745                                 }
746
747                                 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
748                                 $next_publish = max($last_publish + (60 * $min_posting), time());
749                                 if ($publish_time < $next_publish) {
750                                         $publish_time = $next_publish;
751                                 }
752                                 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
753
754                                 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
755                                         DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
756                                 }
757                         }
758                 }
759
760                 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
761                         self::adjustPollFrequency($contact, $creation_dates);
762                 }
763
764                 return ['header' => $author, 'items' => $items];
765         }
766
767         /**
768          * Automatically adjust the poll frequency according to the post frequency
769          *
770          * @param array $contact Contact array
771          * @param array $creation_dates
772          * @return void
773          */
774         private static function adjustPollFrequency(array $contact, array $creation_dates)
775         {
776                 if ($contact['network'] != Protocol::FEED) {
777                         Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
778                         return;
779                 }
780
781                 if (!empty($creation_dates)) {
782                         // Count the post frequency and the earliest and latest post date
783                         $frequency = [];
784                         $oldest = time();
785                         $newest = 0;
786                         $oldest_date = $newest_date = '';
787
788                         foreach ($creation_dates as $date) {
789                                 $timestamp = strtotime($date);
790                                 $day = intdiv($timestamp, 86400);
791                                 $hour = $timestamp % 86400;
792
793                                 // Only have a look at values from the last seven days
794                                 if (((time() / 86400) - $day) < 7) {
795                                         if (empty($frequency[$day])) {
796                                                 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
797                                         } else {
798                                                 ++$frequency[$day]['count'];
799                                                 if ($frequency[$day]['low'] > $hour) {
800                                                         $frequency[$day]['low'] = $hour;
801                                                 }
802                                                 if ($frequency[$day]['high'] < $hour) {
803                                                         $frequency[$day]['high'] = $hour;
804                                                 }
805                                         }
806                                 }
807                                 if ($oldest > $day) {
808                                         $oldest = $day;
809                                         $oldest_date = $date;
810                                 }
811
812                                 if ($newest < $day) {
813                                         $newest = $day;
814                                         $newest_date = $date;
815                                 }
816                         }
817
818                         if (count($creation_dates) == 1) {
819                                 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
820                                 $priority = 8; // Poll once a day
821                         }
822
823                         if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
824                                 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']]);
825                                 $priority = 10; // Poll every month
826                         }
827
828                         if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
829                                 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']]);
830                                 $priority = 9; // Poll every week
831                         }
832
833                         if (empty($priority) && empty($frequency)) {
834                                 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']]);
835                                 $priority = 8; // Poll once a day
836                         }
837
838                         if (empty($priority)) {
839                                 // Calculate the highest "posts per day" value
840                                 $max = 0;
841                                 foreach ($frequency as $entry) {
842                                         if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
843                                                 continue;
844                                         }
845
846                                         // We take the earliest and latest post day and interpolate the number of post per day
847                                         // that would had been created with this post frequency
848
849                                         // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
850                                         $duration = max($entry['high'] - $entry['low'], 14400);
851                                         $ppd = (86400 / $duration) * $entry['count'];
852                                         if ($ppd > $max) {
853                                                 $max = $ppd;
854                                         }
855                                 }
856                                 if ($max > 48) {
857                                         $priority = 1; // Poll every quarter hour
858                                 } elseif ($max > 24) {
859                                         $priority = 2; // Poll half an hour
860                                 } elseif ($max > 12) {
861                                         $priority = 3; // Poll hourly
862                                 } elseif ($max > 8) {
863                                         $priority = 4; // Poll every two hours
864                                 } elseif ($max > 4) {
865                                         $priority = 5; // Poll every three hours
866                                 } elseif ($max > 2) {
867                                         $priority = 6; // Poll every six hours
868                                 } else {
869                                         $priority = 7; // Poll twice a day
870                                 }
871                                 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
872                         }
873                 } else {
874                         Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
875                         $priority = 8; // Poll once a day
876                 }
877
878                 if ($contact['rating'] != $priority) {
879                         Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
880                         Contact::update(['rating' => $priority], ['id' => $contact['id']]);
881                 }
882         }
883
884         /**
885          * Get the poll interval for the given contact array
886          *
887          * @param array $contact
888          * @return int Poll interval in minutes
889          */
890         public static function getPollInterval(array $contact): int
891         {
892                 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
893                         $ratings = [0, 3, 7, 8, 9, 10];
894                         if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
895                                 $rating = $contact['rating'];
896                         } elseif (array_key_exists($contact['priority'], $ratings)) {
897                                 $rating = $ratings[$contact['priority']];
898                         } else {
899                                 $rating = -1;
900                         }
901                 } else {
902                         // Check once a week per default for all other networks
903                         $rating = 9;
904                 }
905
906                 // Friendica and OStatus are checked once a day
907                 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
908                         $rating = 8;
909                 }
910
911                 // Check archived contacts or contacts with unsupported protocols once a month
912                 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
913                         $rating = 10;
914                 }
915
916                 if ($rating < 0) {
917                         return 0;
918                 }
919                 /*
920                  * Based on $contact['priority'], should we poll this site now? Or later?
921                  */
922
923                 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
924
925                 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720, 1440, 10080, 43200];
926
927                 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
928                 //      '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
929
930                 return $poll_intervals[$rating];
931         }
932
933         /**
934          * Convert a tag array to a tag string
935          *
936          * @param array $tags
937          * @return string tag string
938          */
939         private static function tagToString(array $tags): string
940         {
941                 $tagstr = '';
942
943                 foreach ($tags as $tag) {
944                         if ($tagstr != '') {
945                                 $tagstr .= ', ';
946                         }
947
948                         $tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
949                 }
950
951                 return $tagstr;
952         }
953
954         private static function titleIsBody(string $title, string $body): bool
955         {
956                 $title = strip_tags($title);
957                 $title = trim($title);
958                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
959                 $title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
960
961                 $body = strip_tags($body);
962                 $body = trim($body);
963                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
964                 $body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
965
966                 if (strlen($title) < strlen($body)) {
967                         $body = substr($body, 0, strlen($title));
968                 }
969
970                 if (($title != $body) && (substr($title, -3) == '...')) {
971                         $pos = strrpos($title, '...');
972                         if ($pos > 0) {
973                                 $title = substr($title, 0, $pos);
974                                 $body = substr($body, 0, $pos);
975                         }
976                 }
977                 return ($title == $body);
978         }
979
980         /**
981          * Creates the Atom feed for a given nickname
982          *
983          * Supported filters:
984          * - activity (default): all the public posts
985          * - posts: all the public top-level posts
986          * - comments: all the public replies
987          *
988          * Updates the provided last_update parameter if the result comes from the
989          * cache or it is empty
990          *
991          * @param array   $owner       owner-view record of the feed owner
992          * @param string  $last_update Date of the last update
993          * @param integer $max_items   Number of maximum items to fetch
994          * @param string  $filter      Feed items filter (activity, posts or comments)
995          * @param boolean $nocache     Wether to bypass caching
996          *
997          * @return string Atom feed
998          * @throws HTTPException\InternalServerErrorException
999          * @throws \ImagickException
1000          */
1001         public static function atom(array $owner, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
1002         {
1003                 $stamp = microtime(true);
1004
1005                 $cachekey = 'feed:feed:' . $owner['nickname'] . ':' . $filter . ':' . $last_update;
1006
1007                 // Display events in the user's timezone
1008                 if (strlen($owner['timezone'])) {
1009                         DI::app()->setTimeZone($owner['timezone']);
1010                 }
1011
1012                 $previous_created = $last_update;
1013
1014                 // Don't cache when the last item was posted less than 15 minutes ago (Cache duration)
1015                 if ((time() - strtotime($owner['last-item'])) < 15 * 60) {
1016                         $result = DI::cache()->get($cachekey);
1017                         if (!$nocache && !is_null($result)) {
1018                                 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
1019                                 return $result['feed'];
1020                         }
1021                 }
1022
1023                 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
1024                 $authorid = Contact::getIdForURL($owner['url']);
1025
1026                 $condition = [
1027                         "`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
1028                         AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
1029                         $owner['uid'], $check_date, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT,
1030                         Item::PRIVATE, Protocol::ACTIVITYPUB,
1031                         Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA
1032                 ];
1033
1034                 if ($filter === 'comments') {
1035                         $condition[0] .= " AND `gravity` = ? ";
1036                         $condition[] = Item::GRAVITY_COMMENT;
1037                 }
1038
1039                 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1040                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
1041                         $condition[] = $owner['id'];
1042                         $condition[] = $authorid;
1043                 }
1044
1045                 $params = ['order' => ['received' => true], 'limit' => $max_items];
1046
1047                 if ($filter === 'posts') {
1048                         $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
1049                 } else {
1050                         $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
1051                 }
1052
1053                 $items = Post::toArray($ret);
1054
1055                 $doc = new DOMDocument('1.0', 'utf-8');
1056                 $doc->formatOutput = true;
1057
1058                 $root = self::addHeader($doc, $owner, $filter);
1059
1060                 foreach ($items as $item) {
1061                         $entry = self::noteEntry($doc, $item, $owner);
1062                         $root->appendChild($entry);
1063
1064                         if ($last_update < $item['created']) {
1065                                 $last_update = $item['created'];
1066                         }
1067                 }
1068
1069                 $feeddata = trim($doc->saveXML());
1070
1071                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
1072                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1073
1074                 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]);
1075
1076                 return $feeddata;
1077         }
1078
1079         /**
1080          * Adds the header elements to the XML document
1081          *
1082          * @param DOMDocument $doc       XML document
1083          * @param array       $owner     Contact data of the poster
1084          * @param string      $filter    The related feed filter (activity, posts or comments)
1085          *
1086          * @return DOMElement Header root element
1087          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1088          */
1089         private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1090         {
1091                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1092                 $doc->appendChild($root);
1093
1094                 $title = '';
1095                 $selfUri = '/feed/' . $owner['nick'] . '/';
1096                 switch ($filter) {
1097                         case 'activity':
1098                                 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1099                                 $selfUri .= $filter;
1100                                 break;
1101                         case 'posts':
1102                                 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1103                                 break;
1104                         case 'comments':
1105                                 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1106                                 $selfUri .= $filter;
1107                                 break;
1108                 }
1109
1110                 $attributes = ['uri' => 'https://friendi.ca', 'version' => App::VERSION . '-' . DB_UPDATE_VERSION];
1111                 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1112                 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1113                 XML::addElement($doc, $root, 'title', $title);
1114                 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1115                 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1116                 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1117
1118                 $author = self::addAuthor($doc, $owner);
1119                 $root->appendChild($author);
1120
1121                 $attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
1122                 XML::addElement($doc, $root, 'link', '', $attributes);
1123
1124                 OStatus::addHubLink($doc, $root, $owner['nick']);
1125
1126                 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1127                 XML::addElement($doc, $root, 'link', '', $attributes);
1128
1129                 return $root;
1130         }
1131
1132         /**
1133          * Adds the author element to the XML document
1134          *
1135          * @param DOMDocument $doc          XML document
1136          * @param array       $owner        Contact data of the poster
1137          * @return DOMElement author element
1138          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1139          */
1140         private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
1141         {
1142                 $author = $doc->createElement('author');
1143                 XML::addElement($doc, $author, 'uri', $owner['url']);
1144                 XML::addElement($doc, $author, 'name', $owner['nick']);
1145                 XML::addElement($doc, $author, 'email', $owner['addr']);
1146
1147                 return $author;
1148         }
1149
1150         /**
1151          * Adds a regular entry element
1152          *
1153          * @param DOMDocument $doc       XML document
1154          * @param array       $item      Data of the item that is to be posted
1155          * @param array       $owner     Contact data of the poster
1156          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
1157          * @return DOMElement Entry element
1158          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1159          * @throws \ImagickException
1160          */
1161         private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
1162         {
1163                 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1164                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
1165                 }
1166
1167                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1168
1169                 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1170
1171                 self::entryFooter($doc, $entry, $item, $owner);
1172
1173                 return $entry;
1174         }
1175
1176         /**
1177          * Adds elements to the XML document
1178          *
1179          * @param DOMDocument $doc       XML document
1180          * @param \DOMElement $entry     Entry element where the content is added
1181          * @param array       $item      Data of the item that is to be posted
1182          * @param array       $owner     Contact data of the poster
1183          * @param string      $title     Title for the post
1184          * @param string      $verb      The activity verb
1185          * @param bool        $complete  Add the "status_net" element?
1186          * @return void
1187          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1188          */
1189         private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
1190         {
1191                 if ($verb == '') {
1192                         $verb = OStatus::constructVerb($item);
1193                 }
1194
1195                 XML::addElement($doc, $entry, 'id', $item['uri']);
1196                 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1197
1198                 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
1199                 $body = Post\Media::addHTMLLinkToBody($item['uri-id'], $body);
1200
1201                 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1202
1203                 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1204
1205                 XML::addElement(
1206                         $doc,
1207                         $entry,
1208                         'link',
1209                         '',
1210                         [
1211                                 'rel' => 'alternate', 'type' => 'text/html',
1212                                 'href' => DI::baseUrl() . '/display/' . $item['guid']
1213                         ]
1214                 );
1215
1216                 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1217                 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1218         }
1219
1220         /**
1221          * Adds the elements at the foot of an entry to the XML document
1222          *
1223          * @param DOMDocument $doc       XML document
1224          * @param object      $entry     The entry element where the elements are added
1225          * @param array       $item      Data of the item that is to be posted
1226          * @param array       $owner     Contact data of the poster
1227          * @param bool        $complete  default true
1228          * @return void
1229          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1230          */
1231         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1232         {
1233                 $mentioned = [];
1234
1235                 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1236                         $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1237
1238                         $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1239
1240                         if (DBA::isResult($thrparent)) {
1241                                 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1242                                 $mentioned[$thrparent['owner-link']]  = $thrparent['owner-link'];
1243                                 $parent_plink                         = $thrparent['plink'];
1244                         } elseif (DBA::isResult($parent)) {
1245                                 $mentioned[$parent['author-link']] = $parent['author-link'];
1246                                 $mentioned[$parent['owner-link']]  = $parent['owner-link'];
1247                                 $parent_plink                      = DI::baseUrl() . '/display/' . $parent['guid'];
1248                         } else {
1249                                 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1250                         }
1251
1252                         if (isset($parent_plink)) {
1253                                 $attributes = [
1254                                         'ref'  => $item['thr-parent'],
1255                                         'href' => $parent_plink
1256                                 ];
1257                                 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1258
1259                                 $attributes = [
1260                                         'rel'  => 'related',
1261                                         'href' => $parent_plink
1262                                 ];
1263                                 XML::addElement($doc, $entry, 'link', '', $attributes);
1264                         }
1265                 }
1266
1267                 // uri-id isn't present for follow entry pseudo-items
1268                 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1269                 foreach ($tags as $tag) {
1270                         $mentioned[$tag['url']] = $tag['url'];
1271                 }
1272
1273                 foreach ($tags as $tag) {
1274                         if ($tag['type'] == Tag::HASHTAG) {
1275                                 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1276                         }
1277                 }
1278
1279                 OStatus::getAttachment($doc, $entry, $item);
1280         }
1281
1282         /**
1283          * Fetch or create title for feed entry
1284          *
1285          * @param array $item
1286          * @return string title
1287          */
1288         private static function getTitle(array $item): string
1289         {
1290                 if ($item['title'] != '') {
1291                         return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1292                 }
1293
1294                 // Fetch information about the post
1295                 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1296                 if (!empty($media) && !empty($media[0]['name']) && ($media[0]['name'] != $media[0]['url'])) {
1297                         return $media[0]['name'];
1298                 }
1299
1300                 // If no bookmark is found then take the first line
1301                 // Remove the share element before fetching the first line
1302                 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
1303
1304                 $title = BBCode::toPlaintext($title) . "\n";
1305                 $pos = strpos($title, "\n");
1306                 $trailer = '';
1307                 if (($pos == 0) || ($pos > 100)) {
1308                         $pos = 100;
1309                         $trailer = '...';
1310                 }
1311
1312                 return substr($title, 0, $pos) . $trailer;
1313         }
1314 }