]> git.mxchange.org Git - friendica.git/blob - src/Content/Item.php
Merge pull request #13048 from MrPetovan/bug/fatal-errors
[friendica.git] / src / Content / Item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\Content;
23
24 use Friendica\App;
25 use Friendica\App\BaseURL;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\BBCode\Video;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Hook;
30 use Friendica\Core\L10n;
31 use Friendica\Core\Logger;
32 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
33 use Friendica\Core\Protocol;
34 use Friendica\Core\Session\Capability\IHandleUserSessions;
35 use Friendica\Core\System;
36 use Friendica\Database\DBA;
37 use Friendica\Model\Attach;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Conversation;
40 use Friendica\Model\FileTag;
41 use Friendica\Model\Group;
42 use Friendica\Model\Item as ItemModel;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Tag;
45 use Friendica\Model\Post;
46 use Friendica\Model\User;
47 use Friendica\Network\HTTPException;
48 use Friendica\Object\EMail\ItemCCEMail;
49 use Friendica\Protocol\Activity;
50 use Friendica\Util\ACLFormatter;
51 use Friendica\Util\DateTimeFormat;
52 use Friendica\Util\Emailer;
53 use Friendica\Util\ParseUrl;
54 use Friendica\Util\Profiler;
55 use Friendica\Util\Proxy;
56 use Friendica\Util\XML;
57
58 /**
59  * A content helper class for displaying items
60  */
61 class Item
62 {
63         /** @var Activity */
64         private $activity;
65         /** @var L10n */
66         private $l10n;
67         /** @var Profiler */
68         private $profiler;
69         /** @var IHandleUserSessions */
70         private $userSession;
71         /** @var Video */
72         private $bbCodeVideo;
73         /** @var ACLFormatter */
74         private $aclFormatter;
75         /** @var IManagePersonalConfigValues */
76         private $pConfig;
77         /** @var BaseURL */
78         private $baseURL;
79         /** @var Emailer */
80         private $emailer;
81         /** @var App */
82         private $app;
83
84         public function __construct(Profiler $profiler, Activity $activity, L10n $l10n, IHandleUserSessions $userSession, Video $bbCodeVideo, ACLFormatter $aclFormatter, IManagePersonalConfigValues $pConfig, BaseURL $baseURL, Emailer $emailer, App $app)
85         {
86                 $this->profiler     = $profiler;
87                 $this->activity     = $activity;
88                 $this->l10n         = $l10n;
89                 $this->userSession  = $userSession;
90                 $this->bbCodeVideo  = $bbCodeVideo;
91                 $this->aclFormatter = $aclFormatter;
92                 $this->baseURL      = $baseURL;
93                 $this->pConfig      = $pConfig;
94                 $this->emailer      = $emailer;
95                 $this->app          = $app;
96         }
97
98         /**
99          * Lists categories and folders for an item
100          *
101          * @param array $item
102          * @param int   $uid
103          * @return array
104          * [
105          *     [ // categories array
106          *         {
107          *             'name': 'category name',
108          *             'removeurl': 'url to remove this category',
109          *             'first': 'is the first in this array? true/false',
110          *             'last': 'is the last in this array? true/false',
111          *         },
112          *         ...
113          *     ],
114          *     [ //folders array
115          *         {
116          *             'name': 'folder name',
117          *             'removeurl': 'url to remove this folder',
118          *             'first': 'is the first in this array? true/false',
119          *             'last': 'is the last in this array? true/false',
120          *         } ,
121          *         ...
122          *     ]
123          * ]
124          *
125          * @throws \Exception
126          */
127         public function determineCategoriesTerms(array $item, int $uid = 0): array
128         {
129                 $categories = [];
130                 $folders = [];
131                 $first = true;
132
133                 $uid = $item['uid'] ?: $uid;
134
135                 if (empty($item['has-categories'])) {
136                         return [$categories, $folders];
137                 }
138
139                 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid) as $savedFolderName) {
140                         if (!empty($item['author-link'])) {
141                                 $url = $item['author-link'] . '/conversations?category=' . rawurlencode($savedFolderName);
142                         } else {
143                                 $url = '#';
144                         }
145                         $categories[] = [
146                                 'name' => $savedFolderName,
147                                 'url' => $url,
148                                 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '',
149                                 'first' => $first,
150                                 'last' => false
151                         ];
152                         $first = false;
153                 }
154
155                 if (count($categories)) {
156                         $categories[count($categories) - 1]['last'] = true;
157                 }
158
159                 if ($this->userSession->getLocalUserId() == $uid) {
160                         foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) {
161                                 $folders[] = [
162                                         'name' => $savedFolderName,
163                                         'url' => "#",
164                                         'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '',
165                                         'first' => $first,
166                                         'last' => false
167                                 ];
168                                 $first = false;
169                         }
170                 }
171
172                 if (count($folders)) {
173                         $folders[count($folders) - 1]['last'] = true;
174                 }
175
176                 return [$categories, $folders];
177         }
178
179         /**
180          * This function removes the tag $tag from the text $body and replaces it with
181          * the appropriate link.
182          *
183          * @param string $body        the text to replace the tag in
184          * @param int    $profile_uid the user id to replace the tag for (0 = anyone)
185          * @param string $tag         the tag to replace
186          * @param string $network     The network of the post
187          *
188          * @return array|bool ['replaced' => $replaced, 'contact' => $contact] or "false" on if already replaced
189          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
190          * @throws \ImagickException
191          */
192         public static function replaceTag(string &$body, int $profile_uid, string $tag, string $network = '')
193         {
194                 $replaced = false;
195
196                 //is it a person tag?
197                 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
198                         $tag_type = substr($tag, 0, 1);
199                         //is it already replaced?
200                         if (strpos($tag, '[url=')) {
201                                 return $replaced;
202                         }
203
204                         //get the person's name
205                         $name = substr($tag, 1);
206
207                         // Sometimes the tag detection doesn't seem to work right
208                         // This is some workaround
209                         $nameparts = explode(' ', $name);
210                         $name = $nameparts[0];
211
212                         // Try to detect the contact in various ways
213                         if (strpos($name, 'http://') || strpos($name, '@')) {
214                                 $contact = Contact::getByURLForUser($name, $profile_uid);
215                         } else {
216                                 $contact = false;
217                                 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
218
219                                 if (strrpos($name, '+')) {
220                                         // Is it in format @nick+number?
221                                         $tagcid = intval(substr($name, strrpos($name, '+') + 1));
222                                         $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
223                                 }
224
225                                 // select someone by nick in the current network
226                                 if (!DBA::isResult($contact) && ($network != '')) {
227                                         $condition = ['nick' => $name, 'network' => $network, 'uid' => $profile_uid];
228                                         $contact = DBA::selectFirst('contact', $fields, $condition);
229                                 }
230
231                                 // select someone by attag in the current network
232                                 if (!DBA::isResult($contact) && ($network != '')) {
233                                         $condition = ['attag' => $name, 'network' => $network, 'uid' => $profile_uid];
234                                         $contact = DBA::selectFirst('contact', $fields, $condition);
235                                 }
236
237                                 //select someone by name in the current network
238                                 if (!DBA::isResult($contact) && ($network != '')) {
239                                         $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
240                                         $contact = DBA::selectFirst('contact', $fields, $condition);
241                                 }
242
243                                 // select someone by nick in any network
244                                 if (!DBA::isResult($contact)) {
245                                         $condition = ['nick' => $name, 'uid' => $profile_uid];
246                                         $contact = DBA::selectFirst('contact', $fields, $condition);
247                                 }
248
249                                 // select someone by attag in any network
250                                 if (!DBA::isResult($contact)) {
251                                         $condition = ['attag' => $name, 'uid' => $profile_uid];
252                                         $contact = DBA::selectFirst('contact', $fields, $condition);
253                                 }
254
255                                 // select someone by name in any network
256                                 if (!DBA::isResult($contact)) {
257                                         $condition = ['name' => $name, 'uid' => $profile_uid];
258                                         $contact = DBA::selectFirst('contact', $fields, $condition);
259                                 }
260                         }
261
262                         // Check if $contact has been successfully loaded
263                         if (DBA::isResult($contact)) {
264                                 $profile = $contact['url'];
265                                 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
266                         }
267
268                         //if there is an url for this persons profile
269                         if (isset($profile) && ($newname != '')) {
270                                 $replaced = true;
271                                 // create profile link
272                                 $profile = str_replace(',', '%2c', $profile);
273                                 $newtag = $tag_type . '[url=' . $profile . ']' . $newname . '[/url]';
274                                 $body = str_replace($tag_type . $name, $newtag, $body);
275                         }
276                 }
277
278                 return ['replaced' => $replaced, 'contact' => $contact];
279         }
280
281         /**
282          * Render actions localized
283          *
284          * @param array $item
285          * @return void
286          * @throws ImagickException
287          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
288          */
289         public function localize(array &$item)
290         {
291                 $this->profiler->startRecording('rendering');
292                 /// @todo The following functionality needs to be cleaned up.
293                 if (!empty($item['verb'])) {
294                         $xmlhead = '<?xml version="1.0" encoding="UTF-8" ?>';
295
296                         if ($this->activity->match($item['verb'], Activity::TAG)) {
297                                 $fields = [
298                                         'author-id', 'author-link', 'author-name', 'author-network',
299                                         'verb', 'object-type', 'resource-id', 'body', 'plink'
300                                 ];
301                                 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
302                                 if (!DBA::isResult($obj)) {
303                                         $this->profiler->stopRecording();
304                                         return;
305                                 }
306
307                                 $author_arr = [
308                                         'uid' => 0,
309                                         'id' => $item['author-id'],
310                                         'network' => $item['author-network'],
311                                         'url' => $item['author-link'],
312                                 ];
313                                 $author  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
314
315                                 $author_arr = [
316                                         'uid' => 0,
317                                         'id' => $obj['author-id'],
318                                         'network' => $obj['author-network'],
319                                         'url' => $obj['author-link'],
320                                 ];
321                                 $objauthor  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
322
323                                 switch ($obj['verb']) {
324                                         case Activity::POST:
325                                                 switch ($obj['object-type']) {
326                                                         case Activity\ObjectType::EVENT:
327                                                                 $post_type = $this->l10n->t('event');
328                                                                 break;
329                                                         default:
330                                                                 $post_type = $this->l10n->t('status');
331                                                 }
332                                                 break;
333
334                                         default:
335                                                 if ($obj['resource-id']) {
336                                                         $post_type = $this->l10n->t('photo');
337                                                         preg_match("/\[url=([^]]*)\]/", $obj['body'], $matches);
338                                                         $rr['plink'] = $matches[1];
339                                                 } else {
340                                                         $post_type = $this->l10n->t('status');
341                                                 }
342                                                 // Let's break everything ... ;-)
343                                                 break;
344                                 }
345                                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
346
347                                 $parsedobj = XML::parseString($xmlhead . $item['object']);
348
349                                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
350                                 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
351                         }
352                 }
353
354                 $this->profiler->stopRecording();
355         }
356
357         /**
358          * Renders photo menu based on item
359          *
360          * @param array $item
361          * @param string $formSecurityToken
362          * @return string
363          */
364         public function photoMenu(array $item, string $formSecurityToken): string
365         {
366                 $this->profiler->startRecording('rendering');
367                 $sub_link = $contact_url = $pm_url = $status_link = '';
368                 $photos_link = $posts_link = $block_link = $ignore_link = '';
369
370                 if ($this->userSession->getLocalUserId() && $this->userSession->getLocalUserId() == $item['uid'] && $item['gravity'] == ItemModel::GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
371                         $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
372                 }
373
374                 $author = [
375                         'uid' => 0,
376                         'id' => $item['author-id'],
377                         'network' => $item['author-network'],
378                         'url' => $item['author-link'],
379                 ];
380                 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
381                 $sparkle = (strpos($profile_link, 'contact/redir/') === 0);
382
383                 $cid = 0;
384                 $pcid = $item['author-id'];
385                 $network = '';
386                 $rel = 0;
387                 $condition = ['uid' => $this->userSession->getLocalUserId(), 'uri-id' => $item['author-uri-id']];
388                 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
389                 if (DBA::isResult($contact)) {
390                         $cid = $contact['id'];
391                         $network = $contact['network'];
392                         $rel = $contact['rel'];
393                 }
394
395                 if ($sparkle) {
396                         $status_link = $profile_link . '/status';
397                         $photos_link = $profile_link . '/photos';
398                         $profile_link = $profile_link . '/profile';
399                 }
400
401                 if (!empty($pcid)) {
402                         $contact_url   = 'contact/' . $pcid;
403                         $posts_link    = $contact_url . '/posts';
404                         $block_link    = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
405                         $ignore_link   = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
406                         $collapse_link = $item['self'] ? '' : $contact_url . '/collapse?t=' . $formSecurityToken;
407                 }
408
409                 if ($cid && !$item['self']) {
410                         $contact_url = 'contact/' . $cid;
411                         $posts_link  = $contact_url . '/posts';
412
413                         if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
414                                 $pm_url = 'message/new/' . $cid;
415                         }
416                 }
417
418                 if ($this->userSession->getLocalUserId()) {
419                         $menu = [
420                                 $this->l10n->t('Follow Thread') => $sub_link,
421                                 $this->l10n->t('View Status') => $status_link,
422                                 $this->l10n->t('View Profile') => $profile_link,
423                                 $this->l10n->t('View Photos') => $photos_link,
424                                 $this->l10n->t('Network Posts') => $posts_link,
425                                 $this->l10n->t('View Contact') => $contact_url,
426                                 $this->l10n->t('Send PM') => $pm_url,
427                                 $this->l10n->t('Block') => $block_link,
428                                 $this->l10n->t('Ignore') => $ignore_link,
429                                 $this->l10n->t('Collapse') => $collapse_link
430                         ];
431
432                         if (!empty($item['language'])) {
433                                 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ItemModel::getLanguageMessage($item) . '\');';
434                         }
435
436                         if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
437                                 in_array($item['network'], Protocol::FEDERATED)
438                         ) {
439                                 $menu[$this->l10n->t('Connect/Follow')] = 'contact/follow?url=' . urlencode($item['author-link']) . '&auto=1';
440                         }
441                 } else {
442                         $menu = [$this->l10n->t('View Profile') => $item['author-link']];
443                 }
444
445                 $args = ['item' => $item, 'menu' => $menu];
446
447                 Hook::callAll('item_photo_menu', $args);
448
449                 $menu = $args['menu'];
450
451                 $o = '';
452                 foreach ($menu as $k => $v) {
453                         if (strpos($v, 'javascript:') === 0) {
454                                 $v = substr($v, 11);
455                                 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
456                         } elseif ($v) {
457                                 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
458                         }
459                 }
460                 $this->profiler->stopRecording();
461                 return $o;
462         }
463
464         /**
465          * Checks if the activity is visible to current user
466          *
467          * @param array $item Activity item
468          * @return bool Whether the item is visible to the user
469          */
470         public function isVisibleActivity(array $item): bool
471         {
472                 // Empty verb or hidden?
473                 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
474                         return false;
475                 }
476
477                 // Check conditions
478                 return (!($this->activity->match($item['verb'], Activity::FOLLOW) &&
479                         $item['object-type'] === Activity\ObjectType::NOTE &&
480                         empty($item['self']) &&
481                         $item['uid'] == $this->userSession->getLocalUserId())
482                 );
483         }
484
485         public function expandTags(array $item, bool $setPermissions = false): array
486         {
487                 // Look for any tags and linkify them
488                 $item['inform'] = '';
489                 $private_forum  = false;
490                 $private_id     = null;
491                 $only_to_forum  = false;
492                 $forum_contact  = [];
493                 $receivers      = [];
494
495                 // Convert mentions in the body to a unified format
496                 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
497
498                 // Search for forum mentions
499                 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
500                         $contact = Contact::getByURLForUser($tag[2], $item['uid']);
501                         if (empty($contact)) {
502                                 continue;
503                         }
504
505                         $receivers[] = $contact['id'];
506
507                         if (!empty($item['inform'])) {
508                                 $item['inform'] .= ',';
509                         }
510                         $item['inform'] .= 'cid:' . $contact['id'];
511
512                         if (($item['gravity'] == ItemModel::GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
513                                 continue;
514                         }
515
516                         if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
517                                 $private_forum = $contact['prv'];
518                                 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
519                                 $private_id = $contact['id'];
520                                 $forum_contact = $contact;
521                                 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
522                         } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
523                                 $private_forum = false;
524                                 $only_to_forum = true;
525                                 $private_id = $contact['id'];
526                                 $forum_contact = $contact;
527                                 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
528                         } else {
529                                 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
530                         }
531                 }
532                 Logger::info('Got inform', ['inform' => $item['inform']]);
533
534                 if (($item['gravity'] == ItemModel::GRAVITY_PARENT) && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
535                         // we tagged a forum in a top level post. Now we change the post
536                         $item['private'] = $private_forum ? ItemModel::PRIVATE : ItemModel::UNLISTED;
537
538                         if ($only_to_forum) {
539                                 $item['postopts'] = '';
540                         }
541
542                         $item['deny_cid'] = '';
543                         $item['deny_gid'] = '';
544
545                         if ($private_forum) {
546                                 $item['allow_cid'] = '<' . $private_id . '>';
547                                 $item['allow_gid'] = '<' . Group::getIdForForum($forum_contact['id']) . '>';
548                         } else {
549                                 $item['allow_cid'] = '';
550                                 $item['allow_gid'] = '';
551                         }
552                 } elseif ($setPermissions) {
553                         if (empty($receivers)) {
554                                 // For security reasons direct posts without any receiver will be posts to yourself
555                                 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
556                                 $receivers[] = $self['id'];
557                         }
558
559                         $item['private']   = ItemModel::PRIVATE;
560                         $item['allow_cid'] = '';
561                         $item['allow_gid'] = '';
562                         $item['deny_cid']  = '';
563                         $item['deny_gid']  = '';
564
565                         foreach ($receivers as $receiver) {
566                                 $item['allow_cid'] .= '<' . $receiver . '>';
567                         }
568                 }
569                 return $item;
570         }
571
572         public function getAuthorAvatar(array $item): string
573         {
574                 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
575                         $author_avatar  = $item['contact-id'];
576                         $author_updated = '';
577                         $author_thumb   = $item['contact-avatar'];
578                 } else {
579                         $author_avatar  = $item['author-id'];
580                         $author_updated = $item['author-updated'];
581                         $author_thumb   = $item['author-avatar'];
582                 }
583
584
585                 if (empty($author_thumb) || Photo::isPhotoURI($author_thumb)) {
586                         $author_thumb = Contact::getAvatarUrlForId($author_avatar, Proxy::SIZE_THUMB, $author_updated);
587                 }
588
589                 return $author_thumb;
590         }
591
592         public function getOwnerAvatar(array $item): string
593         {
594                 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
595                         $owner_avatar  = $item['contact-id'];
596                         $owner_updated = '';
597                         $owner_thumb   = $item['contact-avatar'];
598                 } else {
599                         $owner_avatar   = $item['owner-id'];
600                         $owner_updated  = $item['owner-updated'];
601                         $owner_thumb    = $item['owner-avatar'];
602                 }
603
604                 if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) {
605                         $owner_thumb = Contact::getAvatarUrlForId($owner_avatar, Proxy::SIZE_THUMB, $owner_updated);
606                 }
607
608                 return $owner_thumb;
609         }
610
611         /**
612          * Add a share block for the given uri-id
613          *
614          * @param array  $item
615          * @param string $body
616          * @return string
617          */
618         public function addSharedPost(array $item, string $body = ''): string
619         {
620                 if (empty($body)) {
621                         $body = $item['body'];
622                 }
623
624                 if (empty($item['quote-uri-id'])) {
625                         return $body;
626                 }
627
628                 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'quote-uri-id'];
629                 $shared_item = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [$item['uid'], 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
630                 if (!DBA::isResult($shared_item)) {
631                         Logger::notice('Post does not exist.', ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid']]);
632                         return $body;
633                 }
634
635                 return trim(BBCode::removeSharedData($body) . "\n" . $this->createSharedBlockByArray($shared_item, true));
636         }
637
638         /**
639          * Add a share block for the given guid
640          *
641          * @param string $guid
642          * @param integer $uid
643          * @param bool $add_media
644          * @return string
645          */
646         private function createSharedPostByGuid(string $guid, bool $add_media): string
647         {
648                 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
649                 $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => 0, 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
650
651                 if (!DBA::isResult($shared_item)) {
652                         Logger::notice('Post does not exist.', ['guid' => $guid]);
653                         return '';
654                 }
655
656                 return $this->createSharedBlockByArray($shared_item, $add_media);
657         }
658
659         /**
660          * Add a share block for the given item array
661          *
662          * @param array $item
663          * @param bool $add_media
664          * @return string
665          */
666         public function createSharedBlockByArray(array $item, bool $add_media = false): string
667         {
668                 if ($item['network'] == Protocol::FEED) {
669                         return PageInfo::getFooterFromUrl($item['plink']);
670                 } elseif (!in_array($item['network'] ?? '', Protocol::FEDERATED)) {
671                         $item['guid'] = '';
672                         $item['uri']  = '';
673                 }
674
675                 if ($add_media) {
676                         $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
677                 }
678
679                 $shared_content = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid'], $item['uri']);
680
681                 if (!empty($item['title'])) {
682                         $shared_content .= '[h3]' . $item['title'] . "[/h3]\n";
683                 }
684
685                 $shared = $this->getShareArray($item);
686
687                 // If it is a reshared post then reformat it to avoid display problems with two share elements
688                 if (!empty($shared)) {
689                         if (!empty($shared['guid']) && ($encapsulated_share = $this->createSharedPostByGuid($shared['guid'], true))) {
690                                 if (!empty(BBCode::fetchShareAttributes($item['body']))) {
691                                         $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $encapsulated_share, $item['body']);
692                                 } else {
693                                         $item['body'] .= $encapsulated_share;
694                                 }
695                         }
696                         $item['body'] = HTML::toBBCode(BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::ACTIVITYPUB));
697                 }
698
699                 $shared_content .= $item['body'] . '[/share]';
700
701                 return $shared_content;
702         }
703
704         /**
705          * Return the shared post from an item array (if the item is shared item)
706          *
707          * @param array $item
708          * @param array $fields
709          *
710          * @return array with the shared post
711          */
712         public function getSharedPost(array $item, array $fields = []): array
713         {
714                 if (!empty($item['quote-uri-id'])) {
715                         $shared = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [0, $item['uid'] ?? 0]]);
716                         if (is_array($shared)) {
717                                 return [
718                                         'comment' => BBCode::removeSharedData($item['body'] ?? ''),
719                                         'post'    => $shared
720                                 ];
721                         }
722                 }
723
724                 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
725                 if (!empty($attributes)) {
726                         $shared = Post::selectFirst($fields, ['guid' => $attributes['guid'], 'uid' => [0, $item['uid'] ?? 0]]);
727                         if (is_array($shared)) {
728                                 return [
729                                         'comment' => $attributes['comment'],
730                                         'post'    => $shared
731                                 ];
732                         }
733                 }
734
735                 return [];
736         }
737
738         /**
739          * Return share data from an item array (if the item is shared item)
740          * We are providing the complete Item array, because at some time in the future
741          * we hopefully will define these values not in the body anymore but in some item fields.
742          * This function is meant to replace all similar functions in the system.
743          *
744          * @param array $item
745          *
746          * @return array with share information
747          */
748         private function getShareArray(array $item): array
749         {
750                 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
751                 if (!empty($attributes)) {
752                         return $attributes;
753                 }
754
755                 if (!empty($item['quote-uri-id'])) {
756                         $shared = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'uri', 'body'], ['uri-id' => $item['quote-uri-id']]);
757                         if (!empty($shared)) {
758                                 return [
759                                         'author'     => $shared['author-name'],
760                                         'profile'    => $shared['author-link'],
761                                         'avatar'     => $shared['author-avatar'],
762                                         'link'       => $shared['plink'],
763                                         'posted'     => $shared['created'],
764                                         'guid'       => $shared['guid'],
765                                         'message_id' => $shared['uri'],
766                                         'comment'    => $item['body'],
767                                         'shared'     => $shared['body'],
768                                 ];
769                         }
770                 }
771
772                 return [];
773         }
774
775         /**
776          * Add a link to a shared post at the end of the post
777          *
778          * @param string  $body
779          * @param integer $quote_uri_id
780          * @return string
781          */
782         public function addShareLink(string $body, int $quote_uri_id): string
783         {
784                 $post = Post::selectFirstPost(['uri', 'plink'], ['uri-id' => $quote_uri_id]);
785                 if (empty($post)) {
786                         return $body;
787                 }
788
789                 $body = BBCode::removeSharedData($body);
790
791                 $body .= "\n♲ " . ($post['plink'] ?: $post['uri']);
792
793                 return $body;
794         }
795
796         public function storeAttachmentFromRequest(array $request): string
797         {
798                 $attachment_type  = $request['attachment_type'] ??  '';
799                 $attachment_title = $request['attachment_title'] ?? '';
800                 $attachment_text  = $request['attachment_text'] ??  '';
801
802                 $attachment_url     = hex2bin($request['attachment_url'] ??     '');
803                 $attachment_img_src = hex2bin($request['attachment_img_src'] ?? '');
804
805                 $attachment_img_width  = $request['attachment_img_width'] ??  0;
806                 $attachment_img_height = $request['attachment_img_height'] ?? 0;
807
808                 // Fetch the basic attachment data
809                 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
810                 unset($attachment['keywords']);
811
812                 // Overwrite the basic data with possible changes from the frontend
813                 $attachment['type'] = $attachment_type;
814                 $attachment['title'] = $attachment_title;
815                 $attachment['text'] = $attachment_text;
816                 $attachment['url'] = $attachment_url;
817
818                 if (!empty($attachment_img_src)) {
819                         $attachment['images'] = [
820                                 0 => [
821                                         'src'    => $attachment_img_src,
822                                         'width'  => $attachment_img_width,
823                                         'height' => $attachment_img_height
824                                 ]
825                         ];
826                 } else {
827                         unset($attachment['images']);
828                 }
829
830                 return "\n" . PageInfo::getFooterFromData($attachment);
831         }
832
833         public function addCategories(array $post, string $category): array
834         {
835                 if (!empty($post['file'])) {
836                         // get the "fileas" tags for this post
837                         $filedas = FileTag::fileToArray($post['file']);
838                 }
839
840                 $list_array = explode(',', trim($category));
841                 $post['file'] = FileTag::arrayToFile($list_array, 'category');
842
843                 if (!empty($filedas) && is_array($filedas)) {
844                         // append the fileas stuff to the new categories list
845                         $post['file'] .= FileTag::arrayToFile($filedas);
846                 }
847                 return $post;
848         }
849
850         public function getACL(array $post, array $toplevel_item, array $request): array
851         {
852                 // If this is a comment, set the permissions from the parent.
853                 if ($toplevel_item) {
854                         $post['allow_cid'] = $toplevel_item['allow_cid'] ?? '';
855                         $post['allow_gid'] = $toplevel_item['allow_gid'] ?? '';
856                         $post['deny_cid']  = $toplevel_item['deny_cid'] ?? '';
857                         $post['deny_gid']  = $toplevel_item['deny_gid'] ?? '';
858                         $post['private']   = $toplevel_item['private'];
859                         return $post;
860                 }
861
862                 $user = User::getById($post['uid'], ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
863                 if (!$user) {
864                         throw new HTTPException\NotFoundException($this->l10n->t('Unable to fetch user.'));
865                 }
866
867                 $post['allow_cid'] = isset($request['contact_allow']) ? $this->aclFormatter->toString($request['contact_allow']) : $user['allow_cid'] ?? '';
868                 $post['allow_gid'] = isset($request['group_allow'])   ? $this->aclFormatter->toString($request['group_allow'])   : $user['allow_gid'] ?? '';
869                 $post['deny_cid']  = isset($request['contact_deny'])  ? $this->aclFormatter->toString($request['contact_deny'])  : $user['deny_cid']  ?? '';
870                 $post['deny_gid']  = isset($request['group_deny'])    ? $this->aclFormatter->toString($request['group_deny'])    : $user['deny_gid']  ?? '';
871
872                 $visibility = $request['visibility'] ?? '';
873                 if ($visibility === 'public') {
874                         // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
875                         $post['allow_cid'] = $post['allow_gid'] = $post['deny_cid'] = $post['deny_gid'] = '';
876                 } else if ($visibility === 'custom') {
877                         // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
878                         // case that would make it public. So we always append the author's contact id to the allowed contacts.
879                         // See https://github.com/friendica/friendica/issues/9672
880                         $post['allow_cid'] .= $this->aclFormatter->toString(Contact::getPublicIdByUserId($post['uid']));
881                 }
882
883                 if ($post['allow_gid'] || $post['allow_cid'] || $post['deny_gid'] || $post['deny_cid']) {
884                         $post['private'] = ItemModel::PRIVATE;
885                 } elseif ($this->pConfig->get($post['uid'], 'system', 'unlisted')) {
886                         $post['private'] = ItemModel::UNLISTED;
887                 } else {
888                         $post['private'] = ItemModel::PUBLIC;
889                 }
890
891                 return $post;
892         }
893
894         public function moveAttachmentsFromBodyToAttach(array $post): array
895         {
896                 if (!preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/', $post['body'], $match)) {
897                         return $post;
898                 }
899
900                 foreach ($match[2] as $attachment_id) {
901                         $attachment = Attach::selectFirst(['id', 'uid', 'filename', 'filesize', 'filetype'], ['id' => $attachment_id, 'uid' => $post['uid']]);
902                         if (empty($attachment)) {
903                                 continue;
904                         }
905                         if ($post['attach']) {
906                                 $post['attach'] .= ',';
907                         }
908                         $post['attach'] .= Post\Media::getAttachElement(
909                                 $this->baseURL . '/attach/' . $attachment['id'],
910                                 $attachment['filesize'],
911                                 $attachment['filetype'],
912                                 $attachment['filename'] ?? ''
913                         );
914
915                         $fields = [
916                                 'allow_cid' => $post['allow_cid'], 'allow_gid' => $post['allow_gid'],
917                                 'deny_cid' => $post['deny_cid'], 'deny_gid' => $post['deny_gid']
918                         ];
919                         $condition = ['id' => $attachment_id];
920                         Attach::update($fields, $condition);
921                 }
922
923                 $post['body'] = str_replace($match[1], '', $post['body']);
924
925                 return $post;
926         }
927
928         private function setObjectType(array $post): array
929         {
930                 if (empty($post['post-type'])) {
931                         $post['post-type'] = empty($post['title']) ? ItemModel::PT_NOTE : ItemModel::PT_ARTICLE;
932                 }
933
934                 // embedded bookmark or attachment in post? set bookmark flag
935                 $data = BBCode::getAttachmentData($post['body']);
936                 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $post['body'], $match, PREG_SET_ORDER) || !empty($data['type']))
937                         && ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE)
938                 ) {
939                         $post['post-type'] = ItemModel::PT_PAGE;
940                         $post['object-type'] = Activity\ObjectType::BOOKMARK;
941                 }
942
943                 // Setting the object type if not defined before
944                 if (empty($post['object-type'])) {
945                         $post['object-type'] = ($post['gravity'] == ItemModel::GRAVITY_PARENT) ? Activity\ObjectType::NOTE : Activity\ObjectType::COMMENT;
946                 }
947                 return $post;
948         }
949
950         public function initializePost(array $post): array
951         {
952                 $post['network']    = Protocol::DFRN;
953                 $post['protocol']   = Conversation::PARCEL_DIRECT;
954                 $post['direction']  = Conversation::PUSH;
955                 $post['received']   = DateTimeFormat::utcNow();
956                 $post['origin']     = true;
957                 $post['wall']       = $post['wall'] ?? true;
958                 $post['guid']       = $post['guid'] ?? System::createUUID();
959                 $post['verb']       = $post['verb'] ?? Activity::POST;
960                 $post['uri']        = $post['uri'] ?? ItemModel::newURI($post['guid']);
961                 $post['thr-parent'] = $post['thr-parent'] ?? $post['uri'];
962
963                 if (empty($post['gravity'])) {
964                         $post['gravity'] = ($post['uri'] == $post['thr-parent']) ? ItemModel::GRAVITY_PARENT : ItemModel::GRAVITY_COMMENT;
965                 }
966
967                 $owner = User::getOwnerDataById($post['uid']);
968
969                 if (!isset($post['allow_cid']) || !isset($post['allow_gid']) || !isset($post['deny_cid']) || !isset($post['deny_gid'])) {
970                         $post['allow_cid'] = $owner['allow_cid'];
971                         $post['allow_gid'] = $owner['allow_gid'];
972                         $post['deny_cid']  = $owner['deny_cid'];
973                         $post['deny_gid']  = $owner['deny_gid'];
974                 }
975
976                 if ($post['allow_gid'] || $post['allow_cid'] || $post['deny_gid'] || $post['deny_cid']) {
977                         $post['private'] = ItemModel::PRIVATE;
978                 } elseif ($this->pConfig->get($post['uid'], 'system', 'unlisted')) {
979                         $post['private'] = ItemModel::UNLISTED;
980                 } else {
981                         $post['private'] = ItemModel::PUBLIC;
982                 }
983
984                 if (empty($post['contact-id'])) {
985                         $post['contact-id'] = $owner['id'];
986                 }
987
988                 if (empty($post['author-link']) && empty($post['author-id'])) {
989                         $post['author-link']   = $owner['url'];
990                         $post['author-id']     = Contact::getIdForURL($post['author-link']);
991                         $post['author-name']   = $owner['name'];
992                         $post['author-avatar'] = $owner['thumb'];
993                 }
994
995                 if (empty($post['owner-link']) && empty($post['owner-id'])) {
996                         $post['owner-link']   = $post['author-link'];
997                         $post['owner-id']     = Contact::getIdForURL($post['owner-link']);
998                         $post['owner-name']   = $post['author-name'];
999                         $post['owner-avatar'] = $post['author-avatar'];
1000                 }
1001
1002                 return $post;
1003         }
1004
1005         public function finalizePost(array $post): array
1006         {
1007                 if (preg_match("/\[attachment\](.*?)\[\/attachment\]/ism", $post['body'], $matches)) {
1008                         $post['body'] = preg_replace("/\[attachment].*?\[\/attachment\]/ism", PageInfo::getFooterFromUrl($matches[1]), $post['body']);
1009                 }
1010
1011                 // Convert links with empty descriptions to links without an explicit description
1012                 $post['body'] = trim(preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $post['body']));
1013                 $post['body'] = $this->bbCodeVideo->transform($post['body']);
1014                 $post = $this->setObjectType($post);
1015
1016                 // Personal notes must never be altered to a forum post.
1017                 if ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE) {
1018                         // Look for any tags and linkify them
1019                         $post = $this->expandTags($post);
1020                 }
1021
1022                 return $post;
1023         }
1024
1025         public function postProcessPost(array $post, array $recipients = [])
1026         {
1027                 if (!\Friendica\Content\Feature::isEnabled($post['uid'], 'explicit_mentions') && ($post['gravity'] == ItemModel::GRAVITY_COMMENT)) {
1028                         Tag::createImplicitMentions($post['uri-id'], $post['thr-parent-id']);
1029                 }
1030
1031                 Hook::callAll('post_local_end', $post);
1032
1033                 $author = DBA::selectFirst('contact', ['thumb'], ['uid' => $post['uid'], 'self' => true]);
1034
1035                 foreach ($recipients as $recipient) {
1036                         $address = trim($recipient);
1037                         if (!$address) {
1038                                 continue;
1039                         }
1040
1041                         $this->emailer->send(new ItemCCEMail(
1042                                 $this->app,
1043                                 $this->l10n,
1044                                 $this->baseURL,
1045                                 $post,
1046                                 $address,
1047                                 $author['thumb'] ?? ''
1048                         ));
1049                 }
1050         }
1051 }