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