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