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