3 * @copyright Copyright (C) 2010-2021, 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/>.
23 use Friendica\BaseModule;
24 use Friendica\Content\ContactSelector;
25 use Friendica\Content\Feature;
26 use Friendica\Core\ACL;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Session;
32 use Friendica\Core\Theme;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Item;
37 use Friendica\Model\Post;
38 use Friendica\Model\Tag;
39 use Friendica\Model\User;
40 use Friendica\Model\Verb;
41 use Friendica\Object\Post as PostObject;
42 use Friendica\Object\Thread;
43 use Friendica\Protocol\Activity;
44 use Friendica\Util\Crypto;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
48 use Friendica\Util\Temporal;
49 use Friendica\Util\XML;
52 * Render actions localized
55 * @throws ImagickException
56 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
58 function localize_item(&$item)
60 DI::profiler()->startRecording('rendering');
61 /// @todo The following functionality needs to be cleaned up.
62 if (!empty($item['verb'])) {
63 $activity = DI::activity();
65 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
67 if (stristr($item['verb'], Activity::POKE)) {
68 $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
70 DI::profiler()->stopRecording();
73 if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
74 DI::profiler()->stopRecording();
78 $obj = XML::parseString($xmlhead . $item['object']);
84 foreach ($obj->link as $l) {
85 $atts = $l->attributes();
86 switch ($atts['rel']) {
87 case "alternate": $Blink = $atts['href'];
88 case "photo": $Bphoto = $atts['href'];
92 $author = ['uid' => 0, 'id' => $item['author-id'],
93 'network' => $item['author-network'], 'url' => $item['author-link']];
94 $A = '[url=' . Contact::magicLinkByContact($author) . ']' . $item['author-name'] . '[/url]';
97 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
102 if ($Bphoto != "" && !empty($Blink)) {
103 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
107 * we can't have a translation string with three positions but no distinguishable text
108 * So here is the translate string.
110 $txt = DI::l10n()->t('%1$s poked %2$s');
112 // now translate the verb
113 $poked_t = trim(sprintf($txt, '', ''));
114 $txt = str_replace($poked_t, DI::l10n()->t($verb), $txt);
116 // then do the sprintf on the translation string
118 $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
122 if ($activity->match($item['verb'], Activity::TAG)) {
123 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
124 'verb', 'object-type', 'resource-id', 'body', 'plink'];
125 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
126 if (!DBA::isResult($obj)) {
127 DI::profiler()->stopRecording();
131 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
132 'network' => $item['author-network'], 'url' => $item['author-link']];
133 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
135 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
136 'network' => $obj['author-network'], 'url' => $obj['author-link']];
137 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
139 switch ($obj['verb']) {
141 switch ($obj['object-type']) {
142 case Activity\ObjectType::EVENT:
143 $post_type = DI::l10n()->t('event');
146 $post_type = DI::l10n()->t('status');
150 if ($obj['resource-id']) {
151 $post_type = DI::l10n()->t('photo');
152 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
153 $rr['plink'] = $m[1];
155 $post_type = DI::l10n()->t('status');
157 // Let's break everthing ... ;-)
160 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
162 $parsedobj = XML::parseString($xmlhead . $item['object']);
164 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
165 $item['body'] = DI::l10n()->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
170 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
171 foreach ($matches as $mtch) {
172 if (!strpos($mtch[1], 'zrl=')) {
173 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
178 // add sparkle links to appropriate permalinks
179 // Only create a redirection to a magic link when logged in
180 if (!empty($item['plink']) && Session::isAuthenticated()) {
181 $author = ['uid' => 0, 'id' => $item['author-id'],
182 'network' => $item['author-network'], 'url' => $item['author-link']];
183 $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
185 DI::profiler()->stopRecording();
189 * Count the total of comments on this item and its desendants
190 * @TODO proper type-hint + doc-tag
194 function count_descendants($item) {
195 $total = count($item['children']);
198 foreach ($item['children'] as $child) {
199 if (!visible_activity($child)) {
202 $total += count_descendants($child);
209 function visible_activity($item) {
211 $activity = DI::activity();
213 if (empty($item['verb']) || $activity->isHidden($item['verb'])) {
217 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
218 if ($activity->match($item['verb'], Activity::FOLLOW) &&
219 $item['object-type'] === Activity\ObjectType::NOTE &&
220 empty($item['self']) &&
221 $item['uid'] == local_user()) {
228 function conv_get_blocklist()
234 $str_blocked = str_replace(["\n", "\r"], ",", DI::pConfig()->get(local_user(), 'system', 'blocked'));
235 if (empty($str_blocked)) {
241 foreach (explode(',', $str_blocked) as $entry) {
242 $cid = Contact::getIdForURL(trim($entry), 0, false);
252 * "Render" a conversation or list of items for HTML display.
253 * There are two major forms of display:
254 * - Sequential or unthreaded ("New Item View" or search results)
255 * - conversation view
256 * The $mode parameter decides between the various renderings and also
257 * figures out how to determine page owner and other contextual items
258 * that are based on unique features of the calling module.
260 * @param array $items
263 * @param bool $preview
264 * @param string $order
267 * @throws ImagickException
268 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
270 function conversation(App $a, array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
272 DI::profiler()->startRecording('rendering');
275 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
276 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
277 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
278 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
280 $ssl_state = (local_user() ? true : false);
282 $live_update_div = '';
284 $blocklist = conv_get_blocklist();
286 $previewing = (($preview) ? ' preview ' : '');
288 if ($mode === 'network') {
289 $items = conversation_add_children($items, false, $order, $uid);
292 * The special div is needed for liveUpdate to kick in for this page.
293 * We only launch liveUpdate if you aren't filtering in some incompatible
294 * way and also you aren't writing a comment (discovered in javascript).
296 $live_update_div = '<div id="live-network"></div>' . "\r\n"
297 . "<script> var profile_uid = " . $_SESSION['uid']
298 . "; var netargs = '" . substr(DI::args()->getCommand(), 8)
300 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
301 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
302 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
303 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
304 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
305 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
306 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
307 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
308 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
309 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
310 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
312 . "'; </script>\r\n";
314 } elseif ($mode === 'profile') {
315 $items = conversation_add_children($items, false, $order, $uid);
319 if (!empty($_GET['tab'])) {
320 $tab = Strings::escapeTags(trim($_GET['tab']));
322 if ($tab === 'posts') {
324 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
325 * because browser prefetching might change it on us. We have to deliver it with the page.
328 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
329 . "<script> var profile_uid = " . $uid
330 . "; var netargs = '?f='; </script>\r\n";
333 } elseif ($mode === 'notes') {
334 $items = conversation_add_children($items, false, $order, local_user());
337 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
338 . "<script> var profile_uid = " . local_user()
339 . "; var netargs = '/?f='; </script>\r\n";
341 } elseif ($mode === 'display') {
342 $items = conversation_add_children($items, false, $order, $uid);
345 $live_update_div = '<div id="live-display"></div>' . "\r\n"
346 . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
349 } elseif ($mode === 'community') {
350 $items = conversation_add_children($items, true, $order, $uid);
353 $live_update_div = '<div id="live-community"></div>' . "\r\n"
354 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 10)
356 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
357 . "'; </script>\r\n";
359 } elseif ($mode === 'contacts') {
360 $items = conversation_add_children($items, false, $order, $uid);
363 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
364 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 8)
365 ."/?f='; </script>\r\n";
367 } elseif ($mode === 'search') {
368 $live_update_div = '<div id="live-search"></div>' . "\r\n";
371 $page_dropping = ((local_user() && local_user() == $uid) ? true : false);
374 $_SESSION['return_path'] = DI::args()->getQueryString();
377 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
378 Hook::callAll('conversation_start', $cb);
380 $items = $cb['items'];
391 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
392 unset($conv_responses['dislike']);
395 // array with html for each thread (parent+comments)
399 $page_template = Renderer::getMarkupTemplate("conversation.tpl");
400 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
402 if (!empty($items)) {
403 if (in_array($mode, ['community', 'contacts'])) {
406 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
413 if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
416 * "New Item View" on network page or search page results
417 * - just loop through the items and format them minimally for display
420 $tpl = 'search_item.tpl';
424 foreach ($items as $item) {
425 if (in_array($item['uri-id'], $uriids)) {
429 $uriids[] = $item['uri-id'];
431 if (!visible_activity($item)) {
435 if (in_array($item['author-id'], $blocklist)) {
441 // prevent private email from leaking.
442 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
446 $profile_name = $item['author-name'];
447 if (!empty($item['author-link']) && empty($item['author-name'])) {
448 $profile_name = $item['author-link'];
451 $tags = Tag::populateFromItem($item);
453 $author = ['uid' => 0, 'id' => $item['author-id'],
454 'network' => $item['author-network'], 'url' => $item['author-link']];
455 $profile_link = Contact::magicLinkByContact($author);
458 if (strpos($profile_link, 'redir/') === 0) {
459 $sparkle = ' sparkle';
462 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
463 Hook::callAll('render_location', $locate);
464 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
466 localize_item($item);
467 if ($mode === 'filed') {
474 'dropping' => $dropping,
475 'pagedrop' => $page_dropping,
476 'select' => DI::l10n()->t('Select'),
477 'delete' => DI::l10n()->t('Delete'),
487 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
488 unset($likebuttons['dislike']);
491 $body_html = Item::prepareBody($item, true, $preview);
493 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item, local_user());
495 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
496 $title = ucfirst($item['content-warning']);
498 $title = $item['title'];
503 'id' => ($preview ? 'P0' : $item['id']),
504 'guid' => ($preview ? 'Q0' : $item['guid']),
505 'commented' => $item['commented'],
506 'received' => $item['received'],
507 'created_date' => $item['created'],
508 'uriid' => $item['uri-id'],
509 'network' => $item['network'],
510 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
511 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link']),
512 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
513 'profile_url' => $profile_link,
514 'item_photo_menu_html' => item_photo_menu($item, $formSecurityToken),
515 'name' => $profile_name,
516 'sparkle' => $sparkle,
518 'thumb' => DI::baseUrl()->remove(Contact::getAvatarUrlForUrl($item['author-link'], $item['uid'], Proxy::SIZE_THUMB)),
520 'body_html' => $body_html,
521 'tags' => $tags['tags'],
522 'hashtags' => $tags['hashtags'],
523 'mentions' => $tags['mentions'],
524 'implicit_mentions' => $tags['implicit_mentions'],
525 'txt_cats' => DI::l10n()->t('Categories:'),
526 'txt_folders' => DI::l10n()->t('Filed under:'),
527 'has_cats' => ((count($categories)) ? 'true' : ''),
528 'has_folders' => ((count($folders)) ? 'true' : ''),
529 'categories' => $categories,
530 'folders' => $folders,
531 'text' => strip_tags($body_html),
532 'localtime' => DateTimeFormat::local($item['created'], 'r'),
533 'ago' => (($item['app']) ? DI::l10n()->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
534 'location_html' => $location_html,
538 'owner_photo' => DI::baseUrl()->remove(Contact::getAvatarUrlForUrl($item['owner-link'], $item['uid'], Proxy::SIZE_THUMB)),
539 'plink' => Item::getPlink($item),
541 'isstarred' => 'unstarred',
544 'vote' => $likebuttons,
546 'dislike_html' => '',
547 'comment_html' => '',
548 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> DI::l10n()->t('View in context')]),
549 'previewing' => $previewing,
550 'wait' => DI::l10n()->t('Please wait'),
554 $arr = ['item' => $item, 'output' => $tmp_item];
555 Hook::callAll('display_item', $arr);
557 $threads[$threadsid]['id'] = $item['id'];
558 $threads[$threadsid]['network'] = $item['network'];
559 $threads[$threadsid]['items'] = [$arr['output']];
564 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
566 $conv = new Thread($mode, $preview, $writable);
569 * get all the topmost parents
570 * this shouldn't be needed, as we should have only them in our array
571 * But for now, this array respects the old style, just in case
573 foreach ($items as $item) {
574 if (in_array($item['author-id'], $blocklist)) {
578 // Can we put this after the visibility check?
579 builtin_activity_puller($item, $conv_responses);
581 // Only add what is visible
582 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
586 if (!visible_activity($item)) {
590 /// @todo Check if this call is needed or not
591 $arr = ['item' => $item];
592 Hook::callAll('display_item', $arr);
594 $item['pagedrop'] = $page_dropping;
596 if ($item['gravity'] == GRAVITY_PARENT) {
597 $item_object = new PostObject($item);
598 $conv->addParent($item_object);
602 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
604 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
610 $o = Renderer::replaceMacros($page_template, [
611 '$baseurl' => DI::baseUrl()->get($ssl_state),
612 '$return_path' => DI::args()->getQueryString(),
613 '$live_update' => $live_update_div,
614 '$remove' => DI::l10n()->t('remove'),
616 '$update' => $update,
617 '$threads' => $threads,
618 '$dropping' => ($page_dropping ? DI::l10n()->t('Delete Selected Items') : False),
621 DI::profiler()->stopRecording();
626 * Adds some information (Causer, post reason, direction) to the fetched post row.
628 * @param array $row Post row
629 * @param array $activity Contact data of the resharer
631 * @return array items with parents and comments
633 function conversation_add_row_information(array $row, array $activity) {
634 DI::profiler()->startRecording('rendering');
636 if ($row['uid'] == 0) {
637 $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
640 if (!empty($activity)) {
641 if (($row['gravity'] == GRAVITY_PARENT)) {
642 $row['post-reason'] = Item::PR_ANNOUNCEMENT;
643 $row = array_merge($row, $activity);
644 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
645 $row['causer-link'] = $contact['url'];
646 $row['causer-avatar'] = $contact['thumb'];
647 $row['causer-name'] = $contact['name'];
648 } elseif (($row['gravity'] == GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
649 ($row['author-id'] == $activity['causer-id'])) {
654 switch ($row['post-reason']) {
656 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'to')];
659 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'cc')];
662 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bto')];
665 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bcc')];
667 case Item::PR_FOLLOWER:
668 $row['direction'] = ['direction' => 6, 'title' => DI::l10n()->t('You are following %s.', $row['author-name'])];
671 $row['direction'] = ['direction' => 4, 'title' => DI::l10n()->t('Tagged')];
673 case Item::PR_ANNOUNCEMENT:
674 if (!empty($row['causer-id']) && DI::pConfig()->get(local_user(), 'system', 'display_resharer')) {
675 $row['owner-id'] = $row['causer-id'];
676 $row['owner-link'] = $row['causer-link'];
677 $row['owner-avatar'] = $row['causer-avatar'];
678 $row['owner-name'] = $row['causer-name'];
681 if (($row['gravity'] == GRAVITY_PARENT) && !empty($row['causer-id'])) {
682 $causer = ['uid' => 0, 'id' => $row['causer-id'],
683 'network' => $row['causer-network'], 'url' => $row['causer-link']];
684 $row['reshared'] = DI::l10n()->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
686 $row['direction'] = ['direction' => 3, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Reshared') : DI::l10n()->t('Reshared by %s <%s>', $row['causer-name'], $row['causer-link']))];
688 case Item::PR_COMMENT:
689 $row['direction'] = ['direction' => 5, 'title' => DI::l10n()->t('%s is participating in this thread.', $row['author-name'])];
691 case Item::PR_STORED:
692 $row['direction'] = ['direction' => 8, 'title' => DI::l10n()->t('Stored')];
694 case Item::PR_GLOBAL:
695 $row['direction'] = ['direction' => 9, 'title' => DI::l10n()->t('Global')];
698 $row['direction'] = ['direction' => 10, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Relayed') : DI::l10n()->t('Relayed by %s <%s>', $row['causer-name'], $row['causer-link']))];
700 case Item::PR_FETCHED:
701 $row['direction'] = ['direction' => 2, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Fetched') : DI::l10n()->t('Fetched because of %s <%s>', $row['causer-name'], $row['causer-link']))];
705 DI::profiler()->stopRecording();
710 * Add comments to top level entries that had been fetched before
712 * The system will fetch the comments for the local user whenever possible.
713 * This behaviour is currently needed to allow commenting on Friendica posts.
715 * @param array $parents Parent items
717 * @param $block_authors
720 * @return array items with parents and comments
721 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
723 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
724 DI::profiler()->startRecording('rendering');
725 if (count($parents) > 1) {
726 $max_comments = DI::config()->get('system', 'max_comments', 100);
728 $max_comments = DI::config()->get('system', 'max_display_comments', 1000);
731 $params = ['order' => ['uri-id' => true, 'uid' => true]];
735 $commentcounter = [];
736 $activitycounter = [];
738 foreach ($parents AS $parent) {
739 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == GRAVITY_ACTIVITY)) {
740 $uriid = $parent['thr-parent-id'];
741 if (!empty($parent['author-id'])) {
742 $activities[$uriid] = ['causer-id' => $parent['author-id']];
743 foreach (['commented', 'received', 'created'] as $orderfields) {
744 if (!empty($parent[$orderfields])) {
745 $activities[$uriid][$orderfields] = $parent[$orderfields];
750 $uriid = $parent['uri-id'];
754 $commentcounter[$uriid] = 0;
755 $activitycounter[$uriid] = 0;
758 $condition = ['parent-uri-id' => $uriids];
759 if ($block_authors) {
760 $condition['author-hidden'] = false;
763 $condition = DBA::mergeConditions($condition,
764 ["`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW)]);
766 $thread_items = Post::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['pinned', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
770 while ($row = Post::fetch($thread_items)) {
771 if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
775 if ($max_comments > 0) {
776 if (($row['gravity'] == GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
779 if (($row['gravity'] == GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
783 $items[$row['uri-id']] = conversation_add_row_information($row, $activities[$row['uri-id']] ?? []);
786 DBA::close($thread_items);
788 $items = conv_sort($items, $order);
790 DI::profiler()->stopRecording();
794 function item_photo_menu($item, string $formSecurityToken)
796 DI::profiler()->startRecording('rendering');
807 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
808 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
811 $author = ['uid' => 0, 'id' => $item['author-id'],
812 'network' => $item['author-network'], 'url' => $item['author-link']];
813 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
814 $sparkle = (strpos($profile_link, 'redir/') === 0);
817 $pcid = $item['author-id'];
820 $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
821 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
822 if (DBA::isResult($contact)) {
823 $cid = $contact['id'];
824 $network = $contact['network'];
825 $rel = $contact['rel'];
829 $status_link = $profile_link . '/status';
830 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
831 $profile_link = $profile_link . '/profile';
835 $contact_url = 'contact/' . $pcid;
836 $posts_link = $contact_url . '/posts';
837 $block_link = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
838 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
841 if ($cid && !$item['self']) {
842 $contact_url = 'contact/' . $cid;
843 $poke_link = $contact_url . '/poke';
844 $posts_link = $contact_url . '/posts';
846 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
847 $pm_url = 'message/new/' . $cid;
853 DI::l10n()->t('Follow Thread') => $sub_link,
854 DI::l10n()->t('View Status') => $status_link,
855 DI::l10n()->t('View Profile') => $profile_link,
856 DI::l10n()->t('View Photos') => $photos_link,
857 DI::l10n()->t('Network Posts') => $posts_link,
858 DI::l10n()->t('View Contact') => $contact_url,
859 DI::l10n()->t('Send PM') => $pm_url,
860 DI::l10n()->t('Block') => $block_link,
861 DI::l10n()->t('Ignore') => $ignore_link
864 if (!empty($item['language'])) {
865 $menu[DI::l10n()->t('Languages')] = 'javascript:alert(\'' . Item::getLanguageMessage($item) . '\');';
868 if ($network == Protocol::DFRN) {
869 $menu[DI::l10n()->t("Poke")] = $poke_link;
872 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
873 in_array($item['network'], Protocol::FEDERATED)) {
874 $menu[DI::l10n()->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
877 $menu = [DI::l10n()->t('View Profile') => $item['author-link']];
880 $args = ['item' => $item, 'menu' => $menu];
882 Hook::callAll('item_photo_menu', $args);
884 $menu = $args['menu'];
887 foreach ($menu as $k => $v) {
888 if (strpos($v, 'javascript:') === 0) {
890 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
892 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
895 DI::profiler()->stopRecording();
900 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
902 * Increments the count of each matching activity and adds a link to the author as needed.
904 * @param array $activity
905 * @param array &$conv_responses (already created with builtin activity structure)
907 * @throws ImagickException
908 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
910 function builtin_activity_puller(array $activity, array &$conv_responses)
912 foreach ($conv_responses as $mode => $v) {
917 $verb = Activity::LIKE;
920 $verb = Activity::DISLIKE;
923 $verb = Activity::ATTEND;
926 $verb = Activity::ATTENDNO;
929 $verb = Activity::ATTENDMAYBE;
932 $verb = Activity::ANNOUNCE;
938 if (!empty($activity['verb']) && DI::activity()->match($activity['verb'], $verb) && ($activity['gravity'] != GRAVITY_PARENT)) {
941 'id' => $activity['author-id'],
942 'network' => $activity['author-network'],
943 'url' => $activity['author-link']
945 $url = Contact::magicLinkByContact($author);
946 if (strpos($url, 'redir/') === 0) {
947 $sparkle = ' class="sparkle" ';
950 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
952 if (empty($activity['thr-parent-id'])) {
953 $activity['thr-parent-id'] = $activity['parent-uri-id'];
956 // Skip when the causer of the parent is the same than the author of the announce
957 if (($verb == Activity::ANNOUNCE) && Post::exists(['uri-id' => $activity['thr-parent-id'],
958 'uid' => $activity['uid'], 'causer-id' => $activity['author-id'], 'gravity' => GRAVITY_PARENT])) {
962 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
963 $conv_responses[$mode][$activity['thr-parent-id']] = [
967 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
968 // only list each unique author once
972 if (public_contact() == $activity['author-id']) {
973 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
976 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
978 // there can only be one activity verb per item so if we found anything, we can stop looking
985 * Format the activity text for an item/photo/video
987 * @param array $links = array of pre-linked names of actors
988 * @param string $verb = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
989 * @param int $id = item id
990 * @return string formatted text
991 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
993 function format_activity(array $links, $verb, $id) {
994 DI::profiler()->startRecording('rendering');
999 $total = count($links);
1001 $likers = $links[0];
1003 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1004 // list which show all likers
1007 $phrase = DI::l10n()->t('%s likes this.', $likers);
1010 $phrase = DI::l10n()->t('%s doesn\'t like this.', $likers);
1013 $phrase = DI::l10n()->t('%s attends.', $likers);
1016 $phrase = DI::l10n()->t('%s doesn\'t attend.', $likers);
1018 case 'attendmaybe' :
1019 $phrase = DI::l10n()->t('%s attends maybe.', $likers);
1022 $phrase = DI::l10n()->t('%s reshared this.', $likers);
1025 } elseif ($total > 1) {
1026 if ($total < MAX_LIKERS) {
1027 $likers = implode(', ', array_slice($links, 0, -1));
1028 $likers .= ' ' . DI::l10n()->t('and') . ' ' . $links[count($links)-1];
1030 $likers = implode(', ', array_slice($links, 0, MAX_LIKERS - 1));
1031 $likers .= ' ' . DI::l10n()->t('and %d other people', $total - MAX_LIKERS);
1034 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
1039 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> like this', $spanatts, $total);
1040 $explikers = DI::l10n()->t('%s like this.', $likers);
1043 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $total);
1044 $explikers = DI::l10n()->t('%s don\'t like this.', $likers);
1047 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend', $spanatts, $total);
1048 $explikers = DI::l10n()->t('%s attend.', $likers);
1051 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $total);
1052 $explikers = DI::l10n()->t('%s don\'t attend.', $likers);
1055 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $total);
1056 $explikers = DI::l10n()->t('%s attend maybe.', $likers);
1059 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> reshared this', $spanatts, $total);
1060 $explikers = DI::l10n()->t('%s reshared this.', $likers);
1064 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1067 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1068 '$phrase' => $phrase,
1074 DI::profiler()->stopRecording();
1078 function status_editor(App $a, array $x = [], $notes_cid = 0, $popup = false)
1080 $user = User::getById($a->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
1081 if (empty($user['uid'])) {
1085 DI::profiler()->startRecording('rendering');
1088 $x['allow_location'] = $x['allow_location'] ?? $user['allow_location'];
1089 $x['default_location'] = $x['default_location'] ?? $user['default-location'];
1090 $x['nickname'] = $x['nickname'] ?? $user['nickname'];
1091 $x['lockstate'] = $x['lockstate'] ?? ACL::getLockstateForUserId($user['uid']) ? 'lock' : 'unlock';
1092 $x['acl'] = $x['acl'] ?? ACL::getFullSelectorHTML(DI::page(), $user['uid'], true);
1093 $x['bang'] = $x['bang'] ?? '';
1094 $x['visitor'] = $x['visitor'] ?? 'block';
1095 $x['is_owner'] = $x['is_owner'] ?? true;
1096 $x['profile_uid'] = $x['profile_uid'] ?? local_user();
1099 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1101 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1102 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
1103 '$newpost' => 'true',
1104 '$baseurl' => DI::baseUrl()->get(true),
1105 '$geotag' => $geotag,
1106 '$nickname' => $x['nickname'],
1107 '$ispublic' => DI::l10n()->t('Visible to <strong>everybody</strong>'),
1108 '$linkurl' => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1109 '$term' => DI::l10n()->t('Tag term:'),
1110 '$fileas' => DI::l10n()->t('Save to Folder:'),
1111 '$whereareu' => DI::l10n()->t('Where are you right now?'),
1112 '$delitems' => DI::l10n()->t("Delete item\x28s\x29?"),
1113 '$is_mobile' => DI::mode()->isMobile(),
1117 Hook::callAll('jot_tool', $jotplugins);
1119 $tpl = Renderer::getMarkupTemplate("jot.tpl");
1121 $o .= Renderer::replaceMacros($tpl, [
1122 '$new_post' => DI::l10n()->t('New Post'),
1123 '$return_path' => DI::args()->getQueryString(),
1124 '$action' => 'item',
1125 '$share' => ($x['button'] ?? '') ?: DI::l10n()->t('Share'),
1126 '$loading' => DI::l10n()->t('Loading...'),
1127 '$upload' => DI::l10n()->t('Upload photo'),
1128 '$shortupload' => DI::l10n()->t('upload photo'),
1129 '$attach' => DI::l10n()->t('Attach file'),
1130 '$shortattach' => DI::l10n()->t('attach file'),
1131 '$edbold' => DI::l10n()->t('Bold'),
1132 '$editalic' => DI::l10n()->t('Italic'),
1133 '$eduline' => DI::l10n()->t('Underline'),
1134 '$edquote' => DI::l10n()->t('Quote'),
1135 '$edcode' => DI::l10n()->t('Code'),
1136 '$edimg' => DI::l10n()->t('Image'),
1137 '$edurl' => DI::l10n()->t('Link'),
1138 '$edattach' => DI::l10n()->t('Link or Media'),
1139 '$edvideo' => DI::l10n()->t('Video'),
1140 '$setloc' => DI::l10n()->t('Set your location'),
1141 '$shortsetloc' => DI::l10n()->t('set location'),
1142 '$noloc' => DI::l10n()->t('Clear browser location'),
1143 '$shortnoloc' => DI::l10n()->t('clear location'),
1144 '$title' => $x['title'] ?? '',
1145 '$placeholdertitle' => DI::l10n()->t('Set title'),
1146 '$category' => $x['category'] ?? '',
1147 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1148 '$scheduled_at' => Temporal::getDateTimeField(
1150 new DateTime('now + 6 months'),
1152 DI::l10n()->t('Scheduled at'),
1155 '$wait' => DI::l10n()->t('Please wait'),
1156 '$permset' => DI::l10n()->t('Permission settings'),
1157 '$shortpermset' => DI::l10n()->t('Permissions'),
1158 '$wall' => $notes_cid ? 0 : 1,
1159 '$posttype' => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1160 '$content' => $x['content'] ?? '',
1161 '$post_id' => $x['post_id'] ?? '',
1162 '$baseurl' => DI::baseUrl()->get(true),
1163 '$defloc' => $x['default_location'],
1164 '$visitor' => $x['visitor'],
1165 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
1166 '$public' => DI::l10n()->t('Public post'),
1167 '$lockstate' => $x['lockstate'],
1168 '$bang' => $x['bang'],
1169 '$profile_uid' => $x['profile_uid'],
1170 '$preview' => DI::l10n()->t('Preview'),
1171 '$jotplugins' => $jotplugins,
1172 '$notes_cid' => $notes_cid,
1173 '$cancel' => DI::l10n()->t('Cancel'),
1174 '$rand_num' => Crypto::randomDigits(12),
1176 // ACL permissions box
1177 '$acl' => $x['acl'],
1179 //jot nav tab (used in some themes)
1180 '$message' => DI::l10n()->t('Message'),
1181 '$browser' => DI::l10n()->t('Browser'),
1183 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1187 if ($popup == true) {
1188 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1191 DI::profiler()->stopRecording();
1196 * Plucks the children of the given parent from a given item list.
1198 * @param array $item_list
1199 * @param array $parent
1200 * @param bool $recursive
1203 function get_item_children(array &$item_list, array $parent, $recursive = true)
1205 DI::profiler()->startRecording('rendering');
1207 foreach ($item_list as $i => $item) {
1208 if ($item['gravity'] != GRAVITY_PARENT) {
1210 // Fallback to parent-uri if thr-parent is not set
1211 $thr_parent = $item['thr-parent-id'];
1212 if ($thr_parent == '') {
1213 $thr_parent = $item['parent-uri-id'];
1216 if ($thr_parent == $parent['uri-id']) {
1217 $item['children'] = get_item_children($item_list, $item);
1218 $children[] = $item;
1219 unset($item_list[$i]);
1221 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1222 $children[] = $item;
1223 unset($item_list[$i]);
1227 DI::profiler()->stopRecording();
1232 * Recursively sorts a tree-like item array
1234 * @param array $items
1237 function sort_item_children(array $items)
1239 DI::profiler()->startRecording('rendering');
1241 usort($result, 'sort_thr_received_rev');
1242 foreach ($result as $k => $i) {
1243 if (isset($result[$k]['children'])) {
1244 $result[$k]['children'] = sort_item_children($result[$k]['children']);
1247 DI::profiler()->stopRecording();
1252 * Recursively add all children items at the top level of a list
1254 * @param array $children List of items to append
1255 * @param array $item_list
1257 function add_children_to_list(array $children, array &$item_list)
1259 foreach ($children as $child) {
1260 $item_list[] = $child;
1261 if (isset($child['children'])) {
1262 add_children_to_list($child['children'], $item_list);
1268 * Selectively flattens a tree-like item structure to prevent threading stairs
1270 * This recursive function takes the item tree structure created by conv_sort() and
1271 * flatten the extraneous depth levels when people reply sequentially, removing the
1272 * stairs effect in threaded conversations limiting the available content width.
1274 * The basic principle is the following: if a post item has only one reply and is
1275 * the last reply of its parent, then the reply is moved to the parent.
1277 * This process is rendered somewhat more complicated because items can be either
1278 * replies or likes, and these don't factor at all in the reply count/last reply.
1280 * @param array $parent A tree-like array of items
1283 function smart_flatten_conversation(array $parent)
1285 DI::profiler()->startRecording('rendering');
1286 if (!isset($parent['children']) || count($parent['children']) == 0) {
1287 DI::profiler()->stopRecording();
1291 // We use a for loop to ensure we process the newly-moved items
1292 for ($i = 0; $i < count($parent['children']); $i++) {
1293 $child = $parent['children'][$i];
1295 if (isset($child['children']) && count($child['children'])) {
1296 // This helps counting only the regular posts
1297 $count_post_closure = function($var) {
1298 DI::profiler()->stopRecording();
1299 return $var['verb'] === Activity::POST;
1302 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1304 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1306 // If there's only one child's children post and this is the last child post
1307 if ($child_post_count == 1 && $remaining_post_count == 1) {
1309 // Searches the post item in the children
1311 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1315 $moved_item = $child['children'][$j];
1316 unset($parent['children'][$i]['children'][$j]);
1317 $parent['children'][] = $moved_item;
1319 $parent['children'][$i] = smart_flatten_conversation($child);
1324 DI::profiler()->stopRecording();
1330 * Expands a flat list of items into corresponding tree-like conversation structures.
1332 * sort the top-level posts either on "received" or "commented", and finally
1333 * append all the items at the top level (???)
1335 * @param array $item_list A list of items belonging to one or more conversations
1336 * @param string $order Either on "received" or "commented"
1338 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1340 function conv_sort(array $item_list, $order)
1342 DI::profiler()->startRecording('rendering');
1345 if (!(is_array($item_list) && count($item_list))) {
1346 DI::profiler()->stopRecording();
1350 $blocklist = conv_get_blocklist();
1354 // Dedupes the item list on the uri to prevent infinite loops
1355 foreach ($item_list as $item) {
1356 if (in_array($item['author-id'], $blocklist)) {
1360 $item_array[$item['uri-id']] = $item;
1363 // Extract the top level items
1364 foreach ($item_array as $item) {
1365 if ($item['gravity'] == GRAVITY_PARENT) {
1370 if (stristr($order, 'pinned_received')) {
1371 usort($parents, 'sort_thr_pinned_received');
1372 } elseif (stristr($order, 'received')) {
1373 usort($parents, 'sort_thr_received');
1374 } elseif (stristr($order, 'commented')) {
1375 usort($parents, 'sort_thr_commented');
1379 * Plucks children from the item_array, second pass collects eventual orphan
1380 * items and add them as children of their top-level post.
1382 foreach ($parents as $i => $parent) {
1383 $parents[$i]['children'] =
1384 array_merge(get_item_children($item_array, $parent, true),
1385 get_item_children($item_array, $parent, false));
1388 foreach ($parents as $i => $parent) {
1389 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1392 if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
1393 foreach ($parents as $i => $parent) {
1394 $parents[$i] = smart_flatten_conversation($parent);
1398 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1399 /// However, this apparently ensures responses (likes, attendance) display (?!)
1400 foreach ($parents as $parent) {
1401 if (count($parent['children'])) {
1402 add_children_to_list($parent['children'], $parents);
1406 DI::profiler()->stopRecording();
1411 * usort() callback to sort item arrays by pinned and the received key
1417 function sort_thr_pinned_received(array $a, array $b)
1419 if ($b['pinned'] && !$a['pinned']) {
1421 } elseif (!$b['pinned'] && $a['pinned']) {
1425 return strcmp($b['received'], $a['received']);
1429 * usort() callback to sort item arrays by the received key
1435 function sort_thr_received(array $a, array $b)
1437 return strcmp($b['received'], $a['received']);
1441 * usort() callback to reverse sort item arrays by the received key
1447 function sort_thr_received_rev(array $a, array $b)
1449 return strcmp($a['received'], $b['received']);
1453 * usort() callback to sort item arrays by the commented key
1459 function sort_thr_commented(array $a, array $b)
1461 return strcmp($b['commented'], $a['commented']);