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