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