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\System;
31 use Friendica\Database\DBA;
32 use Friendica\Model\Contact;
33 use Friendica\Model\Group;
34 use Friendica\Model\Item as ModelItem;
35 use Friendica\Model\Photo;
36 use Friendica\Model\Tag;
37 use Friendica\Model\Post;
38 use Friendica\Protocol\Activity;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\Profiler;
41 use Friendica\Util\Proxy;
42 use Friendica\Util\XML;
45 * A content helper class for displaying items
56 public function __construct(Profiler $profiler, Activity $activity, L10n $l10n)
58 $this->profiler = $profiler;
59 $this->activity = $activity;
64 * Return array with details for categories and folders for an item
68 * @return [array, array]
71 * [ // categories array
73 * 'name': 'category name',
74 * 'removeurl': 'url to remove this category',
75 * 'first': 'is the first in this array? true/false',
76 * 'last': 'is the last in this array? true/false',
82 * 'name': 'folder name',
83 * 'removeurl': 'url to remove this folder',
84 * 'first': 'is the first in this array? true/false',
85 * 'last': 'is the last in this array? true/false',
91 public function determineCategoriesTerms(array $item, int $uid = 0): array
97 $uid = $item['uid'] ?: $uid;
99 if (empty($item['has-categories'])) {
100 return [$categories, $folders];
103 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::CATEGORY) as $savedFolderName) {
104 if (!empty($item['author-link'])) {
105 $url = $item['author-link'] . "?category=" . rawurlencode($savedFolderName);
110 'name' => $savedFolderName,
112 'removeurl' => local_user() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '',
119 if (count($categories)) {
120 $categories[count($categories) - 1]['last'] = true;
123 if (local_user() == $uid) {
124 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) {
126 'name' => $savedFolderName,
128 'removeurl' => local_user() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '',
136 if (count($folders)) {
137 $folders[count($folders) - 1]['last'] = true;
140 return [$categories, $folders];
144 * This function removes the tag $tag from the text $body and replaces it with
145 * the appropriate link.
147 * @param string $body the text to replace the tag in
148 * @param int $profile_uid the user id to replace the tag for (0 = anyone)
149 * @param string $tag the tag to replace
150 * @param string $network The network of the post
152 * @return array|bool ['replaced' => $replaced, 'contact' => $contact] or "false" on if already replaced
153 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
154 * @throws \ImagickException
156 public static function replaceTag(string &$body, int $profile_uid, string $tag, string $network = '')
160 //is it a person tag?
161 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
162 $tag_type = substr($tag, 0, 1);
163 //is it already replaced?
164 if (strpos($tag, '[url=')) {
168 //get the person's name
169 $name = substr($tag, 1);
171 // Sometimes the tag detection doesn't seem to work right
172 // This is some workaround
173 $nameparts = explode(' ', $name);
174 $name = $nameparts[0];
176 // Try to detect the contact in various ways
177 if (strpos($name, 'http://') || strpos($name, '@')) {
178 $contact = Contact::getByURLForUser($name, $profile_uid);
181 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
183 if (strrpos($name, '+')) {
184 // Is it in format @nick+number?
185 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
186 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
189 // select someone by nick in the current network
190 if (!DBA::isResult($contact) && ($network != '')) {
191 $condition = ["`nick` = ? AND `network` = ? AND `uid` = ?",
192 $name, $network, $profile_uid];
193 $contact = DBA::selectFirst('contact', $fields, $condition);
196 // select someone by attag in the current network
197 if (!DBA::isResult($contact) && ($network != '')) {
198 $condition = ["`attag` = ? AND `network` = ? AND `uid` = ?",
199 $name, $network, $profile_uid];
200 $contact = DBA::selectFirst('contact', $fields, $condition);
203 //select someone by name in the current network
204 if (!DBA::isResult($contact) && ($network != '')) {
205 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
206 $contact = DBA::selectFirst('contact', $fields, $condition);
209 // select someone by nick in any network
210 if (!DBA::isResult($contact)) {
211 $condition = ["`nick` = ? AND `uid` = ?", $name, $profile_uid];
212 $contact = DBA::selectFirst('contact', $fields, $condition);
215 // select someone by attag in any network
216 if (!DBA::isResult($contact)) {
217 $condition = ["`attag` = ? AND `uid` = ?", $name, $profile_uid];
218 $contact = DBA::selectFirst('contact', $fields, $condition);
221 // select someone by name in any network
222 if (!DBA::isResult($contact)) {
223 $condition = ['name' => $name, 'uid' => $profile_uid];
224 $contact = DBA::selectFirst('contact', $fields, $condition);
228 // Check if $contact has been successfully loaded
229 if (DBA::isResult($contact)) {
230 $profile = $contact['url'];
231 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
234 //if there is an url for this persons profile
235 if (isset($profile) && ($newname != '')) {
237 // create profile link
238 $profile = str_replace(',', '%2c', $profile);
239 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
240 $body = str_replace($tag_type . $name, $newtag, $body);
244 return ['replaced' => $replaced, 'contact' => $contact];
248 * Render actions localized
252 * @throws ImagickException
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 public function localize(array &$item)
257 $this->profiler->startRecording('rendering');
258 /// @todo The following functionality needs to be cleaned up.
259 if (!empty($item['verb'])) {
260 $xmlhead = '<?xml version="1.0" encoding="UTF-8" ?>';
262 if ($this->activity->match($item['verb'], Activity::TAG)) {
263 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
264 'verb', 'object-type', 'resource-id', 'body', 'plink'];
265 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
266 if (!DBA::isResult($obj)) {
267 $this->profiler->stopRecording();
273 'id' => $item['author-id'],
274 'network' => $item['author-network'],
275 'url' => $item['author-link'],
277 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
281 'id' => $obj['author-id'],
282 'network' => $obj['author-network'],
283 'url' => $obj['author-link'],
285 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
287 switch ($obj['verb']) {
289 switch ($obj['object-type']) {
290 case Activity\ObjectType::EVENT:
291 $post_type = $this->l10n->t('event');
294 $post_type = $this->l10n->t('status');
299 if ($obj['resource-id']) {
300 $post_type = $this->l10n->t('photo');
301 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
302 $rr['plink'] = $m[1];
304 $post_type = $this->l10n->t('status');
306 // Let's break everthing ... ;-)
309 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
311 $parsedobj = XML::parseString($xmlhead . $item['object']);
313 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
314 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
318 $this->profiler->stopRecording();
322 * Renders photo menu based on item
325 * @param string $formSecurityToken
328 public function photoMenu(array $item, string $formSecurityToken): string
330 $this->profiler->startRecording('rendering');
331 $sub_link = $contact_url = $pm_url = $status_link = '';
332 $photos_link = $posts_link = $block_link = $ignore_link = '';
334 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
335 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
340 'id' => $item['author-id'],
341 'network' => $item['author-network'],
342 'url' => $item['author-link'],
344 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
345 $sparkle = (strpos($profile_link, 'redir/') === 0);
348 $pcid = $item['author-id'];
351 $condition = ['uid' => local_user(), 'uri-id' => $item['author-uri-id']];
352 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
353 if (DBA::isResult($contact)) {
354 $cid = $contact['id'];
355 $network = $contact['network'];
356 $rel = $contact['rel'];
360 $status_link = $profile_link . '/status';
361 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
362 $profile_link = $profile_link . '/profile';
366 $contact_url = 'contact/' . $pcid;
367 $posts_link = $contact_url . '/posts';
368 $block_link = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
369 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
372 if ($cid && !$item['self']) {
373 $contact_url = 'contact/' . $cid;
374 $posts_link = $contact_url . '/posts';
376 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
377 $pm_url = 'message/new/' . $cid;
383 $this->l10n->t('Follow Thread') => $sub_link,
384 $this->l10n->t('View Status') => $status_link,
385 $this->l10n->t('View Profile') => $profile_link,
386 $this->l10n->t('View Photos') => $photos_link,
387 $this->l10n->t('Network Posts') => $posts_link,
388 $this->l10n->t('View Contact') => $contact_url,
389 $this->l10n->t('Send PM') => $pm_url,
390 $this->l10n->t('Block') => $block_link,
391 $this->l10n->t('Ignore') => $ignore_link
394 if (!empty($item['language'])) {
395 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ModelItem::getLanguageMessage($item) . '\');';
398 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
399 in_array($item['network'], Protocol::FEDERATED)) {
400 $menu[$this->l10n->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
403 $menu = [$this->l10n->t('View Profile') => $item['author-link']];
406 $args = ['item' => $item, 'menu' => $menu];
408 Hook::callAll('item_photo_menu', $args);
410 $menu = $args['menu'];
413 foreach ($menu as $k => $v) {
414 if (strpos($v, 'javascript:') === 0) {
416 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
418 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
421 $this->profiler->stopRecording();
426 * Checks if the activity is visible to current user
428 * @param array $item Activity item
429 * @return bool Whether the item is visible to the user
431 public function isVisibleActivity(array $item): bool
433 // Empty verb or hidden?
434 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
439 return (!($this->activity->match($item['verb'], Activity::FOLLOW) &&
440 $item['object-type'] === Activity\ObjectType::NOTE &&
441 empty($item['self']) &&
442 $item['uid'] == local_user())
446 public function expandTags(array $item, bool $setPermissions = false): array
448 // Look for any tags and linkify them
449 $item['inform'] = '';
450 $private_forum = false;
452 $only_to_forum = false;
456 // Convert mentions in the body to a unified format
457 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
459 // Search for forum mentions
460 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
461 $contact = Contact::getByURLForUser($tag[2], $item['uid']);
462 if (empty($contact)) {
466 $receivers[] = $contact['id'];
468 if (!empty($item['inform'])) {
469 $item['inform'] .= ',';
471 $item['inform'] .= 'cid:' . $contact['id'];
473 if (($item['gravity'] == GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
477 if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
478 $private_forum = $contact['prv'];
479 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
480 $private_id = $contact['id'];
481 $forum_contact = $contact;
482 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
483 } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
484 $private_forum = false;
485 $only_to_forum = true;
486 $private_id = $contact['id'];
487 $forum_contact = $contact;
488 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
490 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
493 Logger::info('Got inform', ['inform' => $item['inform']]);
495 if (($item['gravity'] == GRAVITY_PARENT) && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
496 // we tagged a forum in a top level post. Now we change the post
497 $item['private'] = $private_forum ? ModelItem::PRIVATE : ModelItem::UNLISTED;
499 if ($only_to_forum) {
500 $item['postopts'] = '';
503 $item['deny_cid'] = '';
504 $item['deny_gid'] = '';
506 if ($private_forum) {
507 $item['allow_cid'] = '<' . $private_id . '>';
508 $item['allow_gid'] = '<' . Group::getIdForForum($forum_contact['id']) . '>';
510 $item['allow_cid'] = '';
511 $item['allow_gid'] = '';
513 } elseif ($setPermissions && ($item['gravity'] == GRAVITY_PARENT)) {
514 if (empty($receivers)) {
515 // For security reasons direct posts without any receiver will be posts to yourself
516 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
517 $receivers[] = $self['id'];
520 $item['private'] = ModelItem::PRIVATE;
521 $item['allow_cid'] = '';
522 $item['allow_gid'] = '';
523 $item['deny_cid'] = '';
524 $item['deny_gid'] = '';
526 foreach ($receivers as $receiver) {
527 $item['allow_cid'] .= '<' . $receiver . '>';
533 public function getAuthorAvatar(array $item): string
535 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
536 $author_avatar = $item['contact-id'];
537 $author_updated = '';
538 $author_thumb = $item['contact-avatar'];
540 $author_avatar = $item['author-id'];
541 $author_updated = $item['author-updated'];
542 $author_thumb = $item['author-avatar'];
546 if (empty($author_thumb) || Photo::isPhotoURI($author_thumb)) {
547 $author_thumb = Contact::getAvatarUrlForId($author_avatar, Proxy::SIZE_THUMB, $author_updated);
550 return $author_thumb;
553 public function getOwnerAvatar(array $item): string
555 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
556 $owner_avatar = $item['contact-id'];
558 $owner_thumb = $item['contact-avatar'];
560 $owner_avatar = $item['owner-id'];
561 $owner_updated = $item['owner-updated'];
562 $owner_thumb = $item['owner-avatar'];
565 if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) {
566 $owner_thumb = Contact::getAvatarUrlForId($owner_avatar, Proxy::SIZE_THUMB, $owner_updated);
573 * Add a share block for the given url
576 * @param integer $uid
579 public function createSharedPostByUrl(string $url, int $uid = 0): string
582 $id = ModelItem::searchByLink($url, $uid);
586 $id = ModelItem::fetchByLink($url);
590 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid, 'callstack' => System::callstack()]);
594 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid, 'callstack' => System::callstack()]);
596 $shared_item = Post::selectFirst(['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'], ['id' => $id]);
597 if (!DBA::isResult($shared_item)) {
598 Logger::warning('Post does not exist.', ['id' => $id, 'url' => $url, 'uid' => $uid]);
602 return $this->createSharedBlockByArray($shared_item);
606 * Add a share block for the given uri-id
608 * @param integer $UriId
609 * @param integer $uid
612 public function createSharedPostByUriId(int $UriId, int $uid = 0): string
614 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
615 $shared_item = Post::selectFirst($fields, ['uri-id' => $UriId, 'uid' => [$uid, 0], 'private' => [ModelItem::PUBLIC, ModelItem::UNLISTED]]);
616 if (!DBA::isResult($shared_item)) {
617 Logger::notice('Post does not exist.', ['uri-id' => $UriId, 'uid' => $uid]);
621 return $this->createSharedBlockByArray($shared_item);
625 * Add a share block for the given guid
627 * @param string $guid
628 * @param integer $uid
631 public function createSharedPostByGuid(string $guid, int $uid = 0, string $host = ''): string
633 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
634 $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [ModelItem::PUBLIC, ModelItem::UNLISTED]]);
636 if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) {
637 Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
638 $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [ModelItem::PUBLIC, ModelItem::UNLISTED]]);
639 } elseif (DBA::isResult($shared_item)) {
640 Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
643 if (!DBA::isResult($shared_item)) {
644 Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
648 return $this->createSharedBlockByArray($shared_item);
652 * Add a share block for the given item array
657 public function createSharedBlockByArray(array $item): string
659 if (!in_array($item['network'] ?? '', Protocol::FEDERATED)) {
662 $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
665 $shared_content = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid'], $item['uri']);
667 if (!empty($item['title'])) {
668 $shared_content .= '[h3]' . $item['title'] . "[/h3]\n";
671 $shared = BBCode::fetchShareAttributes($item['body']);
673 // If it is a reshared post then reformat it to avoid display problems with two share elements
674 if (Diaspora::isReshare($item['body'], false)) {
675 if (!empty($shared['guid']) && ($encaspulated_share = self::createSharedPostByGuid($shared['guid']))) {
676 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $encaspulated_share, $item['body']);
679 $item['body'] = HTML::toBBCode(BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::ACTIVITYPUB));
682 $shared_content .= $item['body'] . '[/share]';
684 return $shared_content;