3 * @copyright Copyright (C) 2010-2022, 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\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\L10n;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Session\Capability\IHandleUserSessions;
31 use Friendica\Core\System;
32 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Group;
35 use Friendica\Model\Item as ItemModel;
36 use Friendica\Model\Photo;
37 use Friendica\Model\Tag;
38 use Friendica\Model\Post;
39 use Friendica\Protocol\Activity;
40 use Friendica\Util\Profiler;
41 use Friendica\Util\Proxy;
42 use Friendica\Util\XML;
45 * A content helper class for displaying items
55 /** @var IHandleUserSessions */
58 public function __construct(Profiler $profiler, Activity $activity, L10n $l10n, IHandleUserSessions $userSession)
60 $this->profiler = $profiler;
61 $this->activity = $activity;
63 $this->userSession = $userSession;
67 * Return array with details for categories and folders for an item
71 * @return [array, array]
74 * [ // categories array
76 * 'name': 'category name',
77 * 'removeurl': 'url to remove this category',
78 * 'first': 'is the first in this array? true/false',
79 * 'last': 'is the last in this array? true/false',
85 * 'name': 'folder name',
86 * 'removeurl': 'url to remove this folder',
87 * 'first': 'is the first in this array? true/false',
88 * 'last': 'is the last in this array? true/false',
94 public function determineCategoriesTerms(array $item, int $uid = 0): array
100 $uid = $item['uid'] ?: $uid;
102 if (empty($item['has-categories'])) {
103 return [$categories, $folders];
106 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::CATEGORY) as $savedFolderName) {
107 if (!empty($item['author-link'])) {
108 $url = $item['author-link'] . "?category=" . rawurlencode($savedFolderName);
113 'name' => $savedFolderName,
115 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '',
122 if (count($categories)) {
123 $categories[count($categories) - 1]['last'] = true;
126 if ($this->userSession->getLocalUserId() == $uid) {
127 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) {
129 'name' => $savedFolderName,
131 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '',
139 if (count($folders)) {
140 $folders[count($folders) - 1]['last'] = true;
143 return [$categories, $folders];
147 * This function removes the tag $tag from the text $body and replaces it with
148 * the appropriate link.
150 * @param string $body the text to replace the tag in
151 * @param int $profile_uid the user id to replace the tag for (0 = anyone)
152 * @param string $tag the tag to replace
153 * @param string $network The network of the post
155 * @return array|bool ['replaced' => $replaced, 'contact' => $contact] or "false" on if already replaced
156 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
157 * @throws \ImagickException
159 public static function replaceTag(string &$body, int $profile_uid, string $tag, string $network = '')
163 //is it a person tag?
164 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
165 $tag_type = substr($tag, 0, 1);
166 //is it already replaced?
167 if (strpos($tag, '[url=')) {
171 //get the person's name
172 $name = substr($tag, 1);
174 // Sometimes the tag detection doesn't seem to work right
175 // This is some workaround
176 $nameparts = explode(' ', $name);
177 $name = $nameparts[0];
179 // Try to detect the contact in various ways
180 if (strpos($name, 'http://') || strpos($name, '@')) {
181 $contact = Contact::getByURLForUser($name, $profile_uid);
184 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
186 if (strrpos($name, '+')) {
187 // Is it in format @nick+number?
188 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
189 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
192 // select someone by nick in the current network
193 if (!DBA::isResult($contact) && ($network != '')) {
194 $condition = ["`nick` = ? AND `network` = ? AND `uid` = ?",
195 $name, $network, $profile_uid];
196 $contact = DBA::selectFirst('contact', $fields, $condition);
199 // select someone by attag in the current network
200 if (!DBA::isResult($contact) && ($network != '')) {
201 $condition = ["`attag` = ? AND `network` = ? AND `uid` = ?",
202 $name, $network, $profile_uid];
203 $contact = DBA::selectFirst('contact', $fields, $condition);
206 //select someone by name in the current network
207 if (!DBA::isResult($contact) && ($network != '')) {
208 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
209 $contact = DBA::selectFirst('contact', $fields, $condition);
212 // select someone by nick in any network
213 if (!DBA::isResult($contact)) {
214 $condition = ["`nick` = ? AND `uid` = ?", $name, $profile_uid];
215 $contact = DBA::selectFirst('contact', $fields, $condition);
218 // select someone by attag in any network
219 if (!DBA::isResult($contact)) {
220 $condition = ["`attag` = ? AND `uid` = ?", $name, $profile_uid];
221 $contact = DBA::selectFirst('contact', $fields, $condition);
224 // select someone by name in any network
225 if (!DBA::isResult($contact)) {
226 $condition = ['name' => $name, 'uid' => $profile_uid];
227 $contact = DBA::selectFirst('contact', $fields, $condition);
231 // Check if $contact has been successfully loaded
232 if (DBA::isResult($contact)) {
233 $profile = $contact['url'];
234 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
237 //if there is an url for this persons profile
238 if (isset($profile) && ($newname != '')) {
240 // create profile link
241 $profile = str_replace(',', '%2c', $profile);
242 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
243 $body = str_replace($tag_type . $name, $newtag, $body);
247 return ['replaced' => $replaced, 'contact' => $contact];
251 * Render actions localized
255 * @throws ImagickException
256 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
258 public function localize(array &$item)
260 $this->profiler->startRecording('rendering');
261 /// @todo The following functionality needs to be cleaned up.
262 if (!empty($item['verb'])) {
263 $xmlhead = '<?xml version="1.0" encoding="UTF-8" ?>';
265 if ($this->activity->match($item['verb'], Activity::TAG)) {
266 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
267 'verb', 'object-type', 'resource-id', 'body', 'plink'];
268 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
269 if (!DBA::isResult($obj)) {
270 $this->profiler->stopRecording();
276 'id' => $item['author-id'],
277 'network' => $item['author-network'],
278 'url' => $item['author-link'],
280 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
284 'id' => $obj['author-id'],
285 'network' => $obj['author-network'],
286 'url' => $obj['author-link'],
288 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
290 switch ($obj['verb']) {
292 switch ($obj['object-type']) {
293 case Activity\ObjectType::EVENT:
294 $post_type = $this->l10n->t('event');
297 $post_type = $this->l10n->t('status');
302 if ($obj['resource-id']) {
303 $post_type = $this->l10n->t('photo');
304 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
305 $rr['plink'] = $m[1];
307 $post_type = $this->l10n->t('status');
309 // Let's break everthing ... ;-)
312 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
314 $parsedobj = XML::parseString($xmlhead . $item['object']);
316 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
317 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
321 $this->profiler->stopRecording();
325 * Renders photo menu based on item
328 * @param string $formSecurityToken
331 public function photoMenu(array $item, string $formSecurityToken): string
333 $this->profiler->startRecording('rendering');
334 $sub_link = $contact_url = $pm_url = $status_link = '';
335 $photos_link = $posts_link = $block_link = $ignore_link = '';
337 if ($this->userSession->getLocalUserId() && $this->userSession->getLocalUserId() == $item['uid'] && $item['gravity'] == ItemModel::GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
338 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
343 'id' => $item['author-id'],
344 'network' => $item['author-network'],
345 'url' => $item['author-link'],
347 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
348 $sparkle = (strpos($profile_link, 'redir/') === 0);
351 $pcid = $item['author-id'];
354 $condition = ['uid' => $this->userSession->getLocalUserId(), 'uri-id' => $item['author-uri-id']];
355 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
356 if (DBA::isResult($contact)) {
357 $cid = $contact['id'];
358 $network = $contact['network'];
359 $rel = $contact['rel'];
363 $status_link = $profile_link . '/status';
364 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
365 $profile_link = $profile_link . '/profile';
369 $contact_url = 'contact/' . $pcid;
370 $posts_link = $contact_url . '/posts';
371 $block_link = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
372 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
375 if ($cid && !$item['self']) {
376 $contact_url = 'contact/' . $cid;
377 $posts_link = $contact_url . '/posts';
379 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
380 $pm_url = 'message/new/' . $cid;
384 if ($this->userSession->getLocalUserId()) {
386 $this->l10n->t('Follow Thread') => $sub_link,
387 $this->l10n->t('View Status') => $status_link,
388 $this->l10n->t('View Profile') => $profile_link,
389 $this->l10n->t('View Photos') => $photos_link,
390 $this->l10n->t('Network Posts') => $posts_link,
391 $this->l10n->t('View Contact') => $contact_url,
392 $this->l10n->t('Send PM') => $pm_url,
393 $this->l10n->t('Block') => $block_link,
394 $this->l10n->t('Ignore') => $ignore_link
397 if (!empty($item['language'])) {
398 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ItemModel::getLanguageMessage($item) . '\');';
401 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
402 in_array($item['network'], Protocol::FEDERATED)) {
403 $menu[$this->l10n->t('Connect/Follow')] = 'contact/follow?url=' . urlencode($item['author-link']) . '&auto=1';
406 $menu = [$this->l10n->t('View Profile') => $item['author-link']];
409 $args = ['item' => $item, 'menu' => $menu];
411 Hook::callAll('item_photo_menu', $args);
413 $menu = $args['menu'];
416 foreach ($menu as $k => $v) {
417 if (strpos($v, 'javascript:') === 0) {
419 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
421 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
424 $this->profiler->stopRecording();
429 * Checks if the activity is visible to current user
431 * @param array $item Activity item
432 * @return bool Whether the item is visible to the user
434 public function isVisibleActivity(array $item): bool
436 // Empty verb or hidden?
437 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
442 return (!($this->activity->match($item['verb'], Activity::FOLLOW) &&
443 $item['object-type'] === Activity\ObjectType::NOTE &&
444 empty($item['self']) &&
445 $item['uid'] == $this->userSession->getLocalUserId())
449 public function expandTags(array $item, bool $setPermissions = false): array
451 // Look for any tags and linkify them
452 $item['inform'] = '';
453 $private_forum = false;
455 $only_to_forum = false;
459 // Convert mentions in the body to a unified format
460 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
462 // Search for forum mentions
463 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
464 $contact = Contact::getByURLForUser($tag[2], $item['uid']);
465 if (empty($contact)) {
469 $receivers[] = $contact['id'];
471 if (!empty($item['inform'])) {
472 $item['inform'] .= ',';
474 $item['inform'] .= 'cid:' . $contact['id'];
476 if (($item['gravity'] == ItemModel::GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
480 if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
481 $private_forum = $contact['prv'];
482 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
483 $private_id = $contact['id'];
484 $forum_contact = $contact;
485 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
486 } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
487 $private_forum = false;
488 $only_to_forum = true;
489 $private_id = $contact['id'];
490 $forum_contact = $contact;
491 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
493 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
496 Logger::info('Got inform', ['inform' => $item['inform']]);
498 if (($item['gravity'] == ItemModel::GRAVITY_PARENT) && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
499 // we tagged a forum in a top level post. Now we change the post
500 $item['private'] = $private_forum ? ItemModel::PRIVATE : ItemModel::UNLISTED;
502 if ($only_to_forum) {
503 $item['postopts'] = '';
506 $item['deny_cid'] = '';
507 $item['deny_gid'] = '';
509 if ($private_forum) {
510 $item['allow_cid'] = '<' . $private_id . '>';
511 $item['allow_gid'] = '<' . Group::getIdForForum($forum_contact['id']) . '>';
513 $item['allow_cid'] = '';
514 $item['allow_gid'] = '';
516 } elseif ($setPermissions && ($item['gravity'] == ItemModel::GRAVITY_PARENT)) {
517 if (empty($receivers)) {
518 // For security reasons direct posts without any receiver will be posts to yourself
519 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
520 $receivers[] = $self['id'];
523 $item['private'] = ItemModel::PRIVATE;
524 $item['allow_cid'] = '';
525 $item['allow_gid'] = '';
526 $item['deny_cid'] = '';
527 $item['deny_gid'] = '';
529 foreach ($receivers as $receiver) {
530 $item['allow_cid'] .= '<' . $receiver . '>';
536 public function getAuthorAvatar(array $item): string
538 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
539 $author_avatar = $item['contact-id'];
540 $author_updated = '';
541 $author_thumb = $item['contact-avatar'];
543 $author_avatar = $item['author-id'];
544 $author_updated = $item['author-updated'];
545 $author_thumb = $item['author-avatar'];
549 if (empty($author_thumb) || Photo::isPhotoURI($author_thumb)) {
550 $author_thumb = Contact::getAvatarUrlForId($author_avatar, Proxy::SIZE_THUMB, $author_updated);
553 return $author_thumb;
556 public function getOwnerAvatar(array $item): string
558 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
559 $owner_avatar = $item['contact-id'];
561 $owner_thumb = $item['contact-avatar'];
563 $owner_avatar = $item['owner-id'];
564 $owner_updated = $item['owner-updated'];
565 $owner_thumb = $item['owner-avatar'];
568 if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) {
569 $owner_thumb = Contact::getAvatarUrlForId($owner_avatar, Proxy::SIZE_THUMB, $owner_updated);
576 * Add a share block for the given uri-id
579 * @param string $body
582 public function addSharedPost(array $item, string $body = ''): string
585 $body = $item['body'];
588 if (empty($item['quote-uri-id'])) {
592 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'quote-uri-id'];
593 $shared_item = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [$item['uid'], 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
594 if (!DBA::isResult($shared_item)) {
595 Logger::notice('Post does not exist.', ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid']]);
599 return trim(BBCode::removeSharedData($body) . "\n" . $this->createSharedBlockByArray($shared_item, true));
603 * Add a share block for the given guid
605 * @param string $guid
606 * @param integer $uid
607 * @param bool $add_media
610 private function createSharedPostByGuid(string $guid, bool $add_media): string
612 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
613 $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => 0, 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
615 if (!DBA::isResult($shared_item)) {
616 Logger::notice('Post does not exist.', ['guid' => $guid]);
620 return $this->createSharedBlockByArray($shared_item, $add_media);
624 * Add a share block for the given item array
627 * @param bool $add_media
630 public function createSharedBlockByArray(array $item, bool $add_media = false): string
632 if ($item['network'] == Protocol::FEED) {
633 return PageInfo::getFooterFromUrl($item['plink']);
634 } elseif (!in_array($item['network'] ?? '', Protocol::FEDERATED)) {
640 $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
643 $shared_content = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid'], $item['uri']);
645 if (!empty($item['title'])) {
646 $shared_content .= '[h3]' . $item['title'] . "[/h3]\n";
649 $shared = $this->getShareArray($item);
651 // If it is a reshared post then reformat it to avoid display problems with two share elements
652 if (!empty($shared)) {
653 if (!empty($shared['guid']) && ($encaspulated_share = $this->createSharedPostByGuid($shared['guid'], true))) {
654 if (!empty(BBCode::fetchShareAttributes($item['body']))) {
655 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $encaspulated_share, $item['body']);
657 $item['body'] .= $encaspulated_share;
660 $item['body'] = HTML::toBBCode(BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::ACTIVITYPUB));
663 $shared_content .= $item['body'] . '[/share]';
665 return $shared_content;
669 * Return the shared post from an item array (if the item is shared item)
672 * @param array $fields
674 * @return array with the shared post
676 public function getSharedPost(array $item, array $fields = []): array
678 if (!empty($item['quote-uri-id'])) {
679 $shared = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [0, $item['uid'] ?? 0]]);
680 if (is_array($shared)) {
682 'comment' => BBCode::removeSharedData($item['body'] ?? ''),
688 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
689 if (!empty($attributes)) {
690 $shared = Post::selectFirst($fields, ['guid' => $attributes['guid'], 'uid' => [0, $item['uid'] ?? 0]]);
691 if (is_array($shared)) {
693 'comment' => $attributes['comment'],
703 * Return share data from an item array (if the item is shared item)
704 * We are providing the complete Item array, because at some time in the future
705 * we hopefully will define these values not in the body anymore but in some item fields.
706 * This function is meant to replace all similar functions in the system.
710 * @return array with share information
712 private function getShareArray(array $item): array
714 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
715 if (!empty($attributes)) {
719 if (!empty($item['quote-uri-id'])) {
720 $shared = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'uri', 'body'], ['uri-id' => $item['quote-uri-id']]);
721 if (!empty($shared)) {
723 'author' => $shared['author-name'],
724 'profile' => $shared['author-link'],
725 'avatar' => $shared['author-avatar'],
726 'link' => $shared['plink'],
727 'posted' => $shared['created'],
728 'guid' => $shared['guid'],
729 'message_id' => $shared['uri'],
730 'comment' => $item['body'],
731 'shared' => $shared['body'],
740 * Add a link to a shared post at the end of the post
742 * @param string $body
743 * @param integer $quote_uri_id
746 public function addShareLink(string $body, int $quote_uri_id): string
748 $post = Post::selectFirstPost(['uri', 'plink'], ['uri-id' => $quote_uri_id]);
753 $body = BBCode::removeSharedData($body);
755 $body .= "\n♲ " . ($post['plink'] ?: $post['uri']);