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