3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Content;
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;
59 * A content helper class for displaying items
69 /** @var IHandleUserSessions */
73 /** @var ACLFormatter */
74 private $aclFormatter;
75 /** @var IManagePersonalConfigValues */
84 public function __construct(Profiler $profiler, Activity $activity, L10n $l10n, IHandleUserSessions $userSession, Video $bbCodeVideo, ACLFormatter $aclFormatter, IManagePersonalConfigValues $pConfig, BaseURL $baseURL, Emailer $emailer, App $app)
86 $this->profiler = $profiler;
87 $this->activity = $activity;
89 $this->userSession = $userSession;
90 $this->bbCodeVideo = $bbCodeVideo;
91 $this->aclFormatter = $aclFormatter;
92 $this->baseURL = $baseURL;
93 $this->pConfig = $pConfig;
94 $this->emailer = $emailer;
99 * Lists categories and folders for an item
105 * [ // categories array
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',
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',
127 public function determineCategoriesTerms(array $item, int $uid = 0): array
133 $uid = $item['uid'] ?: $uid;
135 if (empty($item['has-categories'])) {
136 return [$categories, $folders];
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);
146 'name' => $savedFolderName,
148 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '',
155 if (count($categories)) {
156 $categories[count($categories) - 1]['last'] = true;
159 if ($this->userSession->getLocalUserId() == $uid) {
160 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) {
162 'name' => $savedFolderName,
164 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '',
172 if (count($folders)) {
173 $folders[count($folders) - 1]['last'] = true;
176 return [$categories, $folders];
180 * This function removes the tag $tag from the text $body and replaces it with
181 * the appropriate link.
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
188 * @return array|bool ['replaced' => $replaced, 'contact' => $contact] or "false" on if already replaced
189 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
190 * @throws \ImagickException
192 public static function replaceTag(string &$body, int $profile_uid, string $tag, string $network = '')
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=')) {
204 //get the person's name
205 $name = substr($tag, 1);
207 // Sometimes the tag detection doesn't seem to work right
208 // This is some workaround
209 $nameparts = explode(' ', $name);
210 $name = $nameparts[0];
212 // Try to detect the contact in various ways
213 if (strpos($name, 'http://') || strpos($name, '@')) {
214 $contact = Contact::getByURLForUser($name, $profile_uid);
217 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
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]);
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);
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);
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);
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);
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);
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);
262 // Check if $contact has been successfully loaded
263 if (DBA::isResult($contact)) {
264 $profile = $contact['url'];
265 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
268 //if there is an url for this persons profile
269 if (isset($profile) && ($newname != '')) {
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);
278 return ['replaced' => $replaced, 'contact' => $contact];
282 * Render actions localized
286 * @throws ImagickException
287 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
289 public function localize(array &$item)
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" ?>';
296 if ($this->activity->match($item['verb'], Activity::TAG)) {
298 'author-id', 'author-link', 'author-name', 'author-network',
299 'verb', 'object-type', 'resource-id', 'body', 'plink'
301 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
302 if (!DBA::isResult($obj)) {
303 $this->profiler->stopRecording();
309 'id' => $item['author-id'],
310 'network' => $item['author-network'],
311 'url' => $item['author-link'],
313 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
317 'id' => $obj['author-id'],
318 'network' => $obj['author-network'],
319 'url' => $obj['author-link'],
321 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
323 switch ($obj['verb']) {
325 switch ($obj['object-type']) {
326 case Activity\ObjectType::EVENT:
327 $post_type = $this->l10n->t('event');
330 $post_type = $this->l10n->t('status');
335 if ($obj['resource-id']) {
336 $post_type = $this->l10n->t('photo');
337 preg_match("/\[url=([^]]*)\]/", $obj['body'], $matches);
338 $rr['plink'] = $matches[1];
340 $post_type = $this->l10n->t('status');
342 // Let's break everything ... ;-)
345 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
347 $parsedobj = XML::parseString($xmlhead . $item['object']);
349 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
350 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
354 $this->profiler->stopRecording();
358 * Renders photo menu based on item
361 * @param string $formSecurityToken
364 public function photoMenu(array $item, string $formSecurityToken): string
366 $this->profiler->startRecording('rendering');
367 $sub_link = $contact_url = $pm_url = $status_link = '';
368 $photos_link = $posts_link = $block_link = $ignore_link = '';
370 if ($this->userSession->getLocalUserId() && $this->userSession->getLocalUserId() == $item['uid'] && $item['gravity'] == ItemModel::GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
371 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
376 'id' => $item['author-id'],
377 'network' => $item['author-network'],
378 'url' => $item['author-link'],
380 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
381 if (strpos($profile_link, 'contact/redir/') === 0) {
382 $status_link = $profile_link . '?' . http_build_query(['url' => $item['author-link'] . '/status']);
383 $photos_link = $profile_link . '?' . http_build_query(['url' => $item['author-link'] . '/photos']);
384 $profile_link = $profile_link . '?' . http_build_query(['url' => $item['author-link'] . '/profile']);
388 $pcid = $item['author-id'];
391 $condition = ['uid' => $this->userSession->getLocalUserId(), 'uri-id' => $item['author-uri-id']];
392 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
393 if (DBA::isResult($contact)) {
394 $cid = $contact['id'];
395 $network = $contact['network'];
396 $rel = $contact['rel'];
400 $contact_url = 'contact/' . $pcid;
401 $posts_link = $contact_url . '/posts';
402 $block_link = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
403 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
404 $collapse_link = $item['self'] ? '' : $contact_url . '/collapse?t=' . $formSecurityToken;
407 if ($cid && !$item['self']) {
408 $contact_url = 'contact/' . $cid;
409 $posts_link = $contact_url . '/posts';
411 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
412 $pm_url = 'message/new/' . $cid;
416 if ($this->userSession->getLocalUserId()) {
418 $this->l10n->t('Follow Thread') => $sub_link,
419 $this->l10n->t('View Status') => $status_link,
420 $this->l10n->t('View Profile') => $profile_link,
421 $this->l10n->t('View Photos') => $photos_link,
422 $this->l10n->t('Network Posts') => $posts_link,
423 $this->l10n->t('View Contact') => $contact_url,
424 $this->l10n->t('Send PM') => $pm_url,
425 $this->l10n->t('Block') => $block_link,
426 $this->l10n->t('Ignore') => $ignore_link,
427 $this->l10n->t('Collapse') => $collapse_link
430 if (!empty($item['language'])) {
431 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ItemModel::getLanguageMessage($item) . '\');';
434 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
435 in_array($item['network'], Protocol::FEDERATED)
437 $menu[$this->l10n->t('Connect/Follow')] = 'contact/follow?url=' . urlencode($item['author-link']) . '&auto=1';
440 $menu = [$this->l10n->t('View Profile') => $item['author-link']];
443 $args = ['item' => $item, 'menu' => $menu];
445 Hook::callAll('item_photo_menu', $args);
447 $menu = $args['menu'];
450 foreach ($menu as $k => $v) {
451 if (strpos($v, 'javascript:') === 0) {
453 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
455 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
458 $this->profiler->stopRecording();
463 * Checks if the activity is visible to current user
465 * @param array $item Activity item
466 * @return bool Whether the item is visible to the user
468 public function isVisibleActivity(array $item): bool
470 // Empty verb or hidden?
471 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
476 return (!($this->activity->match($item['verb'], Activity::FOLLOW) &&
477 $item['object-type'] === Activity\ObjectType::NOTE &&
478 empty($item['self']) &&
479 $item['uid'] == $this->userSession->getLocalUserId())
483 public function expandTags(array $item, bool $setPermissions = false): array
485 // Look for any tags and linkify them
486 $item['inform'] = '';
487 $private_group = false;
489 $only_to_group = false;
493 // Convert mentions in the body to a unified format
494 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
496 // Search for group mentions
497 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
498 $contact = Contact::getByURLForUser($tag[2], $item['uid']);
499 if (empty($contact)) {
503 $receivers[] = $contact['id'];
505 if (!empty($item['inform'])) {
506 $item['inform'] .= ',';
508 $item['inform'] .= 'cid:' . $contact['id'];
510 if (($item['gravity'] == ItemModel::GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
514 if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
515 $private_group = $contact['prv'];
516 $only_to_group = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
517 $private_id = $contact['id'];
518 $group_contact = $contact;
519 Logger::info('Private group or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
520 } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
521 $private_group = false;
522 $only_to_group = true;
523 $private_id = $contact['id'];
524 $group_contact = $contact;
525 Logger::info('Public group', ['url' => $tag[2], 'mention' => $tag[1]]);
527 Logger::info('Post with group mention will not be converted to a group post', ['url' => $tag[2], 'mention' => $tag[1]]);
530 Logger::info('Got inform', ['inform' => $item['inform']]);
532 if (($item['gravity'] == ItemModel::GRAVITY_PARENT) && !empty($group_contact) && ($private_group || $only_to_group)) {
533 // we tagged a group in a top level post. Now we change the post
534 $item['private'] = $private_group ? ItemModel::PRIVATE : ItemModel::UNLISTED;
536 if ($only_to_group) {
537 $item['postopts'] = '';
540 $item['deny_cid'] = '';
541 $item['deny_gid'] = '';
543 if ($private_group) {
544 $item['allow_cid'] = '<' . $private_id . '>';
545 $item['allow_gid'] = '<' . Circle::getIdForGroup($group_contact['id']) . '>';
547 $item['allow_cid'] = '';
548 $item['allow_gid'] = '';
550 } elseif ($setPermissions) {
551 if (empty($receivers)) {
552 // For security reasons direct posts without any receiver will be posts to yourself
553 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
554 $receivers[] = $self['id'];
557 $item['private'] = ItemModel::PRIVATE;
558 $item['allow_cid'] = '';
559 $item['allow_gid'] = '';
560 $item['deny_cid'] = '';
561 $item['deny_gid'] = '';
563 foreach ($receivers as $receiver) {
564 $item['allow_cid'] .= '<' . $receiver . '>';
570 public function getAuthorAvatar(array $item): string
572 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
573 $author_avatar = $item['contact-id'];
574 $author_updated = '';
575 $author_thumb = $item['contact-avatar'];
577 $author_avatar = $item['author-id'];
578 $author_updated = $item['author-updated'];
579 $author_thumb = $item['author-avatar'];
583 if (empty($author_thumb) || Photo::isPhotoURI($author_thumb)) {
584 $author_thumb = Contact::getAvatarUrlForId($author_avatar, Proxy::SIZE_THUMB, $author_updated);
587 return $author_thumb;
590 public function getOwnerAvatar(array $item): string
592 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
593 $owner_avatar = $item['contact-id'];
595 $owner_thumb = $item['contact-avatar'];
597 $owner_avatar = $item['owner-id'];
598 $owner_updated = $item['owner-updated'];
599 $owner_thumb = $item['owner-avatar'];
602 if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) {
603 $owner_thumb = Contact::getAvatarUrlForId($owner_avatar, Proxy::SIZE_THUMB, $owner_updated);
610 * Add a share block for the given uri-id
613 * @param string $body
616 public function addSharedPost(array $item, string $body = ''): string
619 $body = $item['body'];
622 if (empty($item['quote-uri-id'])) {
626 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'quote-uri-id'];
627 $shared_item = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [$item['uid'], 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
628 if (!DBA::isResult($shared_item)) {
629 Logger::notice('Post does not exist.', ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid']]);
633 return trim(BBCode::removeSharedData($body) . "\n" . $this->createSharedBlockByArray($shared_item, true));
637 * Add a share block for the given guid
639 * @param string $guid
640 * @param integer $uid
641 * @param bool $add_media
644 private function createSharedPostByGuid(string $guid, bool $add_media): string
646 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
647 $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => 0, 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
649 if (!DBA::isResult($shared_item)) {
650 Logger::notice('Post does not exist.', ['guid' => $guid]);
654 return $this->createSharedBlockByArray($shared_item, $add_media);
658 * Add a share block for the given item array
661 * @param bool $add_media
664 public function createSharedBlockByArray(array $item, bool $add_media = false): string
666 if ($item['network'] == Protocol::FEED) {
667 return PageInfo::getFooterFromUrl($item['plink']);
668 } elseif (!in_array($item['network'] ?? '', Protocol::FEDERATED)) {
674 $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
677 $shared_content = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid'], $item['uri']);
679 if (!empty($item['title'])) {
680 $shared_content .= '[h3]' . $item['title'] . "[/h3]\n";
683 $shared = $this->getShareArray($item);
685 // If it is a reshared post then reformat it to avoid display problems with two share elements
686 if (!empty($shared)) {
687 if (!empty($shared['guid']) && ($encapsulated_share = $this->createSharedPostByGuid($shared['guid'], true))) {
688 if (!empty(BBCode::fetchShareAttributes($item['body']))) {
689 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $encapsulated_share, $item['body']);
691 $item['body'] .= $encapsulated_share;
694 $item['body'] = HTML::toBBCode(BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::ACTIVITYPUB));
697 $shared_content .= $item['body'] . '[/share]';
699 return $shared_content;
703 * Return the shared post from an item array (if the item is shared item)
706 * @param array $fields
708 * @return array with the shared post
710 public function getSharedPost(array $item, array $fields = []): array
712 if (!empty($item['quote-uri-id'])) {
713 $shared = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [0, $item['uid'] ?? 0]]);
714 if (is_array($shared)) {
716 'comment' => BBCode::removeSharedData($item['body'] ?? ''),
722 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
723 if (!empty($attributes)) {
724 $shared = Post::selectFirst($fields, ['guid' => $attributes['guid'], 'uid' => [0, $item['uid'] ?? 0]]);
725 if (is_array($shared)) {
727 'comment' => $attributes['comment'],
737 * Return share data from an item array (if the item is shared item)
738 * We are providing the complete Item array, because at some time in the future
739 * we hopefully will define these values not in the body anymore but in some item fields.
740 * This function is meant to replace all similar functions in the system.
744 * @return array with share information
746 private function getShareArray(array $item): array
748 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
749 if (!empty($attributes)) {
753 if (!empty($item['quote-uri-id'])) {
754 $shared = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'uri', 'body'], ['uri-id' => $item['quote-uri-id']]);
755 if (!empty($shared)) {
757 'author' => $shared['author-name'],
758 'profile' => $shared['author-link'],
759 'avatar' => $shared['author-avatar'],
760 'link' => $shared['plink'],
761 'posted' => $shared['created'],
762 'guid' => $shared['guid'],
763 'message_id' => $shared['uri'],
764 'comment' => $item['body'],
765 'shared' => $shared['body'],
774 * Add a link to a shared post at the end of the post
776 * @param string $body
777 * @param integer $quote_uri_id
780 public function addShareLink(string $body, int $quote_uri_id): string
782 $post = Post::selectFirstPost(['uri', 'plink'], ['uri-id' => $quote_uri_id]);
787 $body = BBCode::removeSharedData($body);
789 $body .= "\n♲ " . ($post['plink'] ?: $post['uri']);
794 public function storeAttachmentFromRequest(array $request): string
796 $attachment_type = $request['attachment_type'] ?? '';
797 $attachment_title = $request['attachment_title'] ?? '';
798 $attachment_text = $request['attachment_text'] ?? '';
800 $attachment_url = hex2bin($request['attachment_url'] ?? '');
801 $attachment_img_src = hex2bin($request['attachment_img_src'] ?? '');
803 $attachment_img_width = $request['attachment_img_width'] ?? 0;
804 $attachment_img_height = $request['attachment_img_height'] ?? 0;
806 // Fetch the basic attachment data
807 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
808 unset($attachment['keywords']);
810 // Overwrite the basic data with possible changes from the frontend
811 $attachment['type'] = $attachment_type;
812 $attachment['title'] = $attachment_title;
813 $attachment['text'] = $attachment_text;
814 $attachment['url'] = $attachment_url;
816 if (!empty($attachment_img_src)) {
817 $attachment['images'] = [
819 'src' => $attachment_img_src,
820 'width' => $attachment_img_width,
821 'height' => $attachment_img_height
825 unset($attachment['images']);
828 return "\n" . PageInfo::getFooterFromData($attachment);
831 public function addCategories(array $post, string $category): array
833 if (!empty($post['file'])) {
834 // get the "fileas" tags for this post
835 $filedas = FileTag::fileToArray($post['file']);
838 $list_array = explode(',', trim($category));
839 $post['file'] = FileTag::arrayToFile($list_array, 'category');
841 if (!empty($filedas) && is_array($filedas)) {
842 // append the fileas stuff to the new categories list
843 $post['file'] .= FileTag::arrayToFile($filedas);
848 public function getACL(array $post, array $toplevel_item, array $request): array
850 // If this is a comment, set the permissions from the parent.
851 if ($toplevel_item) {
852 $post['allow_cid'] = $toplevel_item['allow_cid'] ?? '';
853 $post['allow_gid'] = $toplevel_item['allow_gid'] ?? '';
854 $post['deny_cid'] = $toplevel_item['deny_cid'] ?? '';
855 $post['deny_gid'] = $toplevel_item['deny_gid'] ?? '';
856 $post['private'] = $toplevel_item['private'];
860 $user = User::getById($post['uid'], ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
862 throw new HTTPException\NotFoundException($this->l10n->t('Unable to fetch user.'));
865 $post['allow_cid'] = isset($request['contact_allow']) ? $this->aclFormatter->toString($request['contact_allow']) : $user['allow_cid'] ?? '';
866 $post['allow_gid'] = isset($request['circle_allow']) ? $this->aclFormatter->toString($request['circle_allow']) : $user['allow_gid'] ?? '';
867 $post['deny_cid'] = isset($request['contact_deny']) ? $this->aclFormatter->toString($request['contact_deny']) : $user['deny_cid'] ?? '';
868 $post['deny_gid'] = isset($request['circle_deny']) ? $this->aclFormatter->toString($request['circle_deny']) : $user['deny_gid'] ?? '';
870 $visibility = $request['visibility'] ?? '';
871 if ($visibility === 'public') {
872 // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
873 $post['allow_cid'] = $post['allow_gid'] = $post['deny_cid'] = $post['deny_gid'] = '';
874 } else if ($visibility === 'custom') {
875 // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
876 // case that would make it public. So we always append the author's contact id to the allowed contacts.
877 // See https://github.com/friendica/friendica/issues/9672
878 $post['allow_cid'] .= $this->aclFormatter->toString(Contact::getPublicIdByUserId($post['uid']));
881 if ($post['allow_gid'] || $post['allow_cid'] || $post['deny_gid'] || $post['deny_cid']) {
882 $post['private'] = ItemModel::PRIVATE;
883 } elseif ($this->pConfig->get($post['uid'], 'system', 'unlisted')) {
884 $post['private'] = ItemModel::UNLISTED;
886 $post['private'] = ItemModel::PUBLIC;
892 public function moveAttachmentsFromBodyToAttach(array $post): array
894 if (!preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/', $post['body'], $match)) {
898 foreach ($match[2] as $attachment_id) {
899 $attachment = Attach::selectFirst(['id', 'uid', 'filename', 'filesize', 'filetype'], ['id' => $attachment_id, 'uid' => $post['uid']]);
900 if (empty($attachment)) {
903 if ($post['attach']) {
904 $post['attach'] .= ',';
906 $post['attach'] .= Post\Media::getAttachElement(
907 $this->baseURL . '/attach/' . $attachment['id'],
908 $attachment['filesize'],
909 $attachment['filetype'],
910 $attachment['filename'] ?? ''
914 'allow_cid' => $post['allow_cid'], 'allow_gid' => $post['allow_gid'],
915 'deny_cid' => $post['deny_cid'], 'deny_gid' => $post['deny_gid']
917 $condition = ['id' => $attachment_id];
918 Attach::update($fields, $condition);
921 $post['body'] = str_replace($match[1], '', $post['body']);
926 private function setObjectType(array $post): array
928 if (empty($post['post-type'])) {
929 $post['post-type'] = empty($post['title']) ? ItemModel::PT_NOTE : ItemModel::PT_ARTICLE;
932 // embedded bookmark or attachment in post? set bookmark flag
933 $data = BBCode::getAttachmentData($post['body']);
934 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $post['body'], $match, PREG_SET_ORDER) || !empty($data['type']))
935 && ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE)
937 $post['post-type'] = ItemModel::PT_PAGE;
938 $post['object-type'] = Activity\ObjectType::BOOKMARK;
941 // Setting the object type if not defined before
942 if (empty($post['object-type'])) {
943 $post['object-type'] = ($post['gravity'] == ItemModel::GRAVITY_PARENT) ? Activity\ObjectType::NOTE : Activity\ObjectType::COMMENT;
948 public function initializePost(array $post): array
950 $post['network'] = Protocol::DFRN;
951 $post['protocol'] = Conversation::PARCEL_DIRECT;
952 $post['direction'] = Conversation::PUSH;
953 $post['received'] = DateTimeFormat::utcNow();
954 $post['origin'] = true;
955 $post['wall'] = $post['wall'] ?? true;
956 $post['guid'] = $post['guid'] ?? System::createUUID();
957 $post['verb'] = $post['verb'] ?? Activity::POST;
958 $post['uri'] = $post['uri'] ?? ItemModel::newURI($post['guid']);
959 $post['thr-parent'] = $post['thr-parent'] ?? $post['uri'];
961 if (empty($post['gravity'])) {
962 $post['gravity'] = ($post['uri'] == $post['thr-parent']) ? ItemModel::GRAVITY_PARENT : ItemModel::GRAVITY_COMMENT;
965 $owner = User::getOwnerDataById($post['uid']);
967 if (!isset($post['allow_cid']) || !isset($post['allow_gid']) || !isset($post['deny_cid']) || !isset($post['deny_gid'])) {
968 $post['allow_cid'] = $owner['allow_cid'];
969 $post['allow_gid'] = $owner['allow_gid'];
970 $post['deny_cid'] = $owner['deny_cid'];
971 $post['deny_gid'] = $owner['deny_gid'];
974 if ($post['allow_gid'] || $post['allow_cid'] || $post['deny_gid'] || $post['deny_cid']) {
975 $post['private'] = ItemModel::PRIVATE;
976 } elseif ($this->pConfig->get($post['uid'], 'system', 'unlisted')) {
977 $post['private'] = ItemModel::UNLISTED;
979 $post['private'] = ItemModel::PUBLIC;
982 if (empty($post['contact-id'])) {
983 $post['contact-id'] = $owner['id'];
986 if (empty($post['author-link']) && empty($post['author-id'])) {
987 $post['author-link'] = $owner['url'];
988 $post['author-id'] = Contact::getIdForURL($post['author-link']);
989 $post['author-name'] = $owner['name'];
990 $post['author-avatar'] = $owner['thumb'];
993 if (empty($post['owner-link']) && empty($post['owner-id'])) {
994 $post['owner-link'] = $post['author-link'];
995 $post['owner-id'] = Contact::getIdForURL($post['owner-link']);
996 $post['owner-name'] = $post['author-name'];
997 $post['owner-avatar'] = $post['author-avatar'];
1003 public function finalizePost(array $post): array
1005 if (preg_match("/\[attachment\](.*?)\[\/attachment\]/ism", $post['body'], $matches)) {
1006 $post['body'] = preg_replace("/\[attachment].*?\[\/attachment\]/ism", PageInfo::getFooterFromUrl($matches[1]), $post['body']);
1009 // Convert links with empty descriptions to links without an explicit description
1010 $post['body'] = trim(preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $post['body']));
1011 $post['body'] = $this->bbCodeVideo->transform($post['body']);
1012 $post = $this->setObjectType($post);
1014 // Personal notes must never be altered to a group post.
1015 if ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE) {
1016 // Look for any tags and linkify them
1017 $post = $this->expandTags($post);
1023 public function postProcessPost(array $post, array $recipients = [])
1025 if (!\Friendica\Content\Feature::isEnabled($post['uid'], 'explicit_mentions') && ($post['gravity'] == ItemModel::GRAVITY_COMMENT)) {
1026 Tag::createImplicitMentions($post['uri-id'], $post['thr-parent-id']);
1029 Hook::callAll('post_local_end', $post);
1031 $author = DBA::selectFirst('contact', ['thumb'], ['uid' => $post['uid'], 'self' => true]);
1033 foreach ($recipients as $recipient) {
1034 $address = trim($recipient);
1039 $this->emailer->send(new ItemCCEMail(
1045 $author['thumb'] ?? ''