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