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