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