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