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