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;
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
57 public function __construct(Profiler $profiler, Activity $activity, L10n $l10n)
59 $this->profiler = $profiler;
60 $this->activity = $activity;
65 * Return array with details for categories and folders for an item
69 * @return [array, array]
72 * [ // categories array
74 * 'name': 'category name',
75 * 'removeurl': 'url to remove this category',
76 * 'first': 'is the first in this array? true/false',
77 * 'last': 'is the last in this array? true/false',
83 * 'name': 'folder name',
84 * 'removeurl': 'url to remove this folder',
85 * 'first': 'is the first in this array? true/false',
86 * 'last': 'is the last in this array? true/false',
92 public function determineCategoriesTerms(array $item, int $uid = 0): array
98 $uid = $item['uid'] ?: $uid;
100 if (empty($item['has-categories'])) {
101 return [$categories, $folders];
104 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::CATEGORY) as $savedFolderName) {
105 if (!empty($item['author-link'])) {
106 $url = $item['author-link'] . "?category=" . rawurlencode($savedFolderName);
111 'name' => $savedFolderName,
113 'removeurl' => Session::getLocalUser() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '',
120 if (count($categories)) {
121 $categories[count($categories) - 1]['last'] = true;
124 if (Session::getLocalUser() == $uid) {
125 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) {
127 'name' => $savedFolderName,
129 'removeurl' => Session::getLocalUser() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '',
137 if (count($folders)) {
138 $folders[count($folders) - 1]['last'] = true;
141 return [$categories, $folders];
145 * This function removes the tag $tag from the text $body and replaces it with
146 * the appropriate link.
148 * @param string $body the text to replace the tag in
149 * @param int $profile_uid the user id to replace the tag for (0 = anyone)
150 * @param string $tag the tag to replace
151 * @param string $network The network of the post
153 * @return array|bool ['replaced' => $replaced, 'contact' => $contact] or "false" on if already replaced
154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
155 * @throws \ImagickException
157 public static function replaceTag(string &$body, int $profile_uid, string $tag, string $network = '')
161 //is it a person tag?
162 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
163 $tag_type = substr($tag, 0, 1);
164 //is it already replaced?
165 if (strpos($tag, '[url=')) {
169 //get the person's name
170 $name = substr($tag, 1);
172 // Sometimes the tag detection doesn't seem to work right
173 // This is some workaround
174 $nameparts = explode(' ', $name);
175 $name = $nameparts[0];
177 // Try to detect the contact in various ways
178 if (strpos($name, 'http://') || strpos($name, '@')) {
179 $contact = Contact::getByURLForUser($name, $profile_uid);
182 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
184 if (strrpos($name, '+')) {
185 // Is it in format @nick+number?
186 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
187 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
190 // select someone by nick in the current network
191 if (!DBA::isResult($contact) && ($network != '')) {
192 $condition = ["`nick` = ? AND `network` = ? AND `uid` = ?",
193 $name, $network, $profile_uid];
194 $contact = DBA::selectFirst('contact', $fields, $condition);
197 // select someone by attag in the current network
198 if (!DBA::isResult($contact) && ($network != '')) {
199 $condition = ["`attag` = ? AND `network` = ? AND `uid` = ?",
200 $name, $network, $profile_uid];
201 $contact = DBA::selectFirst('contact', $fields, $condition);
204 //select someone by name in the current network
205 if (!DBA::isResult($contact) && ($network != '')) {
206 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
207 $contact = DBA::selectFirst('contact', $fields, $condition);
210 // select someone by nick in any network
211 if (!DBA::isResult($contact)) {
212 $condition = ["`nick` = ? AND `uid` = ?", $name, $profile_uid];
213 $contact = DBA::selectFirst('contact', $fields, $condition);
216 // select someone by attag in any network
217 if (!DBA::isResult($contact)) {
218 $condition = ["`attag` = ? AND `uid` = ?", $name, $profile_uid];
219 $contact = DBA::selectFirst('contact', $fields, $condition);
222 // select someone by name in any network
223 if (!DBA::isResult($contact)) {
224 $condition = ['name' => $name, 'uid' => $profile_uid];
225 $contact = DBA::selectFirst('contact', $fields, $condition);
229 // Check if $contact has been successfully loaded
230 if (DBA::isResult($contact)) {
231 $profile = $contact['url'];
232 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
235 //if there is an url for this persons profile
236 if (isset($profile) && ($newname != '')) {
238 // create profile link
239 $profile = str_replace(',', '%2c', $profile);
240 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
241 $body = str_replace($tag_type . $name, $newtag, $body);
245 return ['replaced' => $replaced, 'contact' => $contact];
249 * Render actions localized
253 * @throws ImagickException
254 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
256 public function localize(array &$item)
258 $this->profiler->startRecording('rendering');
259 /// @todo The following functionality needs to be cleaned up.
260 if (!empty($item['verb'])) {
261 $xmlhead = '<?xml version="1.0" encoding="UTF-8" ?>';
263 if ($this->activity->match($item['verb'], Activity::TAG)) {
264 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
265 'verb', 'object-type', 'resource-id', 'body', 'plink'];
266 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
267 if (!DBA::isResult($obj)) {
268 $this->profiler->stopRecording();
274 'id' => $item['author-id'],
275 'network' => $item['author-network'],
276 'url' => $item['author-link'],
278 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
282 'id' => $obj['author-id'],
283 'network' => $obj['author-network'],
284 'url' => $obj['author-link'],
286 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
288 switch ($obj['verb']) {
290 switch ($obj['object-type']) {
291 case Activity\ObjectType::EVENT:
292 $post_type = $this->l10n->t('event');
295 $post_type = $this->l10n->t('status');
300 if ($obj['resource-id']) {
301 $post_type = $this->l10n->t('photo');
302 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
303 $rr['plink'] = $m[1];
305 $post_type = $this->l10n->t('status');
307 // Let's break everthing ... ;-)
310 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
312 $parsedobj = XML::parseString($xmlhead . $item['object']);
314 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
315 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
319 $this->profiler->stopRecording();
323 * Renders photo menu based on item
326 * @param string $formSecurityToken
329 public function photoMenu(array $item, string $formSecurityToken): string
331 $this->profiler->startRecording('rendering');
332 $sub_link = $contact_url = $pm_url = $status_link = '';
333 $photos_link = $posts_link = $block_link = $ignore_link = '';
335 if (Session::getLocalUser() && Session::getLocalUser() == $item['uid'] && $item['gravity'] == ItemModel::GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
336 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
341 'id' => $item['author-id'],
342 'network' => $item['author-network'],
343 'url' => $item['author-link'],
345 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
346 $sparkle = (strpos($profile_link, 'redir/') === 0);
349 $pcid = $item['author-id'];
352 $condition = ['uid' => Session::getLocalUser(), 'uri-id' => $item['author-uri-id']];
353 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
354 if (DBA::isResult($contact)) {
355 $cid = $contact['id'];
356 $network = $contact['network'];
357 $rel = $contact['rel'];
361 $status_link = $profile_link . '/status';
362 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
363 $profile_link = $profile_link . '/profile';
367 $contact_url = 'contact/' . $pcid;
368 $posts_link = $contact_url . '/posts';
369 $block_link = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
370 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
373 if ($cid && !$item['self']) {
374 $contact_url = 'contact/' . $cid;
375 $posts_link = $contact_url . '/posts';
377 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
378 $pm_url = 'message/new/' . $cid;
382 if (Session::getLocalUser()) {
384 $this->l10n->t('Follow Thread') => $sub_link,
385 $this->l10n->t('View Status') => $status_link,
386 $this->l10n->t('View Profile') => $profile_link,
387 $this->l10n->t('View Photos') => $photos_link,
388 $this->l10n->t('Network Posts') => $posts_link,
389 $this->l10n->t('View Contact') => $contact_url,
390 $this->l10n->t('Send PM') => $pm_url,
391 $this->l10n->t('Block') => $block_link,
392 $this->l10n->t('Ignore') => $ignore_link
395 if (!empty($item['language'])) {
396 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ItemModel::getLanguageMessage($item) . '\');';
399 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
400 in_array($item['network'], Protocol::FEDERATED)) {
401 $menu[$this->l10n->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
404 $menu = [$this->l10n->t('View Profile') => $item['author-link']];
407 $args = ['item' => $item, 'menu' => $menu];
409 Hook::callAll('item_photo_menu', $args);
411 $menu = $args['menu'];
414 foreach ($menu as $k => $v) {
415 if (strpos($v, 'javascript:') === 0) {
417 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
419 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
422 $this->profiler->stopRecording();
427 * Checks if the activity is visible to current user
429 * @param array $item Activity item
430 * @return bool Whether the item is visible to the user
432 public function isVisibleActivity(array $item): bool
434 // Empty verb or hidden?
435 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
440 return (!($this->activity->match($item['verb'], Activity::FOLLOW) &&
441 $item['object-type'] === Activity\ObjectType::NOTE &&
442 empty($item['self']) &&
443 $item['uid'] == Session::getLocalUser())
447 public function expandTags(array $item, bool $setPermissions = false): array
449 // Look for any tags and linkify them
450 $item['inform'] = '';
451 $private_forum = false;
453 $only_to_forum = false;
457 // Convert mentions in the body to a unified format
458 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
460 // Search for forum mentions
461 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
462 $contact = Contact::getByURLForUser($tag[2], $item['uid']);
463 if (empty($contact)) {
467 $receivers[] = $contact['id'];
469 if (!empty($item['inform'])) {
470 $item['inform'] .= ',';
472 $item['inform'] .= 'cid:' . $contact['id'];
474 if (($item['gravity'] == ItemModel::GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
478 if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
479 $private_forum = $contact['prv'];
480 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
481 $private_id = $contact['id'];
482 $forum_contact = $contact;
483 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
484 } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
485 $private_forum = false;
486 $only_to_forum = true;
487 $private_id = $contact['id'];
488 $forum_contact = $contact;
489 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
491 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
494 Logger::info('Got inform', ['inform' => $item['inform']]);
496 if (($item['gravity'] == ItemModel::GRAVITY_PARENT) && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
497 // we tagged a forum in a top level post. Now we change the post
498 $item['private'] = $private_forum ? ItemModel::PRIVATE : ItemModel::UNLISTED;
500 if ($only_to_forum) {
501 $item['postopts'] = '';
504 $item['deny_cid'] = '';
505 $item['deny_gid'] = '';
507 if ($private_forum) {
508 $item['allow_cid'] = '<' . $private_id . '>';
509 $item['allow_gid'] = '<' . Group::getIdForForum($forum_contact['id']) . '>';
511 $item['allow_cid'] = '';
512 $item['allow_gid'] = '';
514 } elseif ($setPermissions && ($item['gravity'] == ItemModel::GRAVITY_PARENT)) {
515 if (empty($receivers)) {
516 // For security reasons direct posts without any receiver will be posts to yourself
517 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
518 $receivers[] = $self['id'];
521 $item['private'] = ItemModel::PRIVATE;
522 $item['allow_cid'] = '';
523 $item['allow_gid'] = '';
524 $item['deny_cid'] = '';
525 $item['deny_gid'] = '';
527 foreach ($receivers as $receiver) {
528 $item['allow_cid'] .= '<' . $receiver . '>';
534 public function getAuthorAvatar(array $item): string
536 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
537 $author_avatar = $item['contact-id'];
538 $author_updated = '';
539 $author_thumb = $item['contact-avatar'];
541 $author_avatar = $item['author-id'];
542 $author_updated = $item['author-updated'];
543 $author_thumb = $item['author-avatar'];
547 if (empty($author_thumb) || Photo::isPhotoURI($author_thumb)) {
548 $author_thumb = Contact::getAvatarUrlForId($author_avatar, Proxy::SIZE_THUMB, $author_updated);
551 return $author_thumb;
554 public function getOwnerAvatar(array $item): string
556 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
557 $owner_avatar = $item['contact-id'];
559 $owner_thumb = $item['contact-avatar'];
561 $owner_avatar = $item['owner-id'];
562 $owner_updated = $item['owner-updated'];
563 $owner_thumb = $item['owner-avatar'];
566 if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) {
567 $owner_thumb = Contact::getAvatarUrlForId($owner_avatar, Proxy::SIZE_THUMB, $owner_updated);
574 * Add a share block for the given url
577 * @param integer $uid
578 * @param bool $add_media
581 public function createSharedPostByUrl(string $url, int $uid = 0, bool $add_media = false): string
584 $id = ItemModel::searchByLink($url, $uid);
588 $id = ItemModel::fetchByLink($url);
592 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid, 'callstack' => System::callstack()]);
596 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid, 'callstack' => System::callstack()]);
598 $shared_item = Post::selectFirst(['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'], ['id' => $id]);
599 if (!DBA::isResult($shared_item)) {
600 Logger::warning('Post does not exist.', ['id' => $id, 'url' => $url, 'uid' => $uid]);
604 return $this->createSharedBlockByArray($shared_item, $add_media);
608 * Add a share block for the given uri-id
610 * @param integer $UriId
611 * @param integer $uid
612 * @param bool $add_media
615 public function createSharedPostByUriId(int $UriId, int $uid = 0, bool $add_media = false): string
617 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
618 $shared_item = Post::selectFirst($fields, ['uri-id' => $UriId, 'uid' => [$uid, 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
619 if (!DBA::isResult($shared_item)) {
620 Logger::notice('Post does not exist.', ['uri-id' => $UriId, 'uid' => $uid]);
624 return $this->createSharedBlockByArray($shared_item, $add_media);
628 * Add a share block for the given guid
630 * @param string $guid
631 * @param integer $uid
632 * @param bool $add_media
635 public function createSharedPostByGuid(string $guid, int $uid = 0, string $host = '', bool $add_media = false): string
637 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
638 $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
640 if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) {
641 Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
642 $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
643 } elseif (DBA::isResult($shared_item)) {
644 Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
647 if (!DBA::isResult($shared_item)) {
648 Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
652 return $this->createSharedBlockByArray($shared_item, $add_media);
656 * Add a share block for the given item array
659 * @param bool $add_media
662 public function createSharedBlockByArray(array $item, bool $add_media = false): string
664 if ($item['network'] == Protocol::FEED) {
665 return PageInfo::getFooterFromUrl($item['plink']);
666 } elseif (!in_array($item['network'] ?? '', Protocol::FEDERATED)) {
669 $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
670 } elseif ($add_media) {
671 $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
674 $shared_content = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid'], $item['uri']);
676 if (!empty($item['title'])) {
677 $shared_content .= '[h3]' . $item['title'] . "[/h3]\n";
680 $shared = ItemModel::getShareArray($item);
682 // If it is a reshared post then reformat it to avoid display problems with two share elements
683 if (!empty($shared)) {
684 if (!empty($shared['guid']) && ($encaspulated_share = self::createSharedPostByGuid($shared['guid'], 0, '', $add_media))) {
685 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $encaspulated_share, $item['body']);
688 $item['body'] = HTML::toBBCode(BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::ACTIVITYPUB));
691 $shared_content .= $item['body'] . '[/share]';
693 return $shared_content;