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\Core\Hook;
26 use Friendica\Core\L10n;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Session;
30 use Friendica\Database\DBA;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Group;
33 use Friendica\Model\Item as ModelItem;
34 use Friendica\Model\Tag;
35 use Friendica\Model\Post;
36 use Friendica\Protocol\Activity;
37 use Friendica\Util\Profiler;
38 use Friendica\Util\Strings;
39 use Friendica\Util\XML;
42 * A content helper class for displaying items
53 public function __construct(Profiler $profiler, Activity $activity, L10n $l10n)
55 $this->profiler = $profiler;
56 $this->activity = $activity;
61 * Return array with details for categories and folders for an item
65 * @return [array, array]
68 * [ // categories array
70 * 'name': 'category name',
71 * 'removeurl': 'url to remove this category',
72 * 'first': 'is the first in this array? true/false',
73 * 'last': 'is the last in this array? true/false',
79 * 'name': 'folder name',
80 * 'removeurl': 'url to remove this folder',
81 * 'first': 'is the first in this array? true/false',
82 * 'last': 'is the last in this array? true/false',
88 public function determineCategoriesTerms(array $item, int $uid = 0)
94 $uid = $item['uid'] ?: $uid;
96 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::CATEGORY) as $savedFolderName) {
97 if (!empty($item['author-link'])) {
98 $url = $item['author-link'] . "?category=" . rawurlencode($savedFolderName);
103 'name' => $savedFolderName,
105 'removeurl' => local_user() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '',
112 if (count($categories)) {
113 $categories[count($categories) - 1]['last'] = true;
116 if (local_user() == $uid) {
117 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) {
119 'name' => $savedFolderName,
121 'removeurl' => local_user() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '',
129 if (count($folders)) {
130 $folders[count($folders) - 1]['last'] = true;
133 return [$categories, $folders];
137 * This function removes the tag $tag from the text $body and replaces it with
138 * the appropriate link.
140 * @param string $body the text to replace the tag in
141 * @param integer $profile_uid the user id to replace the tag for (0 = anyone)
142 * @param string $tag the tag to replace
143 * @param string $network The network of the post
145 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
146 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
147 * @throws \ImagickException
149 public static function replaceTag(&$body, $profile_uid, $tag, $network = '')
153 //is it a person tag?
154 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
155 $tag_type = substr($tag, 0, 1);
156 //is it already replaced?
157 if (strpos($tag, '[url=')) {
161 //get the person's name
162 $name = substr($tag, 1);
164 // Sometimes the tag detection doesn't seem to work right
165 // This is some workaround
166 $nameparts = explode(' ', $name);
167 $name = $nameparts[0];
169 // Try to detect the contact in various ways
170 if (strpos($name, 'http://') || strpos($name, '@')) {
171 $contact = Contact::getByURLForUser($name, $profile_uid);
174 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
176 if (strrpos($name, '+')) {
177 // Is it in format @nick+number?
178 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
179 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
182 // select someone by nick in the current network
183 if (!DBA::isResult($contact) && ($network != '')) {
184 $condition = ["`nick` = ? AND `network` = ? AND `uid` = ?",
185 $name, $network, $profile_uid];
186 $contact = DBA::selectFirst('contact', $fields, $condition);
189 // select someone by attag in the current network
190 if (!DBA::isResult($contact) && ($network != '')) {
191 $condition = ["`attag` = ? AND `network` = ? AND `uid` = ?",
192 $name, $network, $profile_uid];
193 $contact = DBA::selectFirst('contact', $fields, $condition);
196 //select someone by name in the current network
197 if (!DBA::isResult($contact) && ($network != '')) {
198 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
199 $contact = DBA::selectFirst('contact', $fields, $condition);
202 // select someone by nick in any network
203 if (!DBA::isResult($contact)) {
204 $condition = ["`nick` = ? AND `uid` = ?", $name, $profile_uid];
205 $contact = DBA::selectFirst('contact', $fields, $condition);
208 // select someone by attag in any network
209 if (!DBA::isResult($contact)) {
210 $condition = ["`attag` = ? AND `uid` = ?", $name, $profile_uid];
211 $contact = DBA::selectFirst('contact', $fields, $condition);
214 // select someone by name in any network
215 if (!DBA::isResult($contact)) {
216 $condition = ['name' => $name, 'uid' => $profile_uid];
217 $contact = DBA::selectFirst('contact', $fields, $condition);
221 // Check if $contact has been successfully loaded
222 if (DBA::isResult($contact)) {
223 $profile = $contact['url'];
224 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
227 //if there is an url for this persons profile
228 if (isset($profile) && ($newname != '')) {
230 // create profile link
231 $profile = str_replace(',', '%2c', $profile);
232 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
233 $body = str_replace($tag_type . $name, $newtag, $body);
237 return ['replaced' => $replaced, 'contact' => $contact];
241 * Render actions localized
244 * @throws ImagickException
245 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
247 public function localize(&$item)
249 $this->profiler->startRecording('rendering');
250 /// @todo The following functionality needs to be cleaned up.
251 if (!empty($item['verb'])) {
252 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
254 if (stristr($item['verb'], Activity::POKE)) {
255 $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
257 $this->profiler->stopRecording();
260 if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
261 $this->profiler->stopRecording();
265 $obj = XML::parseString($xmlhead . $item['object']);
267 $Bname = $obj->title;
271 foreach ($obj->link as $l) {
272 $atts = $l->attributes();
273 switch ($atts['rel']) {
274 case "alternate": $Blink = $atts['href'];
275 case "photo": $Bphoto = $atts['href'];
279 $author = ['uid' => 0, 'id' => $item['author-id'],
280 'network' => $item['author-network'], 'url' => $item['author-link']];
281 $A = '[url=' . Contact::magicLinkByContact($author) . ']' . $item['author-name'] . '[/url]';
283 if (!empty($Blink)) {
284 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
289 if ($Bphoto != "" && !empty($Blink)) {
290 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
294 * we can't have a translation string with three positions but no distinguishable text
295 * So here is the translate string.
297 $txt = $this->l10n->t('%1$s poked %2$s');
299 // now translate the verb
300 $poked_t = trim(sprintf($txt, '', ''));
301 $txt = str_replace($poked_t, $this->l10n->t($verb), $txt);
303 // then do the sprintf on the translation string
305 $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
309 if ($this->activity->match($item['verb'], Activity::TAG)) {
310 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
311 'verb', 'object-type', 'resource-id', 'body', 'plink'];
312 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
313 if (!DBA::isResult($obj)) {
314 $this->profiler->stopRecording();
318 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
319 'network' => $item['author-network'], 'url' => $item['author-link']];
320 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
322 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
323 'network' => $obj['author-network'], 'url' => $obj['author-link']];
324 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
326 switch ($obj['verb']) {
328 switch ($obj['object-type']) {
329 case Activity\ObjectType::EVENT:
330 $post_type = $this->l10n->t('event');
333 $post_type = $this->l10n->t('status');
337 if ($obj['resource-id']) {
338 $post_type = $this->l10n->t('photo');
339 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
340 $rr['plink'] = $m[1];
342 $post_type = $this->l10n->t('status');
344 // Let's break everthing ... ;-)
347 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
349 $parsedobj = XML::parseString($xmlhead . $item['object']);
351 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
352 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
357 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
358 foreach ($matches as $mtch) {
359 if (!strpos($mtch[1], 'zrl=')) {
360 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
365 // add sparkle links to appropriate permalinks
366 // Only create a redirection to a magic link when logged in
367 if (!empty($item['plink']) && Session::isAuthenticated() && $item['private'] == ModelItem::PRIVATE) {
368 $author = ['uid' => 0, 'id' => $item['author-id'],
369 'network' => $item['author-network'], 'url' => $item['author-link']];
370 $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
372 $this->profiler->stopRecording();
375 public function photoMenu($item, string $formSecurityToken)
377 $this->profiler->startRecording('rendering');
388 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
389 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
392 $author = ['uid' => 0, 'id' => $item['author-id'],
393 'network' => $item['author-network'], 'url' => $item['author-link']];
394 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
395 $sparkle = (strpos($profile_link, 'redir/') === 0);
398 $pcid = $item['author-id'];
401 $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
402 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
403 if (DBA::isResult($contact)) {
404 $cid = $contact['id'];
405 $network = $contact['network'];
406 $rel = $contact['rel'];
410 $status_link = $profile_link . '/status';
411 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
412 $profile_link = $profile_link . '/profile';
416 $contact_url = 'contact/' . $pcid;
417 $posts_link = $contact_url . '/posts';
418 $block_link = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
419 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
422 if ($cid && !$item['self']) {
423 $contact_url = 'contact/' . $cid;
424 $poke_link = $contact_url . '/poke';
425 $posts_link = $contact_url . '/posts';
427 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
428 $pm_url = 'message/new/' . $cid;
434 $this->l10n->t('Follow Thread') => $sub_link,
435 $this->l10n->t('View Status') => $status_link,
436 $this->l10n->t('View Profile') => $profile_link,
437 $this->l10n->t('View Photos') => $photos_link,
438 $this->l10n->t('Network Posts') => $posts_link,
439 $this->l10n->t('View Contact') => $contact_url,
440 $this->l10n->t('Send PM') => $pm_url,
441 $this->l10n->t('Block') => $block_link,
442 $this->l10n->t('Ignore') => $ignore_link
445 if (!empty($item['language'])) {
446 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ModelItem::getLanguageMessage($item) . '\');';
449 if ($network == Protocol::DFRN) {
450 $menu[$this->l10n->t("Poke")] = $poke_link;
453 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
454 in_array($item['network'], Protocol::FEDERATED)) {
455 $menu[$this->l10n->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
458 $menu = [$this->l10n->t('View Profile') => $item['author-link']];
461 $args = ['item' => $item, 'menu' => $menu];
463 Hook::callAll('item_photo_menu', $args);
465 $menu = $args['menu'];
468 foreach ($menu as $k => $v) {
469 if (strpos($v, 'javascript:') === 0) {
471 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
473 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
476 $this->profiler->stopRecording();
480 public function visibleActivity($item) {
482 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
486 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
487 if ($this->activity->match($item['verb'], Activity::FOLLOW) &&
488 $item['object-type'] === Activity\ObjectType::NOTE &&
489 empty($item['self']) &&
490 $item['uid'] == local_user()) {
497 public function expandTags(array $item, bool $setPermissions = false)
499 // Look for any tags and linkify them
500 $item['inform'] = '';
501 $private_forum = false;
503 $only_to_forum = false;
507 // Convert mentions in the body to a unified format
508 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
510 // Search for forum mentions
511 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
512 $contact = Contact::getByURLForUser($tag[2], $item['uid']);
514 $receivers[] = $contact['id'];
516 if (!empty($item['inform'])) {
517 $item['inform'] .= ',';
519 $item['inform'] .= 'cid:' . $contact['id'];
521 if (($item['gravity'] == GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
525 if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
526 $private_forum = $contact['prv'];
527 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
528 $private_id = $contact['id'];
529 $forum_contact = $contact;
530 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
531 } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
532 $private_forum = false;
533 $only_to_forum = true;
534 $private_id = $contact['id'];
535 $forum_contact = $contact;
536 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
538 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
541 Logger::info('Got inform', ['inform' => $item['inform']]);
543 if (($item['gravity'] == GRAVITY_PARENT) && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
544 // we tagged a forum in a top level post. Now we change the post
545 $item['private'] = $private_forum ? ModelItem::PRIVATE : ModelItem::UNLISTED;
547 if ($only_to_forum) {
548 $item['postopts'] = '';
551 $item['deny_cid'] = '';
552 $item['deny_gid'] = '';
554 if ($private_forum) {
555 $item['allow_cid'] = '<' . $private_id . '>';
556 $item['allow_gid'] = '<' . Group::getIdForForum($forum_contact['id']) . '>';
558 $item['allow_cid'] = '';
559 $item['allow_gid'] = '';
561 } elseif ($setPermissions && ($item['gravity'] == GRAVITY_PARENT)) {
562 if (empty($receivers)) {
563 // For security reasons direct posts without any receiver will be posts to yourself
564 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
565 $receivers[] = $self['id'];
568 $item['private'] = ModelItem::PRIVATE;
569 $item['allow_cid'] = '';
570 $item['allow_gid'] = '';
571 $item['deny_cid'] = '';
572 $item['deny_gid'] = '';
574 foreach ($receivers as $receiver) {
575 $item['allow_cid'] .= '<' . $receiver . '>';