]> git.mxchange.org Git - friendica.git/blob - src/Content/Item.php
49193627f63b37f8e8a38d0951c0f65a1f5890a6
[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-lias'],
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                                 $item['postopts'] = '';
541                         }
542
543                         $item['deny_cid'] = '';
544                         $item['deny_gid'] = '';
545
546                         if ($private_group) {
547                                 $item['allow_cid'] = '<' . $private_id . '>';
548                                 $item['allow_gid'] = '<' . Circle::getIdForGroup($group_contact['id']) . '>';
549                         } else {
550                                 $item['allow_cid'] = '';
551                                 $item['allow_gid'] = '';
552                         }
553                 } elseif ($setPermissions) {
554                         if (empty($receivers)) {
555                                 // For security reasons direct posts without any receiver will be posts to yourself
556                                 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
557                                 $receivers[] = $self['id'];
558                         }
559
560                         $item['private']   = ItemModel::PRIVATE;
561                         $item['allow_cid'] = '';
562                         $item['allow_gid'] = '';
563                         $item['deny_cid']  = '';
564                         $item['deny_gid']  = '';
565
566                         foreach ($receivers as $receiver) {
567                                 $item['allow_cid'] .= '<' . $receiver . '>';
568                         }
569                 }
570                 return $item;
571         }
572
573         public function getAuthorAvatar(array $item): string
574         {
575                 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
576                         $author_avatar  = $item['contact-id'];
577                         $author_updated = '';
578                         $author_thumb   = $item['contact-avatar'];
579                 } else {
580                         $author_avatar  = $item['author-id'];
581                         $author_updated = $item['author-updated'];
582                         $author_thumb   = $item['author-avatar'];
583                 }
584
585
586                 if (empty($author_thumb) || Photo::isPhotoURI($author_thumb)) {
587                         $author_thumb = Contact::getAvatarUrlForId($author_avatar, Proxy::SIZE_THUMB, $author_updated);
588                 }
589
590                 return $author_thumb;
591         }
592
593         public function getOwnerAvatar(array $item): string
594         {
595                 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
596                         $owner_avatar  = $item['contact-id'];
597                         $owner_updated = '';
598                         $owner_thumb   = $item['contact-avatar'];
599                 } else {
600                         $owner_avatar   = $item['owner-id'];
601                         $owner_updated  = $item['owner-updated'];
602                         $owner_thumb    = $item['owner-avatar'];
603                 }
604
605                 if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) {
606                         $owner_thumb = Contact::getAvatarUrlForId($owner_avatar, Proxy::SIZE_THUMB, $owner_updated);
607                 }
608
609                 return $owner_thumb;
610         }
611
612         /**
613          * Add a share block for the given uri-id
614          *
615          * @param array  $item
616          * @param string $body
617          * @return string
618          */
619         public function addSharedPost(array $item, string $body = ''): string
620         {
621                 if (empty($body)) {
622                         $body = $item['body'];
623                 }
624
625                 if (empty($item['quote-uri-id'])) {
626                         return $body;
627                 }
628
629                 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'quote-uri-id'];
630                 $shared_item = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [$item['uid'], 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
631                 if (!DBA::isResult($shared_item)) {
632                         Logger::notice('Post does not exist.', ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid']]);
633                         return $body;
634                 }
635
636                 return trim(BBCode::removeSharedData($body) . "\n" . $this->createSharedBlockByArray($shared_item, true));
637         }
638
639         /**
640          * Add a share block for the given guid
641          *
642          * @param string $guid
643          * @param integer $uid
644          * @param bool $add_media
645          * @return string
646          */
647         private function createSharedPostByGuid(string $guid, bool $add_media): string
648         {
649                 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
650                 $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => 0, 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
651
652                 if (!DBA::isResult($shared_item)) {
653                         Logger::notice('Post does not exist.', ['guid' => $guid]);
654                         return '';
655                 }
656
657                 return $this->createSharedBlockByArray($shared_item, $add_media);
658         }
659
660         /**
661          * Add a share block for the given item array
662          *
663          * @param array $item
664          * @param bool $add_media
665          * @return string
666          */
667         public function createSharedBlockByArray(array $item, bool $add_media = false): string
668         {
669                 if ($item['network'] == Protocol::FEED) {
670                         return PageInfo::getFooterFromUrl($item['plink']);
671                 } elseif (!in_array($item['network'] ?? '', Protocol::FEDERATED)) {
672                         $item['guid'] = '';
673                         $item['uri']  = '';
674                 }
675
676                 if ($add_media) {
677                         $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
678                 }
679
680                 $shared_content = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid'], $item['uri']);
681
682                 if (!empty($item['title'])) {
683                         $shared_content .= '[h3]' . $item['title'] . "[/h3]\n";
684                 }
685
686                 $shared = $this->getShareArray($item);
687
688                 // If it is a reshared post then reformat it to avoid display problems with two share elements
689                 if (!empty($shared)) {
690                         if (!empty($shared['guid']) && ($encapsulated_share = $this->createSharedPostByGuid($shared['guid'], true))) {
691                                 if (!empty(BBCode::fetchShareAttributes($item['body']))) {
692                                         $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $encapsulated_share, $item['body']);
693                                 } else {
694                                         $item['body'] .= $encapsulated_share;
695                                 }
696                         }
697                         $item['body'] = HTML::toBBCode(BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::ACTIVITYPUB));
698                 }
699
700                 $shared_content .= $item['body'] . '[/share]';
701
702                 return $shared_content;
703         }
704
705         /**
706          * Return the shared post from an item array (if the item is shared item)
707          *
708          * @param array $item
709          * @param array $fields
710          *
711          * @return array with the shared post
712          */
713         public function getSharedPost(array $item, array $fields = []): array
714         {
715                 if (!empty($item['quote-uri-id'])) {
716                         $shared = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [0, $item['uid'] ?? 0]]);
717                         if (is_array($shared)) {
718                                 return [
719                                         'comment' => BBCode::removeSharedData($item['body'] ?? ''),
720                                         'post'    => $shared
721                                 ];
722                         }
723                 }
724
725                 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
726                 if (!empty($attributes)) {
727                         $shared = Post::selectFirst($fields, ['guid' => $attributes['guid'], 'uid' => [0, $item['uid'] ?? 0]]);
728                         if (is_array($shared)) {
729                                 return [
730                                         'comment' => $attributes['comment'],
731                                         'post'    => $shared
732                                 ];
733                         }
734                 }
735
736                 return [];
737         }
738
739         /**
740          * Return share data from an item array (if the item is shared item)
741          * We are providing the complete Item array, because at some time in the future
742          * we hopefully will define these values not in the body anymore but in some item fields.
743          * This function is meant to replace all similar functions in the system.
744          *
745          * @param array $item
746          *
747          * @return array with share information
748          */
749         private function getShareArray(array $item): array
750         {
751                 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
752                 if (!empty($attributes)) {
753                         return $attributes;
754                 }
755
756                 if (!empty($item['quote-uri-id'])) {
757                         $shared = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'uri', 'body'], ['uri-id' => $item['quote-uri-id']]);
758                         if (!empty($shared)) {
759                                 return [
760                                         'author'     => $shared['author-name'],
761                                         'profile'    => $shared['author-link'],
762                                         'avatar'     => $shared['author-avatar'],
763                                         'link'       => $shared['plink'],
764                                         'posted'     => $shared['created'],
765                                         'guid'       => $shared['guid'],
766                                         'message_id' => $shared['uri'],
767                                         'comment'    => $item['body'],
768                                         'shared'     => $shared['body'],
769                                 ];
770                         }
771                 }
772
773                 return [];
774         }
775
776         /**
777          * Add a link to a shared post at the end of the post
778          *
779          * @param string  $body
780          * @param integer $quote_uri_id
781          * @return string
782          */
783         public function addShareLink(string $body, int $quote_uri_id): string
784         {
785                 $post = Post::selectFirstPost(['uri', 'plink'], ['uri-id' => $quote_uri_id]);
786                 if (empty($post)) {
787                         return $body;
788                 }
789
790                 $body = BBCode::removeSharedData($body);
791
792                 $body .= "\n♲ " . ($post['plink'] ?: $post['uri']);
793
794                 return $body;
795         }
796
797         public function storeAttachmentFromRequest(array $request): string
798         {
799                 $attachment_type  = $request['attachment_type'] ??  '';
800                 $attachment_title = $request['attachment_title'] ?? '';
801                 $attachment_text  = $request['attachment_text'] ??  '';
802
803                 $attachment_url     = hex2bin($request['attachment_url'] ??     '');
804                 $attachment_img_src = hex2bin($request['attachment_img_src'] ?? '');
805
806                 $attachment_img_width  = $request['attachment_img_width'] ??  0;
807                 $attachment_img_height = $request['attachment_img_height'] ?? 0;
808
809                 // Fetch the basic attachment data
810                 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
811                 unset($attachment['keywords']);
812
813                 // Overwrite the basic data with possible changes from the frontend
814                 $attachment['type'] = $attachment_type;
815                 $attachment['title'] = $attachment_title;
816                 $attachment['text'] = $attachment_text;
817                 $attachment['url'] = $attachment_url;
818
819                 if (!empty($attachment_img_src)) {
820                         $attachment['images'] = [
821                                 0 => [
822                                         'src'    => $attachment_img_src,
823                                         'width'  => $attachment_img_width,
824                                         'height' => $attachment_img_height
825                                 ]
826                         ];
827                 } else {
828                         unset($attachment['images']);
829                 }
830
831                 return "\n" . PageInfo::getFooterFromData($attachment);
832         }
833
834         public function addCategories(array $post, string $category): array
835         {
836                 if (!empty($post['file'])) {
837                         // get the "fileas" tags for this post
838                         $filedas = FileTag::fileToArray($post['file']);
839                 }
840
841                 $list_array = explode(',', trim($category));
842                 $post['file'] = FileTag::arrayToFile($list_array, 'category');
843
844                 if (!empty($filedas) && is_array($filedas)) {
845                         // append the fileas stuff to the new categories list
846                         $post['file'] .= FileTag::arrayToFile($filedas);
847                 }
848                 return $post;
849         }
850
851         public function getACL(array $post, array $toplevel_item, array $request): array
852         {
853                 // If this is a comment, set the permissions from the parent.
854                 if ($toplevel_item) {
855                         $post['allow_cid'] = $toplevel_item['allow_cid'] ?? '';
856                         $post['allow_gid'] = $toplevel_item['allow_gid'] ?? '';
857                         $post['deny_cid']  = $toplevel_item['deny_cid'] ?? '';
858                         $post['deny_gid']  = $toplevel_item['deny_gid'] ?? '';
859                         $post['private']   = $toplevel_item['private'];
860                         return $post;
861                 }
862
863                 $user = User::getById($post['uid'], ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
864                 if (!$user) {
865                         throw new HTTPException\NotFoundException($this->l10n->t('Unable to fetch user.'));
866                 }
867
868                 $post['allow_cid'] = isset($request['contact_allow']) ? $this->aclFormatter->toString($request['contact_allow']) : $user['allow_cid'] ?? '';
869                 $post['allow_gid'] = isset($request['circle_allow'])  ? $this->aclFormatter->toString($request['circle_allow'])  : $user['allow_gid'] ?? '';
870                 $post['deny_cid']  = isset($request['contact_deny'])  ? $this->aclFormatter->toString($request['contact_deny'])  : $user['deny_cid']  ?? '';
871                 $post['deny_gid']  = isset($request['circle_deny'])   ? $this->aclFormatter->toString($request['circle_deny'])   : $user['deny_gid']  ?? '';
872
873                 $visibility = $request['visibility'] ?? '';
874                 if ($visibility === 'public') {
875                         // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
876                         $post['allow_cid'] = $post['allow_gid'] = $post['deny_cid'] = $post['deny_gid'] = '';
877                 } else if ($visibility === 'custom') {
878                         // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
879                         // case that would make it public. So we always append the author's contact id to the allowed contacts.
880                         // See https://github.com/friendica/friendica/issues/9672
881                         $post['allow_cid'] .= $this->aclFormatter->toString(Contact::getPublicIdByUserId($post['uid']));
882                 }
883
884                 if ($post['allow_gid'] || $post['allow_cid'] || $post['deny_gid'] || $post['deny_cid']) {
885                         $post['private'] = ItemModel::PRIVATE;
886                 } elseif ($this->pConfig->get($post['uid'], 'system', 'unlisted')) {
887                         $post['private'] = ItemModel::UNLISTED;
888                 } else {
889                         $post['private'] = ItemModel::PUBLIC;
890                 }
891
892                 return $post;
893         }
894
895         public function moveAttachmentsFromBodyToAttach(array $post): array
896         {
897                 if (!preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/', $post['body'], $match)) {
898                         return $post;
899                 }
900
901                 foreach ($match[2] as $attachment_id) {
902                         $attachment = Attach::selectFirst(['id', 'uid', 'filename', 'filesize', 'filetype'], ['id' => $attachment_id, 'uid' => $post['uid']]);
903                         if (empty($attachment)) {
904                                 continue;
905                         }
906                         if ($post['attach']) {
907                                 $post['attach'] .= ',';
908                         }
909                         $post['attach'] .= Post\Media::getAttachElement(
910                                 $this->baseURL . '/attach/' . $attachment['id'],
911                                 $attachment['filesize'],
912                                 $attachment['filetype'],
913                                 $attachment['filename'] ?? ''
914                         );
915
916                         $fields = [
917                                 'allow_cid' => $post['allow_cid'], 'allow_gid' => $post['allow_gid'],
918                                 'deny_cid' => $post['deny_cid'], 'deny_gid' => $post['deny_gid']
919                         ];
920                         $condition = ['id' => $attachment_id];
921                         Attach::update($fields, $condition);
922                 }
923
924                 $post['body'] = str_replace($match[1], '', $post['body']);
925
926                 return $post;
927         }
928
929         private function setObjectType(array $post): array
930         {
931                 if (empty($post['post-type'])) {
932                         $post['post-type'] = empty($post['title']) ? ItemModel::PT_NOTE : ItemModel::PT_ARTICLE;
933                 }
934
935                 // embedded bookmark or attachment in post? set bookmark flag
936                 $data = BBCode::getAttachmentData($post['body']);
937                 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $post['body'], $match, PREG_SET_ORDER) || !empty($data['type']))
938                         && ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE)
939                 ) {
940                         $post['post-type'] = ItemModel::PT_PAGE;
941                         $post['object-type'] = Activity\ObjectType::BOOKMARK;
942                 }
943
944                 // Setting the object type if not defined before
945                 if (empty($post['object-type'])) {
946                         $post['object-type'] = ($post['gravity'] == ItemModel::GRAVITY_PARENT) ? Activity\ObjectType::NOTE : Activity\ObjectType::COMMENT;
947                 }
948                 return $post;
949         }
950
951         public function initializePost(array $post): array
952         {
953                 $post['network']    = Protocol::DFRN;
954                 $post['protocol']   = Conversation::PARCEL_DIRECT;
955                 $post['direction']  = Conversation::PUSH;
956                 $post['received']   = DateTimeFormat::utcNow();
957                 $post['origin']     = true;
958                 $post['wall']       = $post['wall'] ?? true;
959                 $post['guid']       = $post['guid'] ?? System::createUUID();
960                 $post['verb']       = $post['verb'] ?? Activity::POST;
961                 $post['uri']        = $post['uri'] ?? ItemModel::newURI($post['guid']);
962                 $post['thr-parent'] = $post['thr-parent'] ?? $post['uri'];
963
964                 if (empty($post['gravity'])) {
965                         $post['gravity'] = ($post['uri'] == $post['thr-parent']) ? ItemModel::GRAVITY_PARENT : ItemModel::GRAVITY_COMMENT;
966                 }
967
968                 $owner = User::getOwnerDataById($post['uid']);
969
970                 if (!isset($post['allow_cid']) || !isset($post['allow_gid']) || !isset($post['deny_cid']) || !isset($post['deny_gid'])) {
971                         $post['allow_cid'] = $owner['allow_cid'];
972                         $post['allow_gid'] = $owner['allow_gid'];
973                         $post['deny_cid']  = $owner['deny_cid'];
974                         $post['deny_gid']  = $owner['deny_gid'];
975                 }
976
977                 if ($post['allow_gid'] || $post['allow_cid'] || $post['deny_gid'] || $post['deny_cid']) {
978                         $post['private'] = ItemModel::PRIVATE;
979                 } elseif ($this->pConfig->get($post['uid'], 'system', 'unlisted')) {
980                         $post['private'] = ItemModel::UNLISTED;
981                 } else {
982                         $post['private'] = ItemModel::PUBLIC;
983                 }
984
985                 if (empty($post['contact-id'])) {
986                         $post['contact-id'] = $owner['id'];
987                 }
988
989                 if (empty($post['author-link']) && empty($post['author-id'])) {
990                         $post['author-link']   = $owner['url'];
991                         $post['author-id']     = Contact::getIdForURL($post['author-link']);
992                         $post['author-name']   = $owner['name'];
993                         $post['author-avatar'] = $owner['thumb'];
994                 }
995
996                 if (empty($post['owner-link']) && empty($post['owner-id'])) {
997                         $post['owner-link']   = $post['author-link'];
998                         $post['owner-id']     = Contact::getIdForURL($post['owner-link']);
999                         $post['owner-name']   = $post['author-name'];
1000                         $post['owner-avatar'] = $post['author-avatar'];
1001                 }
1002
1003                 return $post;
1004         }
1005
1006         public function finalizePost(array $post): array
1007         {
1008                 if (preg_match("/\[attachment\](.*?)\[\/attachment\]/ism", $post['body'], $matches)) {
1009                         $post['body'] = preg_replace("/\[attachment].*?\[\/attachment\]/ism", PageInfo::getFooterFromUrl($matches[1]), $post['body']);
1010                 }
1011
1012                 // Convert links with empty descriptions to links without an explicit description
1013                 $post['body'] = trim(preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $post['body']));
1014                 $post['body'] = $this->bbCodeVideo->transform($post['body']);
1015                 $post = $this->setObjectType($post);
1016
1017                 // Personal notes must never be altered to a group post.
1018                 if ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE) {
1019                         // Look for any tags and linkify them
1020                         $post = $this->expandTags($post);
1021                 }
1022
1023                 return $post;
1024         }
1025
1026         public function postProcessPost(array $post, array $recipients = [])
1027         {
1028                 if (!\Friendica\Content\Feature::isEnabled($post['uid'], 'explicit_mentions') && ($post['gravity'] == ItemModel::GRAVITY_COMMENT)) {
1029                         Tag::createImplicitMentions($post['uri-id'], $post['thr-parent-id']);
1030                 }
1031
1032                 Hook::callAll('post_local_end', $post);
1033
1034                 $author = DBA::selectFirst('contact', ['thumb'], ['uid' => $post['uid'], 'self' => true]);
1035
1036                 foreach ($recipients as $recipient) {
1037                         $address = trim($recipient);
1038                         if (!$address) {
1039                                 continue;
1040                         }
1041
1042                         $this->emailer->send(new ItemCCEMail(
1043                                 $this->app,
1044                                 $this->l10n,
1045                                 $this->baseURL,
1046                                 $post,
1047                                 $address,
1048                                 $author['thumb'] ?? ''
1049                         ));
1050                 }
1051         }
1052 }