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;
24 use Friendica\App\BaseURL;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\BBCode\Video;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Core\Hook;
29 use Friendica\Core\L10n;
30 use Friendica\Core\Logger;
31 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Session\Capability\IHandleUserSessions;
34 use Friendica\Core\System;
35 use Friendica\Database\DBA;
36 use Friendica\Model\Attach;
37 use Friendica\Model\Contact;
38 use Friendica\Model\Conversation;
39 use Friendica\Model\FileTag;
40 use Friendica\Model\Group;
41 use Friendica\Model\Item as ItemModel;
42 use Friendica\Model\Photo;
43 use Friendica\Model\Tag;
44 use Friendica\Model\Post;
45 use Friendica\Model\User;
46 use Friendica\Network\HTTPException;
47 use Friendica\Protocol\Activity;
48 use Friendica\Util\ACLFormatter;
49 use Friendica\Util\DateTimeFormat;
50 use Friendica\Util\ParseUrl;
51 use Friendica\Util\Profiler;
52 use Friendica\Util\Proxy;
53 use Friendica\Util\XML;
56 * A content helper class for displaying items
66 /** @var IHandleUserSessions */
70 /** @var ACLFormatter */
71 private $aclFormatter;
72 /** @var IManagePersonalConfigValues */
77 public function __construct(Profiler $profiler, Activity $activity, L10n $l10n, IHandleUserSessions $userSession, Video $bbCodeVideo, ACLFormatter $aclFormatter, IManagePersonalConfigValues $pConfig, BaseURL $baseURL)
79 $this->profiler = $profiler;
80 $this->activity = $activity;
82 $this->userSession = $userSession;
83 $this->bbCodeVideo = $bbCodeVideo;
84 $this->aclFormatter = $aclFormatter;
85 $this->baseURL = $baseURL;
86 $this->pConfig = $pConfig;
90 * Return array with details for categories and folders for an item
94 * @return [array, array]
97 * [ // categories array
99 * 'name': 'category name',
100 * 'removeurl': 'url to remove this category',
101 * 'first': 'is the first in this array? true/false',
102 * 'last': 'is the last in this array? true/false',
108 * 'name': 'folder name',
109 * 'removeurl': 'url to remove this folder',
110 * 'first': 'is the first in this array? true/false',
111 * 'last': 'is the last in this array? true/false',
117 public function determineCategoriesTerms(array $item, int $uid = 0): array
123 $uid = $item['uid'] ?: $uid;
125 if (empty($item['has-categories'])) {
126 return [$categories, $folders];
129 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::CATEGORY) as $savedFolderName) {
130 if (!empty($item['author-link'])) {
131 $url = $item['author-link'] . "?category=" . rawurlencode($savedFolderName);
136 'name' => $savedFolderName,
138 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '',
145 if (count($categories)) {
146 $categories[count($categories) - 1]['last'] = true;
149 if ($this->userSession->getLocalUserId() == $uid) {
150 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) {
152 'name' => $savedFolderName,
154 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '',
162 if (count($folders)) {
163 $folders[count($folders) - 1]['last'] = true;
166 return [$categories, $folders];
170 * This function removes the tag $tag from the text $body and replaces it with
171 * the appropriate link.
173 * @param string $body the text to replace the tag in
174 * @param int $profile_uid the user id to replace the tag for (0 = anyone)
175 * @param string $tag the tag to replace
176 * @param string $network The network of the post
178 * @return array|bool ['replaced' => $replaced, 'contact' => $contact] or "false" on if already replaced
179 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
180 * @throws \ImagickException
182 public static function replaceTag(string &$body, int $profile_uid, string $tag, string $network = '')
186 //is it a person tag?
187 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
188 $tag_type = substr($tag, 0, 1);
189 //is it already replaced?
190 if (strpos($tag, '[url=')) {
194 //get the person's name
195 $name = substr($tag, 1);
197 // Sometimes the tag detection doesn't seem to work right
198 // This is some workaround
199 $nameparts = explode(' ', $name);
200 $name = $nameparts[0];
202 // Try to detect the contact in various ways
203 if (strpos($name, 'http://') || strpos($name, '@')) {
204 $contact = Contact::getByURLForUser($name, $profile_uid);
207 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
209 if (strrpos($name, '+')) {
210 // Is it in format @nick+number?
211 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
212 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
215 // select someone by nick in the current network
216 if (!DBA::isResult($contact) && ($network != '')) {
217 $condition = ["`nick` = ? AND `network` = ? AND `uid` = ?",
218 $name, $network, $profile_uid];
219 $contact = DBA::selectFirst('contact', $fields, $condition);
222 // select someone by attag in the current network
223 if (!DBA::isResult($contact) && ($network != '')) {
224 $condition = ["`attag` = ? AND `network` = ? AND `uid` = ?",
225 $name, $network, $profile_uid];
226 $contact = DBA::selectFirst('contact', $fields, $condition);
229 //select someone by name in the current network
230 if (!DBA::isResult($contact) && ($network != '')) {
231 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
232 $contact = DBA::selectFirst('contact', $fields, $condition);
235 // select someone by nick in any network
236 if (!DBA::isResult($contact)) {
237 $condition = ["`nick` = ? AND `uid` = ?", $name, $profile_uid];
238 $contact = DBA::selectFirst('contact', $fields, $condition);
241 // select someone by attag in any network
242 if (!DBA::isResult($contact)) {
243 $condition = ["`attag` = ? AND `uid` = ?", $name, $profile_uid];
244 $contact = DBA::selectFirst('contact', $fields, $condition);
247 // select someone by name in any network
248 if (!DBA::isResult($contact)) {
249 $condition = ['name' => $name, 'uid' => $profile_uid];
250 $contact = DBA::selectFirst('contact', $fields, $condition);
254 // Check if $contact has been successfully loaded
255 if (DBA::isResult($contact)) {
256 $profile = $contact['url'];
257 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
260 //if there is an url for this persons profile
261 if (isset($profile) && ($newname != '')) {
263 // create profile link
264 $profile = str_replace(',', '%2c', $profile);
265 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
266 $body = str_replace($tag_type . $name, $newtag, $body);
270 return ['replaced' => $replaced, 'contact' => $contact];
274 * Render actions localized
278 * @throws ImagickException
279 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
281 public function localize(array &$item)
283 $this->profiler->startRecording('rendering');
284 /// @todo The following functionality needs to be cleaned up.
285 if (!empty($item['verb'])) {
286 $xmlhead = '<?xml version="1.0" encoding="UTF-8" ?>';
288 if ($this->activity->match($item['verb'], Activity::TAG)) {
289 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
290 'verb', 'object-type', 'resource-id', 'body', 'plink'];
291 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
292 if (!DBA::isResult($obj)) {
293 $this->profiler->stopRecording();
299 'id' => $item['author-id'],
300 'network' => $item['author-network'],
301 'url' => $item['author-link'],
303 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
307 'id' => $obj['author-id'],
308 'network' => $obj['author-network'],
309 'url' => $obj['author-link'],
311 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
313 switch ($obj['verb']) {
315 switch ($obj['object-type']) {
316 case Activity\ObjectType::EVENT:
317 $post_type = $this->l10n->t('event');
320 $post_type = $this->l10n->t('status');
325 if ($obj['resource-id']) {
326 $post_type = $this->l10n->t('photo');
327 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
328 $rr['plink'] = $m[1];
330 $post_type = $this->l10n->t('status');
332 // Let's break everthing ... ;-)
335 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
337 $parsedobj = XML::parseString($xmlhead . $item['object']);
339 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
340 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
344 $this->profiler->stopRecording();
348 * Renders photo menu based on item
351 * @param string $formSecurityToken
354 public function photoMenu(array $item, string $formSecurityToken): string
356 $this->profiler->startRecording('rendering');
357 $sub_link = $contact_url = $pm_url = $status_link = '';
358 $photos_link = $posts_link = $block_link = $ignore_link = '';
360 if ($this->userSession->getLocalUserId() && $this->userSession->getLocalUserId() == $item['uid'] && $item['gravity'] == ItemModel::GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
361 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
366 'id' => $item['author-id'],
367 'network' => $item['author-network'],
368 'url' => $item['author-link'],
370 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
371 $sparkle = (strpos($profile_link, 'contact/redir/') === 0);
374 $pcid = $item['author-id'];
377 $condition = ['uid' => $this->userSession->getLocalUserId(), 'uri-id' => $item['author-uri-id']];
378 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
379 if (DBA::isResult($contact)) {
380 $cid = $contact['id'];
381 $network = $contact['network'];
382 $rel = $contact['rel'];
386 $status_link = $profile_link . '/status';
387 $photos_link = $profile_link . '/photos';
388 $profile_link = $profile_link . '/profile';
392 $contact_url = 'contact/' . $pcid;
393 $posts_link = $contact_url . '/posts';
394 $block_link = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
395 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
398 if ($cid && !$item['self']) {
399 $contact_url = 'contact/' . $cid;
400 $posts_link = $contact_url . '/posts';
402 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
403 $pm_url = 'message/new/' . $cid;
407 if ($this->userSession->getLocalUserId()) {
409 $this->l10n->t('Follow Thread') => $sub_link,
410 $this->l10n->t('View Status') => $status_link,
411 $this->l10n->t('View Profile') => $profile_link,
412 $this->l10n->t('View Photos') => $photos_link,
413 $this->l10n->t('Network Posts') => $posts_link,
414 $this->l10n->t('View Contact') => $contact_url,
415 $this->l10n->t('Send PM') => $pm_url,
416 $this->l10n->t('Block') => $block_link,
417 $this->l10n->t('Ignore') => $ignore_link
420 if (!empty($item['language'])) {
421 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ItemModel::getLanguageMessage($item) . '\');';
424 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
425 in_array($item['network'], Protocol::FEDERATED)) {
426 $menu[$this->l10n->t('Connect/Follow')] = 'contact/follow?url=' . urlencode($item['author-link']) . '&auto=1';
429 $menu = [$this->l10n->t('View Profile') => $item['author-link']];
432 $args = ['item' => $item, 'menu' => $menu];
434 Hook::callAll('item_photo_menu', $args);
436 $menu = $args['menu'];
439 foreach ($menu as $k => $v) {
440 if (strpos($v, 'javascript:') === 0) {
442 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
444 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
447 $this->profiler->stopRecording();
452 * Checks if the activity is visible to current user
454 * @param array $item Activity item
455 * @return bool Whether the item is visible to the user
457 public function isVisibleActivity(array $item): bool
459 // Empty verb or hidden?
460 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
465 return (!($this->activity->match($item['verb'], Activity::FOLLOW) &&
466 $item['object-type'] === Activity\ObjectType::NOTE &&
467 empty($item['self']) &&
468 $item['uid'] == $this->userSession->getLocalUserId())
472 public function expandTags(array $item, bool $setPermissions = false): array
474 // Look for any tags and linkify them
475 $item['inform'] = '';
476 $private_forum = false;
478 $only_to_forum = false;
482 // Convert mentions in the body to a unified format
483 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
485 // Search for forum mentions
486 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
487 $contact = Contact::getByURLForUser($tag[2], $item['uid']);
488 if (empty($contact)) {
492 $receivers[] = $contact['id'];
494 if (!empty($item['inform'])) {
495 $item['inform'] .= ',';
497 $item['inform'] .= 'cid:' . $contact['id'];
499 if (($item['gravity'] == ItemModel::GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
503 if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
504 $private_forum = $contact['prv'];
505 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
506 $private_id = $contact['id'];
507 $forum_contact = $contact;
508 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
509 } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
510 $private_forum = false;
511 $only_to_forum = true;
512 $private_id = $contact['id'];
513 $forum_contact = $contact;
514 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
516 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
519 Logger::info('Got inform', ['inform' => $item['inform']]);
521 if (($item['gravity'] == ItemModel::GRAVITY_PARENT) && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
522 // we tagged a forum in a top level post. Now we change the post
523 $item['private'] = $private_forum ? ItemModel::PRIVATE : ItemModel::UNLISTED;
525 if ($only_to_forum) {
526 $item['postopts'] = '';
529 $item['deny_cid'] = '';
530 $item['deny_gid'] = '';
532 if ($private_forum) {
533 $item['allow_cid'] = '<' . $private_id . '>';
534 $item['allow_gid'] = '<' . Group::getIdForForum($forum_contact['id']) . '>';
536 $item['allow_cid'] = '';
537 $item['allow_gid'] = '';
539 } elseif ($setPermissions && ($item['gravity'] == ItemModel::GRAVITY_PARENT)) {
540 if (empty($receivers)) {
541 // For security reasons direct posts without any receiver will be posts to yourself
542 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
543 $receivers[] = $self['id'];
546 $item['private'] = ItemModel::PRIVATE;
547 $item['allow_cid'] = '';
548 $item['allow_gid'] = '';
549 $item['deny_cid'] = '';
550 $item['deny_gid'] = '';
552 foreach ($receivers as $receiver) {
553 $item['allow_cid'] .= '<' . $receiver . '>';
559 public function getAuthorAvatar(array $item): string
561 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
562 $author_avatar = $item['contact-id'];
563 $author_updated = '';
564 $author_thumb = $item['contact-avatar'];
566 $author_avatar = $item['author-id'];
567 $author_updated = $item['author-updated'];
568 $author_thumb = $item['author-avatar'];
572 if (empty($author_thumb) || Photo::isPhotoURI($author_thumb)) {
573 $author_thumb = Contact::getAvatarUrlForId($author_avatar, Proxy::SIZE_THUMB, $author_updated);
576 return $author_thumb;
579 public function getOwnerAvatar(array $item): string
581 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
582 $owner_avatar = $item['contact-id'];
584 $owner_thumb = $item['contact-avatar'];
586 $owner_avatar = $item['owner-id'];
587 $owner_updated = $item['owner-updated'];
588 $owner_thumb = $item['owner-avatar'];
591 if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) {
592 $owner_thumb = Contact::getAvatarUrlForId($owner_avatar, Proxy::SIZE_THUMB, $owner_updated);
599 * Add a share block for the given uri-id
602 * @param string $body
605 public function addSharedPost(array $item, string $body = ''): string
608 $body = $item['body'];
611 if (empty($item['quote-uri-id'])) {
615 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'quote-uri-id'];
616 $shared_item = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [$item['uid'], 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
617 if (!DBA::isResult($shared_item)) {
618 Logger::notice('Post does not exist.', ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid']]);
622 return trim(BBCode::removeSharedData($body) . "\n" . $this->createSharedBlockByArray($shared_item, true));
626 * Add a share block for the given guid
628 * @param string $guid
629 * @param integer $uid
630 * @param bool $add_media
633 private function createSharedPostByGuid(string $guid, bool $add_media): string
635 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
636 $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => 0, 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
638 if (!DBA::isResult($shared_item)) {
639 Logger::notice('Post does not exist.', ['guid' => $guid]);
643 return $this->createSharedBlockByArray($shared_item, $add_media);
647 * Add a share block for the given item array
650 * @param bool $add_media
653 public function createSharedBlockByArray(array $item, bool $add_media = false): string
655 if ($item['network'] == Protocol::FEED) {
656 return PageInfo::getFooterFromUrl($item['plink']);
657 } elseif (!in_array($item['network'] ?? '', Protocol::FEDERATED)) {
663 $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
666 $shared_content = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid'], $item['uri']);
668 if (!empty($item['title'])) {
669 $shared_content .= '[h3]' . $item['title'] . "[/h3]\n";
672 $shared = $this->getShareArray($item);
674 // If it is a reshared post then reformat it to avoid display problems with two share elements
675 if (!empty($shared)) {
676 if (!empty($shared['guid']) && ($encaspulated_share = $this->createSharedPostByGuid($shared['guid'], true))) {
677 if (!empty(BBCode::fetchShareAttributes($item['body']))) {
678 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $encaspulated_share, $item['body']);
680 $item['body'] .= $encaspulated_share;
683 $item['body'] = HTML::toBBCode(BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::ACTIVITYPUB));
686 $shared_content .= $item['body'] . '[/share]';
688 return $shared_content;
692 * Return the shared post from an item array (if the item is shared item)
695 * @param array $fields
697 * @return array with the shared post
699 public function getSharedPost(array $item, array $fields = []): array
701 if (!empty($item['quote-uri-id'])) {
702 $shared = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [0, $item['uid'] ?? 0]]);
703 if (is_array($shared)) {
705 'comment' => BBCode::removeSharedData($item['body'] ?? ''),
711 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
712 if (!empty($attributes)) {
713 $shared = Post::selectFirst($fields, ['guid' => $attributes['guid'], 'uid' => [0, $item['uid'] ?? 0]]);
714 if (is_array($shared)) {
716 'comment' => $attributes['comment'],
726 * Return share data from an item array (if the item is shared item)
727 * We are providing the complete Item array, because at some time in the future
728 * we hopefully will define these values not in the body anymore but in some item fields.
729 * This function is meant to replace all similar functions in the system.
733 * @return array with share information
735 private function getShareArray(array $item): array
737 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
738 if (!empty($attributes)) {
742 if (!empty($item['quote-uri-id'])) {
743 $shared = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'uri', 'body'], ['uri-id' => $item['quote-uri-id']]);
744 if (!empty($shared)) {
746 'author' => $shared['author-name'],
747 'profile' => $shared['author-link'],
748 'avatar' => $shared['author-avatar'],
749 'link' => $shared['plink'],
750 'posted' => $shared['created'],
751 'guid' => $shared['guid'],
752 'message_id' => $shared['uri'],
753 'comment' => $item['body'],
754 'shared' => $shared['body'],
763 * Add a link to a shared post at the end of the post
765 * @param string $body
766 * @param integer $quote_uri_id
769 public function addShareLink(string $body, int $quote_uri_id): string
771 $post = Post::selectFirstPost(['uri', 'plink'], ['uri-id' => $quote_uri_id]);
776 $body = BBCode::removeSharedData($body);
778 $body .= "\n♲ " . ($post['plink'] ?: $post['uri']);
783 public function storeAttachmentFromRequest(array $request): string
785 $attachment_type = $request['attachment_type'] ?? '';
786 $attachment_title = $request['attachment_title'] ?? '';
787 $attachment_text = $request['attachment_text'] ?? '';
789 $attachment_url = hex2bin($request['attachment_url'] ?? '');
790 $attachment_img_src = hex2bin($request['attachment_img_src'] ?? '');
792 $attachment_img_width = $request['attachment_img_width'] ?? 0;
793 $attachment_img_height = $request['attachment_img_height'] ?? 0;
795 // Fetch the basic attachment data
796 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
797 unset($attachment['keywords']);
799 // Overwrite the basic data with possible changes from the frontend
800 $attachment['type'] = $attachment_type;
801 $attachment['title'] = $attachment_title;
802 $attachment['text'] = $attachment_text;
803 $attachment['url'] = $attachment_url;
805 if (!empty($attachment_img_src)) {
806 $attachment['images'] = [
808 'src' => $attachment_img_src,
809 'width' => $attachment_img_width,
810 'height' => $attachment_img_height
814 unset($attachment['images']);
817 return "\n" . PageInfo::getFooterFromData($attachment);
820 public function addCategories(array $post, string $category): array
822 if (!empty($post['file'])) {
823 // get the "fileas" tags for this post
824 $filedas = FileTag::fileToArray($post['file']);
827 $list_array = explode(',', trim($category));
828 $post['file'] = FileTag::arrayToFile($list_array, 'category');
830 if (!empty($filedas) && is_array($filedas)) {
831 // append the fileas stuff to the new categories list
832 $post['file'] .= FileTag::arrayToFile($filedas);
837 public function getACL(array $post, array $toplevel_item, array $request): array
839 // If this is a comment, set the permissions from the parent.
840 if ($toplevel_item) {
841 $post['allow_cid'] = $toplevel_item['allow_cid'] ?? '';
842 $post['allow_gid'] = $toplevel_item['allow_gid'] ?? '';
843 $post['deny_cid'] = $toplevel_item['deny_cid'] ?? '';
844 $post['deny_gid'] = $toplevel_item['deny_gid'] ?? '';
845 $post['private'] = $toplevel_item['private'];
849 $user = User::getById($post['uid'], ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
850 if (!DBA::isResult($user)) {
851 throw new HTTPException\NotFoundException($this->l10n->t('Unable to locate original post.'));
854 $post['allow_cid'] = isset($request['contact_allow']) ? $this->aclFormatter->toString($request['contact_allow']) : $user['allow_cid'] ?? '';
855 $post['allow_gid'] = isset($request['group_allow']) ? $this->aclFormatter->toString($request['group_allow']) : $user['allow_gid'] ?? '';
856 $post['deny_cid'] = isset($request['contact_deny']) ? $this->aclFormatter->toString($request['contact_deny']) : $user['deny_cid'] ?? '';
857 $post['deny_gid'] = isset($request['group_deny']) ? $this->aclFormatter->toString($request['group_deny']) : $user['deny_gid'] ?? '';
859 $visibility = $request['visibility'] ?? '';
860 if ($visibility === 'public') {
861 // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
862 $post['allow_cid'] = $post['allow_gid'] = $post['deny_cid'] = $post['deny_gid'] = '';
863 } else if ($visibility === 'custom') {
864 // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
865 // case that would make it public. So we always append the author's contact id to the allowed contacts.
866 // See https://github.com/friendica/friendica/issues/9672
867 $post['allow_cid'] .= $this->aclFormatter->toString(Contact::getPublicIdByUserId($post['uid']));
870 if (strlen($post['allow_gid']) || strlen($post['allow_cid']) || strlen($post['deny_gid']) || strlen($post['deny_cid'])) {
871 $post['private'] = ItemModel::PRIVATE;
872 } elseif ($this->pConfig->get($post['uid'], 'system', 'unlisted')) {
873 $post['private'] = ItemModel::UNLISTED;
875 $post['private'] = ItemModel::PUBLIC;
881 public function moveAttachmentsFromBodyToAttach(array $post): array
883 if (!preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$post['body'], $match)) {
887 foreach ($match[2] as $attachment_id) {
888 $attachment = Attach::selectFirst(['id', 'uid', 'filename', 'filesize', 'filetype'], ['id' => $attachment_id, 'uid' => $post['uid']]);
889 if (empty($attachment)) {
892 if (strlen($post['attach'])) {
893 $post['attach'] .= ',';
895 $post['attach'] .= Post\Media::getAttachElement($this->baseURL->get() . '/attach/' . $attachment['id'],
896 $attachment['filesize'], $attachment['filetype'], $attachment['filename'] ?? '');
898 $fields = ['allow_cid' => $post['allow_cid'], 'allow_gid' => $post['allow_gid'],
899 'deny_cid' => $post['deny_cid'], 'deny_gid' => $post['deny_gid']];
900 $condition = ['id' => $attachment_id];
901 Attach::update($fields, $condition);
904 $post['body'] = str_replace($match[1], '', $post['body']);
909 private function setObjectType(array $post): array
911 if (empty($post['post-type'])) {
912 $post['post-type'] = empty($post['title']) ? ItemModel::PT_NOTE : ItemModel::PT_ARTICLE;
915 // embedded bookmark or attachment in post? set bookmark flag
916 $data = BBCode::getAttachmentData($post['body']);
917 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $post['body'], $match, PREG_SET_ORDER) || isset($data['type']))
918 && ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE)) {
919 $post['post-type'] = ItemModel::PT_PAGE;
920 $post['object-type'] = Activity\ObjectType::BOOKMARK;
923 // Setting the object type if not defined before
924 if (empty($post['object-type'])) {
925 $post['object-type'] = ($post['gravity'] == ItemModel::GRAVITY_PARENT) ? Activity\ObjectType::NOTE : Activity\ObjectType::COMMENT;
927 $objectdata = BBCode::getAttachedData($post['body']);
929 if ($objectdata['type'] == 'link') {
930 $post['object-type'] = Activity\ObjectType::BOOKMARK;
931 } elseif ($objectdata['type'] == 'video') {
932 $post['object-type'] = Activity\ObjectType::VIDEO;
933 } elseif ($objectdata['type'] == 'photo') {
934 $post['object-type'] = Activity\ObjectType::IMAGE;
940 public function initializePost(array $post): array
942 $post['wall'] = true;
943 $post['origin'] = true;
944 $post['network'] = Protocol::DFRN;
945 $post['protocol'] = Conversation::PARCEL_DIRECT;
946 $post['direction'] = Conversation::PUSH;
947 $post['guid'] = System::createUUID();
948 $post['uri'] = ItemModel::newURI($post['guid']);
949 $post['verb'] = Activity::POST;
950 $post['received'] = DateTimeFormat::utcNow();
951 $owner = User::getOwnerDataById($post['uid']);
953 if (empty($post['contact-id'])) {
954 $post['contact-id'] = $owner['id'];
957 if (empty($post['author-link']) && empty($post['author-id'])) {
958 $post['author-link'] = $owner['url'];
959 $post['author-id'] = Contact::getIdForURL($post['author-link']);
960 $post['author-name'] = $owner['name'];
961 $post['author-avatar'] = $owner['thumb'];
964 if (empty($post['owner-link']) && empty($post['owner-id'])) {
965 $post['owner-link'] = $post['author-link'];
966 $post['owner-id'] = Contact::getIdForURL($post['owner-link']);
967 $post['owner-name'] = $post['author-name'];
968 $post['owner-avatar'] = $post['author-avatar'];
974 public function finalizePost(array $post): array
976 if (preg_match("/\[attachment\](.*?)\[\/attachment\]/ism", $post['body'], $matches)) {
977 $post['body'] = preg_replace("/\[attachment].*?\[\/attachment\]/ism", PageInfo::getFooterFromUrl($matches[1]), $post['body']);
980 // Convert links with empty descriptions to links without an explicit description
981 $post['body'] = trim(preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $post['body']));
982 $post['body'] = $this->bbCodeVideo->transform($post['body']);
983 $post['body'] = BBCode::scaleExternalImages($post['body']);
984 $post = $this->setObjectType($post);
986 // Personal notes must never be altered to a forum post.
987 if ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE) {
988 // Look for any tags and linkify them
989 $post = $this->expandTags($post);