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\Protocol\Diaspora;
41 use Friendica\Util\Profiler;
42 use Friendica\Util\Proxy;
43 use Friendica\Util\XML;
46 * A content helper class for displaying items
56 /** @var IHandleUserSessions */
59 public function __construct(Profiler $profiler, Activity $activity, L10n $l10n, IHandleUserSessions $userSession)
61 $this->profiler = $profiler;
62 $this->activity = $activity;
64 $this->userSession = $userSession;
68 * Return array with details for categories and folders for an item
72 * @return [array, array]
75 * [ // categories array
77 * 'name': 'category name',
78 * 'removeurl': 'url to remove this category',
79 * 'first': 'is the first in this array? true/false',
80 * 'last': 'is the last in this array? true/false',
86 * 'name': 'folder name',
87 * 'removeurl': 'url to remove this folder',
88 * 'first': 'is the first in this array? true/false',
89 * 'last': 'is the last in this array? true/false',
95 public function determineCategoriesTerms(array $item, int $uid = 0): array
101 $uid = $item['uid'] ?: $uid;
103 if (empty($item['has-categories'])) {
104 return [$categories, $folders];
107 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::CATEGORY) as $savedFolderName) {
108 if (!empty($item['author-link'])) {
109 $url = $item['author-link'] . "?category=" . rawurlencode($savedFolderName);
114 'name' => $savedFolderName,
116 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '',
123 if (count($categories)) {
124 $categories[count($categories) - 1]['last'] = true;
127 if ($this->userSession->getLocalUserId() == $uid) {
128 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) {
130 'name' => $savedFolderName,
132 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '',
140 if (count($folders)) {
141 $folders[count($folders) - 1]['last'] = true;
144 return [$categories, $folders];
148 * This function removes the tag $tag from the text $body and replaces it with
149 * the appropriate link.
151 * @param string $body the text to replace the tag in
152 * @param int $profile_uid the user id to replace the tag for (0 = anyone)
153 * @param string $tag the tag to replace
154 * @param string $network The network of the post
156 * @return array|bool ['replaced' => $replaced, 'contact' => $contact] or "false" on if already replaced
157 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
158 * @throws \ImagickException
160 public static function replaceTag(string &$body, int $profile_uid, string $tag, string $network = '')
164 //is it a person tag?
165 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
166 $tag_type = substr($tag, 0, 1);
167 //is it already replaced?
168 if (strpos($tag, '[url=')) {
172 //get the person's name
173 $name = substr($tag, 1);
175 // Sometimes the tag detection doesn't seem to work right
176 // This is some workaround
177 $nameparts = explode(' ', $name);
178 $name = $nameparts[0];
180 // Try to detect the contact in various ways
181 if (strpos($name, 'http://') || strpos($name, '@')) {
182 $contact = Contact::getByURLForUser($name, $profile_uid);
185 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
187 if (strrpos($name, '+')) {
188 // Is it in format @nick+number?
189 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
190 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
193 // select someone by nick in the current network
194 if (!DBA::isResult($contact) && ($network != '')) {
195 $condition = ["`nick` = ? AND `network` = ? AND `uid` = ?",
196 $name, $network, $profile_uid];
197 $contact = DBA::selectFirst('contact', $fields, $condition);
200 // select someone by attag in the current network
201 if (!DBA::isResult($contact) && ($network != '')) {
202 $condition = ["`attag` = ? AND `network` = ? AND `uid` = ?",
203 $name, $network, $profile_uid];
204 $contact = DBA::selectFirst('contact', $fields, $condition);
207 //select someone by name in the current network
208 if (!DBA::isResult($contact) && ($network != '')) {
209 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
210 $contact = DBA::selectFirst('contact', $fields, $condition);
213 // select someone by nick in any network
214 if (!DBA::isResult($contact)) {
215 $condition = ["`nick` = ? AND `uid` = ?", $name, $profile_uid];
216 $contact = DBA::selectFirst('contact', $fields, $condition);
219 // select someone by attag in any network
220 if (!DBA::isResult($contact)) {
221 $condition = ["`attag` = ? AND `uid` = ?", $name, $profile_uid];
222 $contact = DBA::selectFirst('contact', $fields, $condition);
225 // select someone by name in any network
226 if (!DBA::isResult($contact)) {
227 $condition = ['name' => $name, 'uid' => $profile_uid];
228 $contact = DBA::selectFirst('contact', $fields, $condition);
232 // Check if $contact has been successfully loaded
233 if (DBA::isResult($contact)) {
234 $profile = $contact['url'];
235 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
238 //if there is an url for this persons profile
239 if (isset($profile) && ($newname != '')) {
241 // create profile link
242 $profile = str_replace(',', '%2c', $profile);
243 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
244 $body = str_replace($tag_type . $name, $newtag, $body);
248 return ['replaced' => $replaced, 'contact' => $contact];
252 * Render actions localized
256 * @throws ImagickException
257 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
259 public function localize(array &$item)
261 $this->profiler->startRecording('rendering');
262 /// @todo The following functionality needs to be cleaned up.
263 if (!empty($item['verb'])) {
264 $xmlhead = '<?xml version="1.0" encoding="UTF-8" ?>';
266 if ($this->activity->match($item['verb'], Activity::TAG)) {
267 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
268 'verb', 'object-type', 'resource-id', 'body', 'plink'];
269 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
270 if (!DBA::isResult($obj)) {
271 $this->profiler->stopRecording();
277 'id' => $item['author-id'],
278 'network' => $item['author-network'],
279 'url' => $item['author-link'],
281 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
285 'id' => $obj['author-id'],
286 'network' => $obj['author-network'],
287 'url' => $obj['author-link'],
289 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
291 switch ($obj['verb']) {
293 switch ($obj['object-type']) {
294 case Activity\ObjectType::EVENT:
295 $post_type = $this->l10n->t('event');
298 $post_type = $this->l10n->t('status');
303 if ($obj['resource-id']) {
304 $post_type = $this->l10n->t('photo');
305 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
306 $rr['plink'] = $m[1];
308 $post_type = $this->l10n->t('status');
310 // Let's break everthing ... ;-)
313 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
315 $parsedobj = XML::parseString($xmlhead . $item['object']);
317 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
318 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
322 $this->profiler->stopRecording();
326 * Renders photo menu based on item
329 * @param string $formSecurityToken
332 public function photoMenu(array $item, string $formSecurityToken): string
334 $this->profiler->startRecording('rendering');
335 $sub_link = $contact_url = $pm_url = $status_link = '';
336 $photos_link = $posts_link = $block_link = $ignore_link = '';
338 if ($this->userSession->getLocalUserId() && $this->userSession->getLocalUserId() == $item['uid'] && $item['gravity'] == ItemModel::GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
339 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
344 'id' => $item['author-id'],
345 'network' => $item['author-network'],
346 'url' => $item['author-link'],
348 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
349 $sparkle = (strpos($profile_link, 'redir/') === 0);
352 $pcid = $item['author-id'];
355 $condition = ['uid' => $this->userSession->getLocalUserId(), 'uri-id' => $item['author-uri-id']];
356 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
357 if (DBA::isResult($contact)) {
358 $cid = $contact['id'];
359 $network = $contact['network'];
360 $rel = $contact['rel'];
364 $status_link = $profile_link . '/status';
365 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
366 $profile_link = $profile_link . '/profile';
370 $contact_url = 'contact/' . $pcid;
371 $posts_link = $contact_url . '/posts';
372 $block_link = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
373 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
376 if ($cid && !$item['self']) {
377 $contact_url = 'contact/' . $cid;
378 $posts_link = $contact_url . '/posts';
380 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
381 $pm_url = 'message/new/' . $cid;
385 if ($this->userSession->getLocalUserId()) {
387 $this->l10n->t('Follow Thread') => $sub_link,
388 $this->l10n->t('View Status') => $status_link,
389 $this->l10n->t('View Profile') => $profile_link,
390 $this->l10n->t('View Photos') => $photos_link,
391 $this->l10n->t('Network Posts') => $posts_link,
392 $this->l10n->t('View Contact') => $contact_url,
393 $this->l10n->t('Send PM') => $pm_url,
394 $this->l10n->t('Block') => $block_link,
395 $this->l10n->t('Ignore') => $ignore_link
398 if (!empty($item['language'])) {
399 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ItemModel::getLanguageMessage($item) . '\');';
402 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
403 in_array($item['network'], Protocol::FEDERATED)) {
404 $menu[$this->l10n->t('Connect/Follow')] = 'contact/follow?url=' . urlencode($item['author-link']) . '&auto=1';
407 $menu = [$this->l10n->t('View Profile') => $item['author-link']];
410 $args = ['item' => $item, 'menu' => $menu];
412 Hook::callAll('item_photo_menu', $args);
414 $menu = $args['menu'];
417 foreach ($menu as $k => $v) {
418 if (strpos($v, 'javascript:') === 0) {
420 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
422 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
425 $this->profiler->stopRecording();
430 * Checks if the activity is visible to current user
432 * @param array $item Activity item
433 * @return bool Whether the item is visible to the user
435 public function isVisibleActivity(array $item): bool
437 // Empty verb or hidden?
438 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
443 return (!($this->activity->match($item['verb'], Activity::FOLLOW) &&
444 $item['object-type'] === Activity\ObjectType::NOTE &&
445 empty($item['self']) &&
446 $item['uid'] == $this->userSession->getLocalUserId())
450 public function expandTags(array $item, bool $setPermissions = false): array
452 // Look for any tags and linkify them
453 $item['inform'] = '';
454 $private_forum = false;
456 $only_to_forum = false;
460 // Convert mentions in the body to a unified format
461 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
463 // Search for forum mentions
464 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
465 $contact = Contact::getByURLForUser($tag[2], $item['uid']);
466 if (empty($contact)) {
470 $receivers[] = $contact['id'];
472 if (!empty($item['inform'])) {
473 $item['inform'] .= ',';
475 $item['inform'] .= 'cid:' . $contact['id'];
477 if (($item['gravity'] == ItemModel::GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
481 if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
482 $private_forum = $contact['prv'];
483 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
484 $private_id = $contact['id'];
485 $forum_contact = $contact;
486 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
487 } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
488 $private_forum = false;
489 $only_to_forum = true;
490 $private_id = $contact['id'];
491 $forum_contact = $contact;
492 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
494 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
497 Logger::info('Got inform', ['inform' => $item['inform']]);
499 if (($item['gravity'] == ItemModel::GRAVITY_PARENT) && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
500 // we tagged a forum in a top level post. Now we change the post
501 $item['private'] = $private_forum ? ItemModel::PRIVATE : ItemModel::UNLISTED;
503 if ($only_to_forum) {
504 $item['postopts'] = '';
507 $item['deny_cid'] = '';
508 $item['deny_gid'] = '';
510 if ($private_forum) {
511 $item['allow_cid'] = '<' . $private_id . '>';
512 $item['allow_gid'] = '<' . Group::getIdForForum($forum_contact['id']) . '>';
514 $item['allow_cid'] = '';
515 $item['allow_gid'] = '';
517 } elseif ($setPermissions && ($item['gravity'] == ItemModel::GRAVITY_PARENT)) {
518 if (empty($receivers)) {
519 // For security reasons direct posts without any receiver will be posts to yourself
520 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
521 $receivers[] = $self['id'];
524 $item['private'] = ItemModel::PRIVATE;
525 $item['allow_cid'] = '';
526 $item['allow_gid'] = '';
527 $item['deny_cid'] = '';
528 $item['deny_gid'] = '';
530 foreach ($receivers as $receiver) {
531 $item['allow_cid'] .= '<' . $receiver . '>';
537 public function getAuthorAvatar(array $item): string
539 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
540 $author_avatar = $item['contact-id'];
541 $author_updated = '';
542 $author_thumb = $item['contact-avatar'];
544 $author_avatar = $item['author-id'];
545 $author_updated = $item['author-updated'];
546 $author_thumb = $item['author-avatar'];
550 if (empty($author_thumb) || Photo::isPhotoURI($author_thumb)) {
551 $author_thumb = Contact::getAvatarUrlForId($author_avatar, Proxy::SIZE_THUMB, $author_updated);
554 return $author_thumb;
557 public function getOwnerAvatar(array $item): string
559 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
560 $owner_avatar = $item['contact-id'];
562 $owner_thumb = $item['contact-avatar'];
564 $owner_avatar = $item['owner-id'];
565 $owner_updated = $item['owner-updated'];
566 $owner_thumb = $item['owner-avatar'];
569 if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) {
570 $owner_thumb = Contact::getAvatarUrlForId($owner_avatar, Proxy::SIZE_THUMB, $owner_updated);
577 * Add a share block for the given uri-id
580 * @param string $body
583 public function addSharedPost(array $item, string $body = ''): string
586 $body = $item['body'];
589 if (empty($item['quote-uri-id'])) {
593 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
594 $shared_item = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [$item['uid'], 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
595 if (!DBA::isResult($shared_item)) {
596 Logger::notice('Post does not exist.', ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid']]);
600 return BBCode::removeSharedData($body) . "\n" . $this->createSharedBlockByArray($shared_item, true);
604 * Add a share block for the given guid
606 * @param string $guid
607 * @param integer $uid
608 * @param bool $add_media
611 private function createSharedPostByGuid(string $guid, bool $add_media): string
613 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
614 $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => 0, 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
616 if (!DBA::isResult($shared_item)) {
617 Logger::notice('Post does not exist.', ['guid' => $guid]);
621 return $this->createSharedBlockByArray($shared_item, $add_media);
625 * Add a share block for the given item array
628 * @param bool $add_media
631 public function createSharedBlockByArray(array $item, bool $add_media = false): string
633 if ($item['network'] == Protocol::FEED) {
634 return PageInfo::getFooterFromUrl($item['plink']);
635 } elseif (!in_array($item['network'] ?? '', Protocol::FEDERATED)) {
641 $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
644 $shared_content = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid'], $item['uri']);
646 if (!empty($item['title'])) {
647 $shared_content .= '[h3]' . $item['title'] . "[/h3]\n";
650 $shared = $this->getShareArray($item);
652 // If it is a reshared post then reformat it to avoid display problems with two share elements
653 if (!empty($shared)) {
654 if (!empty($shared['guid']) && ($encaspulated_share = $this->createSharedPostByGuid($shared['guid'], $add_media))) {
655 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $encaspulated_share, $item['body']);
658 $item['body'] = HTML::toBBCode(BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::ACTIVITYPUB));
661 $shared_content .= $item['body'] . '[/share]';
663 return $shared_content;
667 * Return the shared post from an item array (if the item is shared item)
670 * @param array $fields
672 * @return array with the shared post
674 public function getSharedPost(array $item, array $fields = []): array
676 if (!empty($item['quote-uri-id'])) {
677 $shared = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [0, $item['uid'] ?? 0]]);
678 if (is_array($shared)) {
680 'comment' => BBCode::removeSharedData($item['body'] ?? ''),
686 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
687 if (!empty($attributes)) {
688 $shared = Post::selectFirst($fields, ['guid' => $attributes['guid'], 'uid' => [0, $item['uid'] ?? 0]]);
689 if (is_array($shared)) {
691 'comment' => $attributes['comment'],
701 * Return share data from an item array (if the item is shared item)
702 * We are providing the complete Item array, because at some time in the future
703 * we hopefully will define these values not in the body anymore but in some item fields.
704 * This function is meant to replace all similar functions in the system.
708 * @return array with share information
710 private function getShareArray(array $item): array
712 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
713 if (!empty($attributes)) {
717 if (!empty($item['quote-uri-id'])) {
718 $shared = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'uri', 'body'], ['uri-id' => $item['quote-uri-id']]);
719 if (!empty($shared)) {
721 'author' => $shared['author-name'],
722 'profile' => $shared['author-link'],
723 'avatar' => $shared['author-avatar'],
724 'link' => $shared['plink'],
725 'posted' => $shared['created'],
726 'guid' => $shared['guid'],
727 'message_id' => $shared['uri'],
728 'comment' => $item['body'],
729 'shared' => $shared['body'],
738 * Add a link to a shared post at the end of the post
740 * @param string $body
741 * @param integer $quote_uri_id
744 public function addShareLink(string $body, int $quote_uri_id): string
746 $post = Post::selectFirstPost(['uri', 'plink'], ['uri-id' => $quote_uri_id]);
751 $body = BBCode::removeSharedData($body);
753 $body .= "\n♲ " . ($post['plink'] ?: $post['uri']);