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\XML;
41 * A content helper class for displaying items
52 public function __construct(Profiler $profiler, Activity $activity, L10n $l10n)
54 $this->profiler = $profiler;
55 $this->activity = $activity;
60 * Return array with details for categories and folders for an item
64 * @return [array, array]
67 * [ // categories array
69 * 'name': 'category name',
70 * 'removeurl': 'url to remove this category',
71 * 'first': 'is the first in this array? true/false',
72 * 'last': 'is the last in this array? true/false',
78 * 'name': 'folder name',
79 * 'removeurl': 'url to remove this folder',
80 * 'first': 'is the first in this array? true/false',
81 * 'last': 'is the last in this array? true/false',
87 public function determineCategoriesTerms(array $item, int $uid = 0)
93 $uid = $item['uid'] ?: $uid;
95 if (!Post\Category::existsForURIId($item['uri-id'], $uid)) {
96 return [$categories, $folders];
99 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::CATEGORY) as $savedFolderName) {
100 if (!empty($item['author-link'])) {
101 $url = $item['author-link'] . "?category=" . rawurlencode($savedFolderName);
106 'name' => $savedFolderName,
108 'removeurl' => local_user() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '',
115 if (count($categories)) {
116 $categories[count($categories) - 1]['last'] = true;
119 if (local_user() == $uid) {
120 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) {
122 'name' => $savedFolderName,
124 'removeurl' => local_user() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '',
132 if (count($folders)) {
133 $folders[count($folders) - 1]['last'] = true;
136 return [$categories, $folders];
140 * This function removes the tag $tag from the text $body and replaces it with
141 * the appropriate link.
143 * @param string $body the text to replace the tag in
144 * @param integer $profile_uid the user id to replace the tag for (0 = anyone)
145 * @param string $tag the tag to replace
146 * @param string $network The network of the post
148 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
149 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
150 * @throws \ImagickException
152 public static function replaceTag(&$body, $profile_uid, $tag, $network = '')
156 //is it a person tag?
157 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
158 $tag_type = substr($tag, 0, 1);
159 //is it already replaced?
160 if (strpos($tag, '[url=')) {
164 //get the person's name
165 $name = substr($tag, 1);
167 // Sometimes the tag detection doesn't seem to work right
168 // This is some workaround
169 $nameparts = explode(' ', $name);
170 $name = $nameparts[0];
172 // Try to detect the contact in various ways
173 if (strpos($name, 'http://') || strpos($name, '@')) {
174 $contact = Contact::getByURLForUser($name, $profile_uid);
177 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
179 if (strrpos($name, '+')) {
180 // Is it in format @nick+number?
181 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
182 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
185 // select someone by nick in the current network
186 if (!DBA::isResult($contact) && ($network != '')) {
187 $condition = ["`nick` = ? AND `network` = ? AND `uid` = ?",
188 $name, $network, $profile_uid];
189 $contact = DBA::selectFirst('contact', $fields, $condition);
192 // select someone by attag in the current network
193 if (!DBA::isResult($contact) && ($network != '')) {
194 $condition = ["`attag` = ? AND `network` = ? AND `uid` = ?",
195 $name, $network, $profile_uid];
196 $contact = DBA::selectFirst('contact', $fields, $condition);
199 //select someone by name in the current network
200 if (!DBA::isResult($contact) && ($network != '')) {
201 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
202 $contact = DBA::selectFirst('contact', $fields, $condition);
205 // select someone by nick in any network
206 if (!DBA::isResult($contact)) {
207 $condition = ["`nick` = ? AND `uid` = ?", $name, $profile_uid];
208 $contact = DBA::selectFirst('contact', $fields, $condition);
211 // select someone by attag in any network
212 if (!DBA::isResult($contact)) {
213 $condition = ["`attag` = ? AND `uid` = ?", $name, $profile_uid];
214 $contact = DBA::selectFirst('contact', $fields, $condition);
217 // select someone by name in any network
218 if (!DBA::isResult($contact)) {
219 $condition = ['name' => $name, 'uid' => $profile_uid];
220 $contact = DBA::selectFirst('contact', $fields, $condition);
224 // Check if $contact has been successfully loaded
225 if (DBA::isResult($contact)) {
226 $profile = $contact['url'];
227 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
230 //if there is an url for this persons profile
231 if (isset($profile) && ($newname != '')) {
233 // create profile link
234 $profile = str_replace(',', '%2c', $profile);
235 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
236 $body = str_replace($tag_type . $name, $newtag, $body);
240 return ['replaced' => $replaced, 'contact' => $contact];
244 * Render actions localized
247 * @throws ImagickException
248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 public function localize(&$item)
252 $this->profiler->startRecording('rendering');
253 /// @todo The following functionality needs to be cleaned up.
254 if (!empty($item['verb'])) {
255 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
257 if (stristr($item['verb'], Activity::POKE)) {
258 $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
260 $this->profiler->stopRecording();
263 if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
264 $this->profiler->stopRecording();
268 $obj = XML::parseString($xmlhead . $item['object']);
270 $Bname = $obj->title;
274 foreach ($obj->link as $l) {
275 $atts = $l->attributes();
276 switch ($atts['rel']) {
277 case "alternate": $Blink = $atts['href'];
278 case "photo": $Bphoto = $atts['href'];
282 $author = ['uid' => 0, 'id' => $item['author-id'],
283 'network' => $item['author-network'], 'url' => $item['author-link']];
284 $A = '[url=' . Contact::magicLinkByContact($author) . ']' . $item['author-name'] . '[/url]';
286 if (!empty($Blink)) {
287 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
292 if ($Bphoto != "" && !empty($Blink)) {
293 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
297 * we can't have a translation string with three positions but no distinguishable text
298 * So here is the translate string.
300 $txt = $this->l10n->t('%1$s poked %2$s');
302 // now translate the verb
303 $poked_t = trim(sprintf($txt, '', ''));
304 $txt = str_replace($poked_t, $this->l10n->t($verb), $txt);
306 // then do the sprintf on the translation string
308 $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
312 if ($this->activity->match($item['verb'], Activity::TAG)) {
313 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
314 'verb', 'object-type', 'resource-id', 'body', 'plink'];
315 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
316 if (!DBA::isResult($obj)) {
317 $this->profiler->stopRecording();
321 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
322 'network' => $item['author-network'], 'url' => $item['author-link']];
323 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
325 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
326 'network' => $obj['author-network'], 'url' => $obj['author-link']];
327 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
329 switch ($obj['verb']) {
331 switch ($obj['object-type']) {
332 case Activity\ObjectType::EVENT:
333 $post_type = $this->l10n->t('event');
336 $post_type = $this->l10n->t('status');
340 if ($obj['resource-id']) {
341 $post_type = $this->l10n->t('photo');
342 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
343 $rr['plink'] = $m[1];
345 $post_type = $this->l10n->t('status');
347 // Let's break everthing ... ;-)
350 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
352 $parsedobj = XML::parseString($xmlhead . $item['object']);
354 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
355 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
359 $this->profiler->stopRecording();
362 public function photoMenu($item, string $formSecurityToken)
364 $this->profiler->startRecording('rendering');
375 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
376 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
379 $author = ['uid' => 0, 'id' => $item['author-id'],
380 'network' => $item['author-network'], 'url' => $item['author-link']];
381 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
382 $sparkle = (strpos($profile_link, 'redir/') === 0);
385 $pcid = $item['author-id'];
388 $condition = ['uid' => local_user(), 'uri-id' => $item['author-uri-id']];
389 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
390 if (DBA::isResult($contact)) {
391 $cid = $contact['id'];
392 $network = $contact['network'];
393 $rel = $contact['rel'];
397 $status_link = $profile_link . '/status';
398 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
399 $profile_link = $profile_link . '/profile';
403 $contact_url = 'contact/' . $pcid;
404 $posts_link = $contact_url . '/posts';
405 $block_link = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
406 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
409 if ($cid && !$item['self']) {
410 $contact_url = 'contact/' . $cid;
411 $poke_link = $contact_url . '/poke';
412 $posts_link = $contact_url . '/posts';
414 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
415 $pm_url = 'message/new/' . $cid;
421 $this->l10n->t('Follow Thread') => $sub_link,
422 $this->l10n->t('View Status') => $status_link,
423 $this->l10n->t('View Profile') => $profile_link,
424 $this->l10n->t('View Photos') => $photos_link,
425 $this->l10n->t('Network Posts') => $posts_link,
426 $this->l10n->t('View Contact') => $contact_url,
427 $this->l10n->t('Send PM') => $pm_url,
428 $this->l10n->t('Block') => $block_link,
429 $this->l10n->t('Ignore') => $ignore_link
432 if (!empty($item['language'])) {
433 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ModelItem::getLanguageMessage($item) . '\');';
436 if ($network == Protocol::DFRN) {
437 $menu[$this->l10n->t("Poke")] = $poke_link;
440 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
441 in_array($item['network'], Protocol::FEDERATED)) {
442 $menu[$this->l10n->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
445 $menu = [$this->l10n->t('View Profile') => $item['author-link']];
448 $args = ['item' => $item, 'menu' => $menu];
450 Hook::callAll('item_photo_menu', $args);
452 $menu = $args['menu'];
455 foreach ($menu as $k => $v) {
456 if (strpos($v, 'javascript:') === 0) {
458 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
460 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
463 $this->profiler->stopRecording();
467 public function visibleActivity($item) {
469 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
473 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
474 if ($this->activity->match($item['verb'], Activity::FOLLOW) &&
475 $item['object-type'] === Activity\ObjectType::NOTE &&
476 empty($item['self']) &&
477 $item['uid'] == local_user()) {
484 public function expandTags(array $item, bool $setPermissions = false)
486 // Look for any tags and linkify them
487 $item['inform'] = '';
488 $private_forum = false;
490 $only_to_forum = false;
494 // Convert mentions in the body to a unified format
495 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
497 // Search for forum mentions
498 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
499 $contact = Contact::getByURLForUser($tag[2], $item['uid']);
501 $receivers[] = $contact['id'];
503 if (!empty($item['inform'])) {
504 $item['inform'] .= ',';
506 $item['inform'] .= 'cid:' . $contact['id'];
508 if (($item['gravity'] == GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
512 if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
513 $private_forum = $contact['prv'];
514 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
515 $private_id = $contact['id'];
516 $forum_contact = $contact;
517 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
518 } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
519 $private_forum = false;
520 $only_to_forum = true;
521 $private_id = $contact['id'];
522 $forum_contact = $contact;
523 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
525 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
528 Logger::info('Got inform', ['inform' => $item['inform']]);
530 if (($item['gravity'] == GRAVITY_PARENT) && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
531 // we tagged a forum in a top level post. Now we change the post
532 $item['private'] = $private_forum ? ModelItem::PRIVATE : ModelItem::UNLISTED;
534 if ($only_to_forum) {
535 $item['postopts'] = '';
538 $item['deny_cid'] = '';
539 $item['deny_gid'] = '';
541 if ($private_forum) {
542 $item['allow_cid'] = '<' . $private_id . '>';
543 $item['allow_gid'] = '<' . Group::getIdForForum($forum_contact['id']) . '>';
545 $item['allow_cid'] = '';
546 $item['allow_gid'] = '';
548 } elseif ($setPermissions && ($item['gravity'] == GRAVITY_PARENT)) {
549 if (empty($receivers)) {
550 // For security reasons direct posts without any receiver will be posts to yourself
551 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
552 $receivers[] = $self['id'];
555 $item['private'] = ModelItem::PRIVATE;
556 $item['allow_cid'] = '';
557 $item['allow_gid'] = '';
558 $item['deny_cid'] = '';
559 $item['deny_gid'] = '';
561 foreach ($receivers as $receiver) {
562 $item['allow_cid'] .= '<' . $receiver . '>';