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