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