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