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;
25 use Friendica\App\Arguments;
26 use Friendica\App\BaseURL;
27 use Friendica\BaseModule;
28 use Friendica\Core\ACL;
29 use Friendica\Core\Config\Capability\IManageConfigValues;
30 use Friendica\Core\Hook;
31 use Friendica\Core\L10n;
32 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
33 use Friendica\Core\Protocol;
34 use Friendica\Core\Renderer;
35 use Friendica\Core\Session;
36 use Friendica\Core\Theme;
37 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Item as ItemModel;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Model\Verb;
45 use Friendica\Object\Post as PostObject;
46 use Friendica\Object\Thread;
47 use Friendica\Protocol\Activity;
48 use Friendica\Util\Crypto;
49 use Friendica\Util\DateTimeFormat;
50 use Friendica\Util\Profiler;
51 use Friendica\Util\Proxy;
52 use Friendica\Util\Strings;
53 use Friendica\Util\Temporal;
54 use Psr\Log\LoggerInterface;
64 /** @var LoggerInterface */
68 /** @var App\Arguments */
70 /** @var IManagePersonalConfigValues */
74 /** @var IManageConfigValues */
83 public function __construct(LoggerInterface $logger, Profiler $profiler, Activity $activity, L10n $l10n, Item $item, Arguments $args, BaseURL $baseURL, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, App\Page $page, App\Mode $mode, App $app)
85 $this->activity = $activity;
87 $this->config = $config;
89 $this->baseURL = $baseURL;
90 $this->profiler = $profiler;
91 $this->logger = $logger;
94 $this->pConfig = $pConfig;
100 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
102 * Increments the count of each matching activity and adds a link to the author as needed.
104 * @param array $activity
105 * @param array &$conv_responses (already created with builtin activity structure)
107 * @throws ImagickException
108 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
110 public function builtinActivityPuller(array $activity, array &$conv_responses)
112 $thread_parent = $activity['thr-parent-row'] ?? [];
114 foreach ($conv_responses as $mode => $v) {
119 $verb = Activity::LIKE;
122 $verb = Activity::DISLIKE;
125 $verb = Activity::ATTEND;
128 $verb = Activity::ATTENDNO;
131 $verb = Activity::ATTENDMAYBE;
134 $verb = Activity::ANNOUNCE;
140 if (!empty($activity['verb']) && $this->activity->match($activity['verb'], $verb) && ($activity['gravity'] != GRAVITY_PARENT)) {
143 'id' => $activity['author-id'],
144 'network' => $activity['author-network'],
145 'url' => $activity['author-link']
147 $url = Contact::magicLinkByContact($author);
148 if (strpos($url, 'redir/') === 0) {
149 $sparkle = ' class="sparkle" ';
152 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
154 if (empty($activity['thr-parent-id'])) {
155 $activity['thr-parent-id'] = $activity['parent-uri-id'];
158 // Skip when the causer of the parent is the same as the author of the announce
159 if (($verb == Activity::ANNOUNCE) && !empty($thread_parent['causer-id'] && ($thread_parent['causer-id'] == $activity['author-id']))) {
163 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
164 $conv_responses[$mode][$activity['thr-parent-id']] = [
168 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
169 // only list each unique author once
173 if (public_contact() == $activity['author-id']) {
174 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
177 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
179 // there can only be one activity verb per item so if we found anything, we can stop looking
186 * Format the activity text for an item/photo/video
188 * @param array $links = array of pre-linked names of actors
189 * @param string $verb = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
190 * @param int $id = item id
191 * @return string formatted text
192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
194 public function formatActivity(array $links, $verb, $id)
196 $this->profiler->startRecording('rendering');
201 $total = count($links);
205 // Phrase if there is only one liker. In other cases it will be uses for the expanded
206 // list which show all likers
209 $phrase = $this->l10n->t('%s likes this.', $likers);
212 $phrase = $this->l10n->t('%s doesn\'t like this.', $likers);
215 $phrase = $this->l10n->t('%s attends.', $likers);
218 $phrase = $this->l10n->t('%s doesn\'t attend.', $likers);
221 $phrase = $this->l10n->t('%s attends maybe.', $likers);
224 $phrase = $this->l10n->t('%s reshared this.', $likers);
227 } elseif ($total > 1) {
228 if ($total < $this->config->get('system', 'max_likers')) {
229 $likers = implode(', ', array_slice($links, 0, -1));
230 $likers .= ' ' . $this->l10n->t('and') . ' ' . $links[count($links) - 1];
232 $likers = implode(', ', array_slice($links, 0, $this->config->get('system', 'max_likers') - 1));
233 $likers .= ' ' . $this->l10n->t('and %d other people', $total - $this->config->get('system', 'max_likers'));
236 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
241 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> like this', $spanatts, $total);
242 $explikers = $this->l10n->t('%s like this.', $likers);
245 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $total);
246 $explikers = $this->l10n->t('%s don\'t like this.', $likers);
249 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> attend', $spanatts, $total);
250 $explikers = $this->l10n->t('%s attend.', $likers);
253 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $total);
254 $explikers = $this->l10n->t('%s don\'t attend.', $likers);
257 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $total);
258 $explikers = $this->l10n->t('%s attend maybe.', $likers);
261 $phrase = $this->l10n->t('<span %1$s>%2$d people</span> reshared this', $spanatts, $total);
262 $explikers = $this->l10n->t('%s reshared this.', $likers);
266 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
269 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
270 '$phrase' => $phrase,
276 $this->profiler->stopRecording();
280 public function statusEditor(array $x = [], $notes_cid = 0, $popup = false)
282 $user = User::getById($this->app->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
283 if (empty($user['uid'])) {
287 $this->profiler->startRecording('rendering');
290 $x['allow_location'] = $x['allow_location'] ?? $user['allow_location'];
291 $x['default_location'] = $x['default_location'] ?? $user['default-location'];
292 $x['nickname'] = $x['nickname'] ?? $user['nickname'];
293 $x['lockstate'] = $x['lockstate'] ?? ACL::getLockstateForUserId($user['uid']) ? 'lock' : 'unlock';
294 $x['acl'] = $x['acl'] ?? ACL::getFullSelectorHTML($this->page, $user['uid'], true);
295 $x['bang'] = $x['bang'] ?? '';
296 $x['visitor'] = $x['visitor'] ?? 'block';
297 $x['is_owner'] = $x['is_owner'] ?? true;
298 $x['profile_uid'] = $x['profile_uid'] ?? local_user();
301 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
303 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
304 $this->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
305 '$newpost' => 'true',
306 '$baseurl' => $this->baseURL->get(true),
307 '$geotag' => $geotag,
308 '$nickname' => $x['nickname'],
309 '$ispublic' => $this->l10n->t('Visible to <strong>everybody</strong>'),
310 '$linkurl' => $this->l10n->t('Please enter a image/video/audio/webpage URL:'),
311 '$term' => $this->l10n->t('Tag term:'),
312 '$fileas' => $this->l10n->t('Save to Folder:'),
313 '$whereareu' => $this->l10n->t('Where are you right now?'),
314 '$delitems' => $this->l10n->t("Delete item\x28s\x29?"),
315 '$is_mobile' => $this->mode->isMobile(),
319 Hook::callAll('jot_tool', $jotplugins);
321 if ($this->config->get('system', 'set_creation_date')) {
322 $created_at = Temporal::getDateTimeField(
323 new \DateTime(DBA::NULL_DATETIME),
324 new \DateTime('now'),
326 $this->l10n->t('Created at'),
333 $tpl = Renderer::getMarkupTemplate("jot.tpl");
335 $o .= Renderer::replaceMacros($tpl, [
336 '$new_post' => $this->l10n->t('New Post'),
337 '$return_path' => $this->args->getQueryString(),
339 '$share' => ($x['button'] ?? '') ?: $this->l10n->t('Share'),
340 '$loading' => $this->l10n->t('Loading...'),
341 '$upload' => $this->l10n->t('Upload photo'),
342 '$shortupload' => $this->l10n->t('upload photo'),
343 '$attach' => $this->l10n->t('Attach file'),
344 '$shortattach' => $this->l10n->t('attach file'),
345 '$edbold' => $this->l10n->t('Bold'),
346 '$editalic' => $this->l10n->t('Italic'),
347 '$eduline' => $this->l10n->t('Underline'),
348 '$edquote' => $this->l10n->t('Quote'),
349 '$edcode' => $this->l10n->t('Code'),
350 '$edimg' => $this->l10n->t('Image'),
351 '$edurl' => $this->l10n->t('Link'),
352 '$edattach' => $this->l10n->t('Link or Media'),
353 '$edvideo' => $this->l10n->t('Video'),
354 '$setloc' => $this->l10n->t('Set your location'),
355 '$shortsetloc' => $this->l10n->t('set location'),
356 '$noloc' => $this->l10n->t('Clear browser location'),
357 '$shortnoloc' => $this->l10n->t('clear location'),
358 '$title' => $x['title'] ?? '',
359 '$placeholdertitle' => $this->l10n->t('Set title'),
360 '$category' => $x['category'] ?? '',
361 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? $this->l10n->t("Categories \x28comma-separated list\x29") : '',
362 '$scheduled_at' => Temporal::getDateTimeField(
364 new \DateTime('now + 6 months'),
366 $this->l10n->t('Scheduled at'),
369 '$created_at' => $created_at,
370 '$wait' => $this->l10n->t('Please wait'),
371 '$permset' => $this->l10n->t('Permission settings'),
372 '$shortpermset' => $this->l10n->t('Permissions'),
373 '$wall' => $notes_cid ? 0 : 1,
374 '$posttype' => $notes_cid ? ItemModel::PT_PERSONAL_NOTE : ItemModel::PT_ARTICLE,
375 '$content' => $x['content'] ?? '',
376 '$post_id' => $x['post_id'] ?? '',
377 '$baseurl' => $this->baseURL->get(true),
378 '$defloc' => $x['default_location'],
379 '$visitor' => $x['visitor'],
380 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
381 '$public' => $this->l10n->t('Public post'),
382 '$lockstate' => $x['lockstate'],
383 '$bang' => $x['bang'],
384 '$profile_uid' => $x['profile_uid'],
385 '$preview' => $this->l10n->t('Preview'),
386 '$jotplugins' => $jotplugins,
387 '$notes_cid' => $notes_cid,
388 '$cancel' => $this->l10n->t('Cancel'),
389 '$rand_num' => Crypto::randomDigits(12),
391 // ACL permissions box
394 //jot nav tab (used in some themes)
395 '$message' => $this->l10n->t('Message'),
396 '$browser' => $this->l10n->t('Browser'),
398 '$compose_link_title' => $this->l10n->t('Open Compose page'),
402 if ($popup == true) {
403 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
406 $this->profiler->stopRecording();
411 * "Render" a conversation or list of items for HTML display.
412 * There are two major forms of display:
413 * - Sequential or unthreaded ("New Item View" or search results)
414 * - conversation view
415 * The $mode parameter decides between the various renderings and also
416 * figures out how to determine page owner and other contextual items
417 * that are based on unique features of the calling module.
418 * @param array $items
421 * @param bool $preview
422 * @param string $order
425 * @throws ImagickException
426 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
428 public function create(array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
430 $this->profiler->startRecording('rendering');
432 $this->page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
433 $this->page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
434 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
435 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
437 $ssl_state = (local_user() ? true : false);
439 $live_update_div = '';
441 $blocklist = $this->getBlocklist();
443 $previewing = (($preview) ? ' preview ' : '');
445 if ($mode === 'network') {
446 $items = $this->addChildren($items, false, $order, $uid);
449 * The special div is needed for liveUpdate to kick in for this page.
450 * We only launch liveUpdate if you aren't filtering in some incompatible
451 * way and also you aren't writing a comment (discovered in javascript).
453 $live_update_div = '<div id="live-network"></div>' . "\r\n"
454 . "<script> var profile_uid = " . $_SESSION['uid']
455 . "; var netargs = '" . substr($this->args->getCommand(), 8)
457 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
458 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
459 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
460 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
461 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
462 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
463 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
464 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
465 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
466 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
467 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
469 . "'; </script>\r\n";
471 } elseif ($mode === 'profile') {
472 $items = $this->addChildren($items, false, $order, $uid);
475 $tab = !empty($_GET['tab']) ? trim($_GET['tab']) : 'posts';
477 if ($tab === 'posts') {
479 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
480 * because browser prefetching might change it on us. We have to deliver it with the page.
483 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
484 . "<script> var profile_uid = " . $uid
485 . "; var netargs = '?f='; </script>\r\n";
488 } elseif ($mode === 'notes') {
489 $items = $this->addChildren($items, false, $order, local_user());
492 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
493 . "<script> var profile_uid = " . local_user()
494 . "; var netargs = '/?f='; </script>\r\n";
496 } elseif ($mode === 'display') {
497 $items = $this->addChildren($items, false, $order, $uid);
500 $live_update_div = '<div id="live-display"></div>' . "\r\n"
501 . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
504 } elseif ($mode === 'community') {
505 $items = $this->addChildren($items, true, $order, $uid);
508 $live_update_div = '<div id="live-community"></div>' . "\r\n"
509 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 10)
511 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
512 . "'; </script>\r\n";
514 } elseif ($mode === 'contacts') {
515 $items = $this->addChildren($items, false, $order, $uid);
518 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
519 . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
520 ."/?f='; </script>\r\n";
522 } elseif ($mode === 'search') {
523 $live_update_div = '<div id="live-search"></div>' . "\r\n";
526 $page_dropping = ((local_user() && local_user() == $uid) ? true : false);
529 $_SESSION['return_path'] = $this->args->getQueryString();
532 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
533 Hook::callAll('conversation_start', $cb);
535 $items = $cb['items'];
546 if ($this->pConfig->get(local_user(), 'system', 'hide_dislike')) {
547 unset($conv_responses['dislike']);
550 // array with html for each thread (parent+comments)
554 $page_template = Renderer::getMarkupTemplate("conversation.tpl");
555 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
557 if (!empty($items)) {
558 if (in_array($mode, ['community', 'contacts', 'profile'])) {
561 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
568 if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
571 * "New Item View" on network page or search page results
572 * - just loop through the items and format them minimally for display
575 $tpl = 'search_item.tpl';
579 foreach ($items as $item) {
580 if (in_array($item['uri-id'], $uriids)) {
584 $uriids[] = $item['uri-id'];
586 if (!$this->item->visibleActivity($item)) {
590 if (in_array($item['author-id'], $blocklist)) {
596 // prevent private email from leaking.
597 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
601 $profile_name = $item['author-name'];
602 if (!empty($item['author-link']) && empty($item['author-name'])) {
603 $profile_name = $item['author-link'];
606 $tags = Tag::populateFromItem($item);
608 $author = ['uid' => 0, 'id' => $item['author-id'], 'network' => $item['author-network'], 'url' => $item['author-link']];
609 $profile_link = Contact::magicLinkByContact($author);
612 if (strpos($profile_link, 'redir/') === 0) {
613 $sparkle = ' sparkle';
616 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
617 Hook::callAll('render_location', $locate);
618 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
620 $this->item->localize($item);
621 if ($mode === 'filed') {
628 'dropping' => $dropping,
629 'pagedrop' => $page_dropping,
630 'select' => $this->l10n->t('Select'),
631 'delete' => $this->l10n->t('Delete'),
641 if ($this->pConfig->get(local_user(), 'system', 'hide_dislike')) {
642 unset($likebuttons['dislike']);
645 $body_html = ItemModel::prepareBody($item, true, $preview);
647 [$categories, $folders] = $this->item->determineCategoriesTerms($item, local_user());
649 if (!empty($item['title'])) {
650 $title = $item['title'];
651 } elseif (!empty($item['content-warning']) && $this->pConfig->get(local_user(), 'system', 'disable_cw', false)) {
652 $title = ucfirst($item['content-warning']);
657 if (!empty($item['featured'])) {
658 $pinned = $this->l10n->t('Pinned item');
663 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
664 $owner_avatar = $author_avatar = $item['contact-id'];
665 $owner_updated = $author_updated = '';
666 $owner_thumb = $author_thumb = $item['contact-avatar'];
668 $owner_avatar = $item['owner-id'];
669 $owner_updated = $item['owner-updated'];
670 $owner_thumb = $item['owner-avatar'];
671 $author_avatar = $item['author-id'];
672 $author_updated = $item['author-updated'];
673 $author_thumb = $item['author-avatar'];
676 if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) {
677 $owner_thumb = Contact::getAvatarUrlForId($owner_avatar, Proxy::SIZE_THUMB, $owner_updated);
680 if (empty($author_thumb) || Photo::isPhotoURI($author_thumb)) {
681 $author_thumb = Contact::getAvatarUrlForId($author_avatar, Proxy::SIZE_THUMB, $author_updated);
686 'id' => ($preview ? 'P0' : $item['id']),
687 'guid' => ($preview ? 'Q0' : $item['guid']),
688 'commented' => $item['commented'],
689 'received' => $item['received'],
690 'created_date' => $item['created'],
691 'uriid' => $item['uri-id'],
692 'network' => $item['network'],
693 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
694 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
695 'linktitle' => $this->l10n->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
696 'profile_url' => $profile_link,
697 'item_photo_menu_html' => $this->item->photoMenu($item, $formSecurityToken),
698 'name' => $profile_name,
699 'sparkle' => $sparkle,
701 'thumb' => $this->baseURL->remove($author_thumb),
703 'body_html' => $body_html,
704 'tags' => $tags['tags'],
705 'hashtags' => $tags['hashtags'],
706 'mentions' => $tags['mentions'],
707 'implicit_mentions' => $tags['implicit_mentions'],
708 'txt_cats' => $this->l10n->t('Categories:'),
709 'txt_folders' => $this->l10n->t('Filed under:'),
710 'has_cats' => ((count($categories)) ? 'true' : ''),
711 'has_folders' => ((count($folders)) ? 'true' : ''),
712 'categories' => $categories,
713 'folders' => $folders,
714 'text' => strip_tags($body_html),
715 'localtime' => DateTimeFormat::local($item['created'], 'r'),
716 'utc' => DateTimeFormat::utc($item['created'], 'c'),
717 'ago' => (($item['app']) ? $this->l10n->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
718 'location_html' => $location_html,
722 'owner_photo' => $this->baseURL->remove($owner_thumb),
723 'plink' => ItemModel::getPlink($item),
726 'isstarred' => 'unstarred',
729 'vote' => $likebuttons,
731 'dislike_html ' => '',
732 'comment_html' => '',
733 'conv' => ($preview ? '' : ['href' => 'display/' . $item['guid'], 'title' => $this->l10n->t('View in context')]),
734 'previewing' => $previewing,
735 'wait' => $this->l10n->t('Please wait'),
739 $arr = ['item' => $item, 'output' => $tmp_item];
740 Hook::callAll('display_item', $arr);
742 $threads[$threadsid]['id'] = $item['id'];
743 $threads[$threadsid]['network'] = $item['network'];
744 $threads[$threadsid]['items'] = [$arr['output']];
748 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
750 $conv = new Thread($mode, $preview, $writable);
753 * get all the topmost parents
754 * this shouldn't be needed, as we should have only them in our array
755 * But for now, this array respects the old style, just in case
757 foreach ($items as $item) {
758 if (in_array($item['author-id'], $blocklist)) {
762 // Can we put this after the visibility check?
763 $this->builtinActivityPuller($item, $conv_responses);
765 // Only add what is visible
766 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
770 if (!$this->item->visibleActivity($item)) {
774 /// @todo Check if this call is needed or not
775 $arr = ['item' => $item];
776 Hook::callAll('display_item', $arr);
778 $item['pagedrop'] = $page_dropping;
780 if ($item['gravity'] == GRAVITY_PARENT) {
781 $item_object = new PostObject($item);
782 $conv->addParent($item_object);
786 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
788 $this->logger->info('[ERROR] conversation : Failed to get template data.');
794 $o = Renderer::replaceMacros($page_template, [
795 '$baseurl' => $this->baseURL->get($ssl_state),
796 '$return_path' => $this->args->getQueryString(),
797 '$live_update' => $live_update_div,
798 '$remove' => $this->l10n->t('remove'),
800 '$update' => $update,
801 '$threads' => $threads,
802 '$dropping' => ($page_dropping ? $this->l10n->t('Delete Selected Items') : false),
805 $this->profiler->stopRecording();
809 private function getBlocklist()
815 $str_blocked = str_replace(["\n", "\r"], ",", $this->pConfig->get(local_user(), 'system', 'blocked'));
816 if (empty($str_blocked)) {
822 foreach (explode(',', $str_blocked) as $entry) {
823 $cid = Contact::getIdForURL(trim($entry), 0, false);
833 * Adds some information (Causer, post reason, direction) to the fetched post row.
835 * @param array $row Post row
836 * @param array $activity Contact data of the resharer
837 * @param array $thr_parent Thread parent row
839 * @return array items with parents and comments
841 private function addRowInformation(array $row, array $activity, array $thr_parent)
843 $this->profiler->startRecording('rendering');
845 if ($row['uid'] == 0) {
846 $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
849 if (!empty($activity)) {
850 if (($row['gravity'] == GRAVITY_PARENT)) {
851 $row['post-reason'] = ItemModel::PR_ANNOUNCEMENT;
853 $row = array_merge($row, $activity);
854 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
856 $row['causer-link'] = $contact['url'];
857 $row['causer-avatar'] = $contact['thumb'];
858 $row['causer-name'] = $contact['name'];
859 } elseif (($row['gravity'] == GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
860 ($row['author-id'] == $activity['causer-id'])) {
865 switch ($row['post-reason']) {
866 case ItemModel::PR_TO:
867 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'to')];
869 case ItemModel::PR_CC:
870 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'cc')];
872 case ItemModel::PR_BTO:
873 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bto')];
875 case ItemModel::PR_BCC:
876 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bcc')];
878 case ItemModel::PR_FOLLOWER:
879 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('You are following %s.', $row['author-name'])];
881 case ItemModel::PR_TAG:
882 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('Tagged')];
884 case ItemModel::PR_ANNOUNCEMENT:
885 if (!empty($row['causer-id']) && $this->pConfig->get(local_user(), 'system', 'display_resharer')) {
886 $row['owner-id'] = $row['causer-id'];
887 $row['owner-link'] = $row['causer-link'];
888 $row['owner-avatar'] = $row['causer-avatar'];
889 $row['owner-name'] = $row['causer-name'];
892 if (in_array($row['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) && !empty($row['causer-id'])) {
893 $causer = ['uid' => 0, 'id' => $row['causer-id'], 'network' => $row['causer-network'], 'url' => $row['causer-link']];
895 $row['reshared'] = $this->l10n->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
897 $row['direction'] = ['direction' => 3, 'title' => (empty($row['causer-id']) ? $this->l10n->t('Reshared') : $this->l10n->t('Reshared by %s <%s>', $row['causer-name'], $row['causer-link']))];
899 case ItemModel::PR_COMMENT:
900 $row['direction'] = ['direction' => 5, 'title' => $this->l10n->t('%s is participating in this thread.', $row['author-name'])];
902 case ItemModel::PR_STORED:
903 $row['direction'] = ['direction' => 8, 'title' => $this->l10n->t('Stored')];
905 case ItemModel::PR_GLOBAL:
906 $row['direction'] = ['direction' => 9, 'title' => $this->l10n->t('Global')];
908 case ItemModel::PR_RELAY:
909 $row['direction'] = ['direction' => 10, 'title' => (empty($row['causer-id']) ? $this->l10n->t('Relayed') : $this->l10n->t('Relayed by %s <%s>', $row['causer-name'], $row['causer-link']))];
911 case ItemModel::PR_FETCHED:
912 $row['direction'] = ['direction' => 2, 'title' => (empty($row['causer-id']) ? $this->l10n->t('Fetched') : $this->l10n->t('Fetched because of %s <%s>', $row['causer-name'], $row['causer-link']))];
916 $row['thr-parent-row'] = $thr_parent;
918 $this->profiler->stopRecording();
923 * Add comments to top level entries that had been fetched before
925 * The system will fetch the comments for the local user whenever possible.
926 * This behaviour is currently needed to allow commenting on Friendica posts.
928 * @param array $parents Parent items
930 * @param $block_authors
933 * @return array items with parents and comments
934 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
936 private function addChildren(array $parents, $block_authors, $order, $uid)
938 $this->profiler->startRecording('rendering');
939 if (count($parents) > 1) {
940 $max_comments = $this->config->get('system', 'max_comments', 100);
942 $max_comments = $this->config->get('system', 'max_display_comments', 1000);
947 $commentcounter = [];
948 $activitycounter = [];
950 foreach ($parents as $parent) {
951 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == GRAVITY_ACTIVITY)) {
952 $uriid = $parent['thr-parent-id'];
953 if (!empty($parent['author-id'])) {
954 $activities[$uriid] = ['causer-id' => $parent['author-id']];
955 foreach (['commented', 'received', 'created'] as $orderfields) {
956 if (!empty($parent[$orderfields])) {
957 $activities[$uriid][$orderfields] = $parent[$orderfields];
962 $uriid = $parent['uri-id'];
966 $commentcounter[$uriid] = 0;
967 $activitycounter[$uriid] = 0;
970 $condition = ['parent-uri-id' => $uriids];
971 if ($block_authors) {
972 $condition['author-hidden'] = false;
975 $condition = DBA::mergeConditions($condition,
976 ["`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW)]);
978 $thread_parents = Post::select(['uri-id', 'causer-id'], $condition, ['order' => ['uri-id' => false, 'uid' => true]]);
982 while ($row = Post::fetch($thread_parents)) {
983 $thr_parent[$row['uri-id']] = $row;
985 DBA::close($thread_parents);
987 $params = ['order' => ['uri-id' => true, 'uid' => true]];
989 $thread_items = Post::selectForUser($uid, array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
993 while ($row = Post::fetch($thread_items)) {
994 if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
998 if ($max_comments > 0) {
999 if (($row['gravity'] == GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
1002 if (($row['gravity'] == GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
1007 $items[$row['uri-id']] = $this->addRowInformation($row, $activities[$row['uri-id']] ?? [], $thr_parent[$row['thr-parent-id']] ?? []);
1010 DBA::close($thread_items);
1012 $items = $this->convSort($items, $order);
1014 $this->profiler->stopRecording();
1019 * Plucks the children of the given parent from a given item list.
1021 * @param array $item_list
1022 * @param array $parent
1023 * @param bool $recursive
1026 private function getItemChildren(array &$item_list, array $parent, $recursive = true)
1028 $this->profiler->startRecording('rendering');
1030 foreach ($item_list as $i => $item) {
1031 if ($item['gravity'] != GRAVITY_PARENT) {
1033 // Fallback to parent-uri if thr-parent is not set
1034 $thr_parent = $item['thr-parent-id'];
1035 if ($thr_parent == '') {
1036 $thr_parent = $item['parent-uri-id'];
1039 if ($thr_parent == $parent['uri-id']) {
1040 $item['children'] = $this->getItemChildren($item_list, $item);
1042 $children[] = $item;
1043 unset($item_list[$i]);
1045 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1046 $children[] = $item;
1047 unset($item_list[$i]);
1051 $this->profiler->stopRecording();
1056 * Recursively sorts a tree-like item array
1058 * @param array $items
1061 private function sortItemChildren(array $items)
1063 $this->profiler->startRecording('rendering');
1065 usort($result, [$this, 'sortThrReceivedRev']);
1066 foreach ($result as $k => $i) {
1067 if (isset($result[$k]['children'])) {
1068 $result[$k]['children'] = $this->sortItemChildren($result[$k]['children']);
1071 $this->profiler->stopRecording();
1076 * Recursively add all children items at the top level of a list
1078 * @param array $children List of items to append
1079 * @param array $item_list
1081 private function addChildrenToList(array $children, array &$item_list)
1083 foreach ($children as $child) {
1084 $item_list[] = $child;
1085 if (isset($child['children'])) {
1086 $this->addChildrenToList($child['children'], $item_list);
1092 * Selectively flattens a tree-like item structure to prevent threading stairs
1094 * This recursive function takes the item tree structure created by conv_sort() and
1095 * flatten the extraneous depth levels when people reply sequentially, removing the
1096 * stairs effect in threaded conversations limiting the available content width.
1098 * The basic principle is the following: if a post item has only one reply and is
1099 * the last reply of its parent, then the reply is moved to the parent.
1101 * This process is rendered somewhat more complicated because items can be either
1102 * replies or likes, and these don't factor at all in the reply count/last reply.
1104 * @param array $parent A tree-like array of items
1107 private function smartFlattenConversation(array $parent)
1109 $this->profiler->startRecording('rendering');
1110 if (!isset($parent['children']) || count($parent['children']) == 0) {
1111 $this->profiler->stopRecording();
1115 // We use a for loop to ensure we process the newly-moved items
1116 for ($i = 0; $i < count($parent['children']); $i++) {
1117 $child = $parent['children'][$i];
1119 if (isset($child['children']) && count($child['children'])) {
1120 // This helps counting only the regular posts
1121 $count_post_closure = function ($var) {
1122 $this->profiler->stopRecording();
1123 return $var['verb'] === Activity::POST;
1126 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1128 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1130 // If there's only one child's children post and this is the last child post
1131 if ($child_post_count == 1 && $remaining_post_count == 1) {
1133 // Searches the post item in the children
1135 while ($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1139 $moved_item = $child['children'][$j];
1140 unset($parent['children'][$i]['children'][$j]);
1141 $parent['children'][] = $moved_item;
1143 $parent['children'][$i] = $this->smartFlattenConversation($child);
1148 $this->profiler->stopRecording();
1153 * Expands a flat list of items into corresponding tree-like conversation structures.
1155 * sort the top-level posts either on "received" or "commented", and finally
1156 * append all the items at the top level (???)
1158 * @param array $item_list A list of items belonging to one or more conversations
1159 * @param string $order Either on "received" or "commented"
1161 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1163 private function convSort(array $item_list, $order)
1165 $this->profiler->startRecording('rendering');
1168 if (!(is_array($item_list) && count($item_list))) {
1169 $this->profiler->stopRecording();
1173 $blocklist = $this->getBlocklist();
1177 // Dedupes the item list on the uri to prevent infinite loops
1178 foreach ($item_list as $item) {
1179 if (in_array($item['author-id'], $blocklist)) {
1183 $item_array[$item['uri-id']] = $item;
1186 // Extract the top level items
1187 foreach ($item_array as $item) {
1188 if ($item['gravity'] == GRAVITY_PARENT) {
1193 if (stristr($order, 'pinned_received')) {
1194 usort($parents, [$this, 'sortThrFeaturedReceived']);
1195 } elseif (stristr($order, 'pinned_commented')) {
1196 usort($parents, [$this, 'sortThrFeaturedCommented']);
1197 } elseif (stristr($order, 'received')) {
1198 usort($parents, [$this, 'sortThrReceived']);
1199 } elseif (stristr($order, 'commented')) {
1200 usort($parents, [$this, 'sortThrCommented']);
1201 } elseif (stristr($order, 'created')) {
1202 usort($parents, [$this, 'sortThrCreated']);
1206 * Plucks children from the item_array, second pass collects eventual orphan
1207 * items and add them as children of their top-level post.
1209 foreach ($parents as $i => $parent) {
1210 $parents[$i]['children'] = array_merge($this->getItemChildren($item_array, $parent, true),
1211 $this->getItemChildren($item_array, $parent, false));
1214 foreach ($parents as $i => $parent) {
1215 $parents[$i]['children'] = $this->sortItemChildren($parents[$i]['children']);
1218 if (!$this->pConfig->get(local_user(), 'system', 'no_smart_threading', 0)) {
1219 foreach ($parents as $i => $parent) {
1220 $parents[$i] = $this->smartFlattenConversation($parent);
1224 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1225 /// However, this apparently ensures responses (likes, attendance) display (?!)
1226 foreach ($parents as $parent) {
1227 if (count($parent['children'])) {
1228 $this->addChildrenToList($parent['children'], $parents);
1232 $this->profiler->stopRecording();
1237 * usort() callback to sort item arrays by featured and the received key
1243 private function sortThrFeaturedReceived(array $a, array $b)
1245 if ($b['featured'] && !$a['featured']) {
1247 } elseif (!$b['featured'] && $a['featured']) {
1251 return strcmp($b['received'], $a['received']);
1255 * usort() callback to sort item arrays by featured and the received key
1261 private function sortThrFeaturedCommented(array $a, array $b)
1263 if ($b['featured'] && !$a['featured']) {
1265 } elseif (!$b['featured'] && $a['featured']) {
1269 return strcmp($b['commented'], $a['commented']);
1273 * usort() callback to sort item arrays by the received key
1279 private function sortThrReceived(array $a, array $b)
1281 return strcmp($b['received'], $a['received']);
1285 * usort() callback to reverse sort item arrays by the received key
1291 private function sortThrReceivedRev(array $a, array $b)
1293 return strcmp($a['received'], $b['received']);
1297 * usort() callback to sort item arrays by the commented key
1303 private function sortThrCommented(array $a, array $b)
1305 return strcmp($b['commented'], $a['commented']);
1309 * usort() callback to sort item arrays by the created key
1315 private function sortThrCreated(array $a, array $b)
1317 return strcmp($b['created'], $a['created']);