Remove unused parameter
[friendica.git/.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          * Read a RSS/RDF/Atom feed and create an item entry for it
54          *
55          * @param string $xml      The feed data
56          * @param array  $importer The user record of the importer
57          * @param array  $contact  The contact record of the feed
58          *
59          * @return array Returns the header and the first item in dry run mode
60          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
61          */
62         public static function import($xml, array $importer = [], array $contact = [])
63         {
64                 $dryRun = empty($importer) && empty($contact);
65
66                 if ($dryRun) {
67                         Logger::info("Test Atom/RSS feed");
68                 } else {
69                         Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
70                 }
71
72                 if (empty($xml)) {
73                         Logger::info('XML is empty.');
74                         return [];
75                 }
76
77                 if (!empty($contact['poll'])) {
78                         $basepath = $contact['poll'];
79                 } elseif (!empty($contact['url'])) {
80                         $basepath = $contact['url'];
81                 } else {
82                         $basepath = '';
83                 }
84
85                 $doc = new DOMDocument();
86                 @$doc->loadXML(trim($xml));
87                 $xpath = new DOMXPath($doc);
88                 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
89                 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
90                 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
91                 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
92                 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
93                 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
94                 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
95
96                 $author = [];
97                 $entries = null;
98
99                 // Is it RDF?
100                 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
101                         $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
102                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
103
104                         if (empty($author["author-name"])) {
105                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
106                         }
107                         $entries = $xpath->query('/rdf:RDF/rss:item');
108                 }
109
110                 // Is it Atom?
111                 if ($xpath->query('/atom:feed')->length > 0) {
112                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
113                         if (is_object($alternate)) {
114                                 foreach ($alternate AS $attribute) {
115                                         if ($attribute->name == "href") {
116                                                 $author["author-link"] = $attribute->textContent;
117                                         }
118                                 }
119                         }
120
121                         if (empty($author["author-link"])) {
122                                 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
123                                 if (is_object($self)) {
124                                         foreach ($self AS $attribute) {
125                                                 if ($attribute->name == "href") {
126                                                         $author["author-link"] = $attribute->textContent;
127                                                 }
128                                         }
129                                 }
130                         }
131
132                         if (empty($author["author-link"])) {
133                                 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
134                         }
135                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
136
137                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
138
139                         if (empty($author["author-name"])) {
140                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
141                         }
142
143                         if (empty($author["author-name"])) {
144                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
145                         }
146
147                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
148                         if ($value != "") {
149                                 $author["author-name"] = $value;
150                         }
151
152                         if ($dryRun) {
153                                 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
154
155                                 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
156                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
157                                 if ($value != "") {
158                                         $author["author-link"] = $value;
159                                 }
160
161                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
162                                 if ($value != "") {
163                                         $author["author-nick"] = $value;
164                                 }
165
166                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
167                                 if ($value != "") {
168                                         $author["author-location"] = $value;
169                                 }
170
171                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
172                                 if ($value != "") {
173                                         $author["author-about"] = $value;
174                                 }
175
176                                 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
177                                 if (is_object($avatar)) {
178                                         foreach ($avatar AS $attribute) {
179                                                 if ($attribute->name == "href") {
180                                                         $author["author-avatar"] = $attribute->textContent;
181                                                 }
182                                         }
183                                 }
184                         }
185
186                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
187
188                         $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
189
190                         $entries = $xpath->query('/atom:feed/atom:entry');
191                 }
192
193                 // Is it RSS?
194                 if ($xpath->query('/rss/channel')->length > 0) {
195                         $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
196
197                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
198                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
199
200                         if (empty($author["author-name"])) {
201                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
202                         }
203
204                         if (empty($author["author-name"])) {
205                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
206                         }
207
208                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
209
210                         $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
211
212                         $entries = $xpath->query('/rss/channel/item');
213                 }
214
215                 if (!$dryRun) {
216                         $author["author-link"] = $contact["url"];
217
218                         if (empty($author["author-name"])) {
219                                 $author["author-name"] = $contact["name"];
220                         }
221
222                         $author["author-avatar"] = $contact["thumb"];
223
224                         $author["owner-link"] = $contact["url"];
225                         $author["owner-name"] = $contact["name"];
226                         $author["owner-avatar"] = $contact["thumb"];
227                 }
228
229                 $header = [];
230                 $header["uid"] = $importer["uid"] ?? 0;
231                 $header["network"] = Protocol::FEED;
232                 $header["wall"] = 0;
233                 $header["origin"] = 0;
234                 $header["gravity"] = GRAVITY_PARENT;
235                 $header["private"] = Item::PUBLIC;
236                 $header["verb"] = Activity::POST;
237                 $header["object-type"] = Activity\ObjectType::NOTE;
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::httpRequest()->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                         Logger::info('Stored feed', ['item' => $item]);
543
544                         $notify = Item::isRemoteSelf($contact, $item);
545
546                         // Distributed items should have a well formatted URI.
547                         // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
548                         if ($notify) {
549                                 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
550                                 $item['uri'] = Item::newURI($item['uid'], $item['guid']);
551                                 unset($item['thr-parent']);
552                                 unset($item['parent-uri']);
553
554                                 // Set the delivery priority for "remote self" to "medium"
555                                 $notify = PRIORITY_MEDIUM;
556                         }
557
558                         $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
559                         if (!Post::exists($condition) && !Post\Delayed::exists($item["uri"], $item['uid'])) {
560                                 if (!$notify) {
561                                         Post\Delayed::publish($item, $notify, $taglist, $attachments);
562                                 } else {
563                                         $postings[] = ['item' => $item, 'notify' => $notify,
564                                                 'taglist' => $taglist, 'attachments' => $attachments];
565                                 }
566                         } else {
567                                 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item["uri"]]);
568                         }
569                 }
570
571                 if (!empty($postings)) {
572                         $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
573                         $total = count($postings);
574                         if ($total > 1) {
575                                 // Posts shouldn't be delayed more than a day
576                                 $interval = min(1440, self::getPollInterval($contact));
577                                 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
578                                 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
579                         } else {
580                                 $delay = 0;
581                         }
582
583                         $post_delay = 0;
584
585                         foreach ($postings as $posting) {
586                                 if ($delay > 0) {
587                                         $publish_time = time() + $post_delay;
588                                         $post_delay += $delay;
589                                 } else {
590                                         $publish_time = time();
591                                 }
592
593                                 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
594                                 $next_publish = max($last_publish + (60 * $min_posting), time());
595                                 if ($publish_time < $next_publish) {
596                                         $publish_time = $next_publish;
597                                 }
598                                 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
599
600                                 Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], false, $publish_at, $posting['taglist'], $posting['attachments']);
601                         }
602                 }
603
604                 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
605                         self::adjustPollFrequency($contact, $creation_dates);
606                 }
607
608                 return ["header" => $author, "items" => $items];
609         }
610
611         /**
612          * Automatically adjust the poll frequency according to the post frequency
613          *
614          * @param array $contact
615          * @param array $creation_dates
616          * @return void
617          */
618         private static function adjustPollFrequency(array $contact, array $creation_dates)
619         {
620                 if ($contact['network'] != Protocol::FEED) {
621                         Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
622                         return;
623                 }
624
625                 if (!empty($creation_dates)) {
626                         // Count the post frequency and the earliest and latest post date
627                         $frequency = [];
628                         $oldest = time();
629                         $newest = 0;
630                         $oldest_date = $newest_date = '';
631
632                         foreach ($creation_dates as $date) {
633                                 $timestamp = strtotime($date);
634                                 $day = intdiv($timestamp, 86400);
635                                 $hour = $timestamp % 86400;
636
637                                 // Only have a look at values from the last seven days
638                                 if (((time() / 86400) - $day) < 7) {
639                                         if (empty($frequency[$day])) {
640                                                 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
641                                         } else {
642                                                 ++$frequency[$day]['count'];
643                                                 if ($frequency[$day]['low'] > $hour) {
644                                                         $frequency[$day]['low'] = $hour;
645                                                 }
646                                                 if ($frequency[$day]['high'] < $hour) {
647                                                         $frequency[$day]['high'] = $hour;
648                                                 }
649                                         }
650                                 }
651                                 if ($oldest > $day) {
652                                         $oldest = $day;
653                                         $oldest_date = $date;
654                                 }
655
656                                 if ($newest < $day) {
657                                         $newest = $day;
658                                         $newest_date = $date;
659                                 }
660                         }
661
662                         if (count($creation_dates) == 1) {
663                                 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
664                                 $priority = 8; // Poll once a day
665                         }
666
667                         if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
668                                 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']]);
669                                 $priority = 10; // Poll every month
670                         }
671
672                         if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
673                                 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']]);
674                                 $priority = 9; // Poll every week
675                         }
676
677                         if (empty($priority) && empty($frequency)) {
678                                 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']]);
679                                 $priority = 8; // Poll once a day
680                         }
681
682                         if (empty($priority)) {
683                                 // Calculate the highest "posts per day" value
684                                 $max = 0;
685                                 foreach ($frequency as $entry) {
686                                         if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
687                                                 continue;
688                                         }
689
690                                         // We take the earliest and latest post day and interpolate the number of post per day
691                                         // that would had been created with this post frequency
692
693                                         // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
694                                         $duration = max($entry['high'] - $entry['low'], 14400);
695                                         $ppd = (86400 / $duration) * $entry['count'];
696                                         if ($ppd > $max) {
697                                                 $max = $ppd;
698                                         }
699                                 }
700                                 if ($max > 48) {
701                                         $priority = 1; // Poll every quarter hour
702                                 } elseif ($max > 24) {
703                                         $priority = 2; // Poll half an hour
704                                 } elseif ($max > 12) {
705                                         $priority = 3; // Poll hourly
706                                 } elseif ($max > 8) {
707                                         $priority = 4; // Poll every two hours
708                                 } elseif ($max > 4) {
709                                         $priority = 5; // Poll every three hours
710                                 } elseif ($max > 2) {
711                                         $priority = 6; // Poll every six hours
712                                 } else {
713                                         $priority = 7; // Poll twice a day
714                                 }
715                                 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
716                         }
717                 } else {
718                         Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
719                         $priority = 8; // Poll once a day
720                 }
721
722                 if ($contact['rating'] != $priority) {
723                         Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
724                         DBA::update('contact', ['rating' => $priority], ['id' => $contact['id']]);
725                 }
726         }
727
728         /**
729          * Get the poll interval for the given contact array
730          *
731          * @param array $contact
732          * @return int Poll interval in minutes
733          */
734         public static function getPollInterval(array $contact)
735         {
736                 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
737                         $ratings = [0, 3, 7, 8, 9, 10];
738                         if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
739                                 $rating = $contact['rating'];
740                         } elseif (array_key_exists($contact['priority'], $ratings)) {
741                                 $rating = $ratings[$contact['priority']];
742                         } else {
743                                 $rating = -1;
744                         }
745                 } else {
746                         // Check once a week per default for all other networks
747                         $rating = 9;
748                 }
749
750                 // Friendica and OStatus are checked once a day
751                 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
752                         $rating = 8;
753                 }
754
755                 // Check archived contacts or contacts with unsupported protocols once a month
756                 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
757                         $rating = 10;
758                 }
759
760                 if ($rating < 0) {
761                         return 0;
762                 }
763                 /*
764                  * Based on $contact['priority'], should we poll this site now? Or later?
765                  */
766
767                 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
768
769                 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
770
771                 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
772                 //      '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
773
774                 return $poll_intervals[$rating];
775         }
776
777         /**
778          * Convert a tag array to a tag string
779          *
780          * @param array $tags
781          * @return string tag string
782          */
783         private static function tagToString(array $tags)
784         {
785                 $tagstr = '';
786
787                 foreach ($tags as $tag) {
788                         if ($tagstr != "") {
789                                 $tagstr .= ", ";
790                         }
791
792                         $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
793                 }
794
795                 return $tagstr;
796         }
797
798         private static function titleIsBody($title, $body)
799         {
800                 $title = strip_tags($title);
801                 $title = trim($title);
802                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
803                 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
804
805                 $body = strip_tags($body);
806                 $body = trim($body);
807                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
808                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
809
810                 if (strlen($title) < strlen($body)) {
811                         $body = substr($body, 0, strlen($title));
812                 }
813
814                 if (($title != $body) && (substr($title, -3) == "...")) {
815                         $pos = strrpos($title, "...");
816                         if ($pos > 0) {
817                                 $title = substr($title, 0, $pos);
818                                 $body = substr($body, 0, $pos);
819                         }
820                 }
821                 return ($title == $body);
822         }
823
824         /**
825          * Creates the Atom feed for a given nickname
826          *
827          * Supported filters:
828          * - activity (default): all the public posts
829          * - posts: all the public top-level posts
830          * - comments: all the public replies
831          *
832          * Updates the provided last_update parameter if the result comes from the
833          * cache or it is empty
834          *
835          * @param string  $owner_nick  Nickname of the feed owner
836          * @param string  $last_update Date of the last update
837          * @param integer $max_items   Number of maximum items to fetch
838          * @param string  $filter      Feed items filter (activity, posts or comments)
839          * @param boolean $nocache     Wether to bypass caching
840          *
841          * @return string Atom feed
842          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
843          * @throws \ImagickException
844          */
845         public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
846         {
847                 $stamp = microtime(true);
848
849                 $owner = User::getOwnerDataByNick($owner_nick);
850                 if (!$owner) {
851                         return;
852                 }
853
854                 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
855
856                 $previous_created = $last_update;
857
858                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
859                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
860                         $result = DI::cache()->get($cachekey);
861                         if (!$nocache && !is_null($result)) {
862                                 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
863                                 return $result['feed'];
864                         }
865                 }
866
867                 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
868                 $authorid = Contact::getIdForURL($owner["url"]);
869
870                 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
871                         AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
872                         $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
873                         Item::PRIVATE, Protocol::ACTIVITYPUB,
874                         Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
875
876                 if ($filter === 'comments') {
877                         $condition[0] .= " AND `object-type` = ? ";
878                         $condition[] = Activity\ObjectType::COMMENT;
879                 }
880
881                 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
882                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
883                         $condition[] = $owner["id"];
884                         $condition[] = $authorid;
885                 }
886
887                 $params = ['order' => ['received' => true], 'limit' => $max_items];
888
889                 if ($filter === 'posts') {
890                         $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
891                 } else {
892                         $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
893                 }
894
895                 $items = Post::toArray($ret);
896
897                 $doc = new DOMDocument('1.0', 'utf-8');
898                 $doc->formatOutput = true;
899
900                 $root = self::addHeader($doc, $owner, $filter);
901
902                 foreach ($items as $item) {
903                         $entry = self::entry($doc, $item, $owner);
904                         $root->appendChild($entry);
905
906                         if ($last_update < $item['created']) {
907                                 $last_update = $item['created'];
908                         }
909                 }
910
911                 $feeddata = trim($doc->saveXML());
912
913                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
914                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
915
916                 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
917
918                 return $feeddata;
919         }
920
921         /**
922          * Adds the header elements to the XML document
923          *
924          * @param DOMDocument $doc       XML document
925          * @param array       $owner     Contact data of the poster
926          * @param string      $filter    The related feed filter (activity, posts or comments)
927          *
928          * @return object header root element
929          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
930          */
931         private static function addHeader(DOMDocument $doc, array $owner, $filter)
932         {
933                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
934                 $doc->appendChild($root);
935
936                 $title = '';
937                 $selfUri = '/feed/' . $owner["nick"] . '/';
938                 switch ($filter) {
939                         case 'activity':
940                                 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
941                                 $selfUri .= $filter;
942                                 break;
943                         case 'posts':
944                                 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
945                                 break;
946                         case 'comments':
947                                 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
948                                 $selfUri .= $filter;
949                                 break;
950                 }
951
952                 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
953                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
954                 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
955                 XML::addElement($doc, $root, "title", $title);
956                 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
957                 XML::addElement($doc, $root, "logo", $owner["photo"]);
958                 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
959
960                 $author = self::addAuthor($doc, $owner);
961                 $root->appendChild($author);
962
963                 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
964                 XML::addElement($doc, $root, "link", "", $attributes);
965
966                 OStatus::hublinks($doc, $root, $owner["nick"]);
967
968                 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
969                 XML::addElement($doc, $root, "link", "", $attributes);
970
971                 return $root;
972         }
973
974         /**
975          * Adds the author element to the XML document
976          *
977          * @param DOMDocument $doc          XML document
978          * @param array       $owner        Contact data of the poster
979          *
980          * @return \DOMElement author element
981          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
982          */
983         private static function addAuthor(DOMDocument $doc, array $owner)
984         {
985                 $author = $doc->createElement("author");
986                 XML::addElement($doc, $author, "uri", $owner["url"]);
987                 XML::addElement($doc, $author, "name", $owner["nick"]);
988                 XML::addElement($doc, $author, "email", $owner["addr"]);
989
990                 return $author;
991         }
992
993         /**
994          * Adds an entry element to the XML document
995          *
996          * @param DOMDocument $doc       XML document
997          * @param array       $item      Data of the item that is to be posted
998          * @param array       $owner     Contact data of the poster
999          * @param bool        $toplevel  optional default false
1000          *
1001          * @return \DOMElement Entry element
1002          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1003          * @throws \ImagickException
1004          */
1005         private static function entry(DOMDocument $doc, array $item, array $owner)
1006         {
1007                 $xml = null;
1008
1009                 $repeated_guid = OStatus::getResharedGuid($item);
1010                 if ($repeated_guid != "") {
1011                         $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
1012                 }
1013
1014                 if ($xml) {
1015                         return $xml;
1016                 }
1017
1018                 return self::noteEntry($doc, $item, $owner);
1019         }
1020
1021                 /**
1022          * Adds an entry element with reshared content
1023          *
1024          * @param DOMDocument $doc           XML document
1025          * @param array       $item          Data of the item that is to be posted
1026          * @param array       $owner         Contact data of the poster
1027          * @param string      $repeated_guid guid
1028          * @param bool        $toplevel      Is it for en entry element (false) or a feed entry (true)?
1029          *
1030          * @return bool Entry element
1031          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1032          * @throws \ImagickException
1033          */
1034         private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
1035         {
1036                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1037                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1038                 }
1039
1040                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1041
1042                 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1043                         'network' => Protocol::FEDERATED];
1044                 $repeated_item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition);
1045                 if (!DBA::isResult($repeated_item)) {
1046                         return false;
1047                 }
1048
1049                 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
1050
1051                 self::entryFooter($doc, $entry, $item, $owner);
1052
1053                 return $entry;
1054         }
1055
1056         /**
1057          * Adds a regular entry element
1058          *
1059          * @param DOMDocument $doc       XML document
1060          * @param array       $item      Data of the item that is to be posted
1061          * @param array       $owner     Contact data of the poster
1062          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
1063          *
1064          * @return \DOMElement Entry element
1065          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1066          * @throws \ImagickException
1067          */
1068         private static function noteEntry(DOMDocument $doc, array $item, array $owner)
1069         {
1070                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1071                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1072                 }
1073
1074                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1075
1076                 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1077
1078                 self::entryFooter($doc, $entry, $item, $owner);
1079
1080                 return $entry;
1081         }
1082
1083         /**
1084          * Adds elements to the XML document
1085          *
1086          * @param DOMDocument $doc       XML document
1087          * @param \DOMElement $entry     Entry element where the content is added
1088          * @param array       $item      Data of the item that is to be posted
1089          * @param array       $owner     Contact data of the poster
1090          * @param string      $title     Title for the post
1091          * @param string      $verb      The activity verb
1092          * @param bool        $complete  Add the "status_net" element?
1093          * @param bool        $feed_mode Behave like a regular feed for users if true
1094          * @return void
1095          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1096          */
1097         private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
1098         {
1099                 if ($verb == "") {
1100                         $verb = OStatus::constructVerb($item);
1101                 }
1102
1103                 XML::addElement($doc, $entry, "id", $item["uri"]);
1104                 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1105
1106                 $body = OStatus::formatPicturePost($item['body']);
1107
1108                 $body = BBCode::convert($body, false, BBCode::OSTATUS);
1109
1110                 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1111
1112                 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1113                                                                 "href" => DI::baseUrl()."/display/".$item["guid"]]
1114                 );
1115
1116                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1117                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1118         }
1119
1120         /**
1121          * Adds the elements at the foot of an entry to the XML document
1122          *
1123          * @param DOMDocument $doc       XML document
1124          * @param object      $entry     The entry element where the elements are added
1125          * @param array       $item      Data of the item that is to be posted
1126          * @param array       $owner     Contact data of the poster
1127          * @param bool        $complete  default true
1128          * @return void
1129          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1130          */
1131         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1132         {
1133                 $mentioned = [];
1134
1135                 if ($item['gravity'] != GRAVITY_PARENT) {
1136                         $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1137
1138                         $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $item['thr-parent']]);
1139
1140                         if (DBA::isResult($thrparent)) {
1141                                 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1142                                 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1143                                 $parent_plink = $thrparent["plink"];
1144                         } else {
1145                                 $mentioned[$parent["author-link"]] = $parent["author-link"];
1146                                 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1147                                 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1148                         }
1149
1150                         $attributes = [
1151                                         "ref" => $item['thr-parent'],
1152                                         "href" => $parent_plink];
1153                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1154
1155                         $attributes = [
1156                                         "rel" => "related",
1157                                         "href" => $parent_plink];
1158                         XML::addElement($doc, $entry, "link", "", $attributes);
1159                 }
1160
1161                 // uri-id isn't present for follow entry pseudo-items
1162                 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1163                 foreach ($tags as $tag) {
1164                         $mentioned[$tag['url']] = $tag['url'];
1165                 }
1166
1167                 foreach ($tags as $tag) {
1168                         if ($tag['type'] == Tag::HASHTAG) {
1169                                 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
1170                         }
1171                 }
1172
1173                 OStatus::getAttachment($doc, $entry, $item);
1174         }
1175
1176         /**
1177          * Fetch or create title for feed entry
1178          *
1179          * @param array $item
1180          * @return string title
1181          */
1182         private static function getTitle(array $item)
1183         {
1184                 if ($item['title'] != '') {
1185                         return BBCode::convert($item['title'], false, BBCode::OSTATUS);
1186                 }
1187
1188                 // Fetch information about the post
1189                 $siteinfo = BBCode::getAttachedData($item["body"]);
1190                 if (isset($siteinfo["title"])) {
1191                         return $siteinfo["title"];
1192                 }
1193
1194                 // If no bookmark is found then take the first line
1195                 // Remove the share element before fetching the first line
1196                 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1197
1198                 $title = HTML::toPlaintext(BBCode::convert($title, false), 0, true)."\n";
1199                 $pos = strpos($title, "\n");
1200                 $trailer = "";
1201                 if (($pos == 0) || ($pos > 100)) {
1202                         $pos = 100;
1203                         $trailer = "...";
1204                 }
1205
1206                 return substr($title, 0, $pos) . $trailer;
1207         }
1208 }