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