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