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