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';
422 foreach ($items as $item) {
424 if (!visible_activity($item)) {
428 if (in_array($item['author-id'], $blocklist)) {
434 // prevent private email from leaking.
435 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
439 $profile_name = $item['author-name'];
440 if (!empty($item['author-link']) && empty($item['author-name'])) {
441 $profile_name = $item['author-link'];
444 $tags = Tag::populateFromItem($item);
446 $author = ['uid' => 0, 'id' => $item['author-id'],
447 'network' => $item['author-network'], 'url' => $item['author-link']];
448 $profile_link = Contact::magicLinkByContact($author);
451 if (strpos($profile_link, 'redir/') === 0) {
452 $sparkle = ' sparkle';
455 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
456 Hook::callAll('render_location', $locate);
457 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
459 localize_item($item);
460 if ($mode === 'filed') {
467 'dropping' => $dropping,
468 'pagedrop' => $page_dropping,
469 'select' => DI::l10n()->t('Select'),
470 'delete' => DI::l10n()->t('Delete'),
480 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
481 unset($likebuttons['dislike']);
484 $body_html = Item::prepareBody($item, true, $preview);
486 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item, local_user());
488 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
489 $title = ucfirst($item['content-warning']);
491 $title = $item['title'];
496 'id' => ($preview ? 'P0' : $item['id']),
497 'guid' => ($preview ? 'Q0' : $item['guid']),
498 'commented' => $item['commented'],
499 'received' => $item['received'],
500 'created_date' => $item['created'],
501 'uriid' => $item['uri-id'],
502 'network' => $item['network'],
503 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
504 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link']),
505 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
506 'profile_url' => $profile_link,
507 'item_photo_menu_html' => item_photo_menu($item, $formSecurityToken),
508 'name' => $profile_name,
509 'sparkle' => $sparkle,
511 'thumb' => DI::baseUrl()->remove(Contact::getAvatarUrlForUrl($item['author-link'], $item['uid'], Proxy::SIZE_THUMB)),
513 'body_html' => $body_html,
514 'tags' => $tags['tags'],
515 'hashtags' => $tags['hashtags'],
516 'mentions' => $tags['mentions'],
517 'implicit_mentions' => $tags['implicit_mentions'],
518 'txt_cats' => DI::l10n()->t('Categories:'),
519 'txt_folders' => DI::l10n()->t('Filed under:'),
520 'has_cats' => ((count($categories)) ? 'true' : ''),
521 'has_folders' => ((count($folders)) ? 'true' : ''),
522 'categories' => $categories,
523 'folders' => $folders,
524 'text' => strip_tags($body_html),
525 'localtime' => DateTimeFormat::local($item['created'], 'r'),
526 'ago' => (($item['app']) ? DI::l10n()->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
527 'location_html' => $location_html,
531 'owner_photo' => DI::baseUrl()->remove(Contact::getAvatarUrlForUrl($item['owner-link'], $item['uid'], Proxy::SIZE_THUMB)),
532 'plink' => Item::getPlink($item),
534 'isstarred' => 'unstarred',
537 'vote' => $likebuttons,
539 'dislike_html' => '',
540 'comment_html' => '',
541 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> DI::l10n()->t('View in context')]),
542 'previewing' => $previewing,
543 'wait' => DI::l10n()->t('Please wait'),
547 $arr = ['item' => $item, 'output' => $tmp_item];
548 Hook::callAll('display_item', $arr);
550 $threads[$threadsid]['id'] = $item['id'];
551 $threads[$threadsid]['network'] = $item['network'];
552 $threads[$threadsid]['items'] = [$arr['output']];
557 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
559 $conv = new Thread($mode, $preview, $writable);
562 * get all the topmost parents
563 * this shouldn't be needed, as we should have only them in our array
564 * But for now, this array respects the old style, just in case
566 foreach ($items as $item) {
567 if (in_array($item['author-id'], $blocklist)) {
571 // Can we put this after the visibility check?
572 builtin_activity_puller($item, $conv_responses);
574 // Only add what is visible
575 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
579 if (!visible_activity($item)) {
583 /// @todo Check if this call is needed or not
584 $arr = ['item' => $item];
585 Hook::callAll('display_item', $arr);
587 $item['pagedrop'] = $page_dropping;
589 if ($item['gravity'] == GRAVITY_PARENT) {
590 $item_object = new PostObject($item);
591 $conv->addParent($item_object);
595 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
597 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
603 $o = Renderer::replaceMacros($page_template, [
604 '$baseurl' => DI::baseUrl()->get($ssl_state),
605 '$return_path' => DI::args()->getQueryString(),
606 '$live_update' => $live_update_div,
607 '$remove' => DI::l10n()->t('remove'),
609 '$update' => $update,
610 '$threads' => $threads,
611 '$dropping' => ($page_dropping ? DI::l10n()->t('Delete Selected Items') : False),
614 DI::profiler()->stopRecording();
619 * Adds some information (Causer, post reason, direction) to the fetched post row.
621 * @param array $row Post row
622 * @param array $activity Contact data of the resharer
624 * @return array items with parents and comments
626 function conversation_add_row_information(array $row, array $activity) {
627 DI::profiler()->startRecording('rendering');
629 if ($row['uid'] == 0) {
630 $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
633 if (!empty($activity)) {
634 if (($row['gravity'] == GRAVITY_PARENT)) {
635 $row['post-reason'] = Item::PR_ANNOUNCEMENT;
636 $row = array_merge($row, $activity);
637 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
638 $row['causer-link'] = $contact['url'];
639 $row['causer-avatar'] = $contact['thumb'];
640 $row['causer-name'] = $contact['name'];
641 } elseif (($row['gravity'] == GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
642 ($row['author-id'] == $activity['causer-id'])) {
647 switch ($row['post-reason']) {
649 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'to')];
652 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'cc')];
655 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bto')];
658 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bcc')];
660 case Item::PR_FOLLOWER:
661 $row['direction'] = ['direction' => 6, 'title' => DI::l10n()->t('You are following %s.', $row['author-name'])];
664 $row['direction'] = ['direction' => 4, 'title' => DI::l10n()->t('Tagged')];
666 case Item::PR_ANNOUNCEMENT:
667 if (!empty($row['causer-id']) && DI::pConfig()->get(local_user(), 'system', 'display_resharer')) {
668 $row['owner-id'] = $row['causer-id'];
669 $row['owner-link'] = $row['causer-link'];
670 $row['owner-avatar'] = $row['causer-avatar'];
671 $row['owner-name'] = $row['causer-name'];
674 if (($row['gravity'] == GRAVITY_PARENT) && !empty($row['causer-id'])) {
675 $causer = ['uid' => 0, 'id' => $row['causer-id'],
676 'network' => $row['causer-network'], 'url' => $row['causer-link']];
677 $row['reshared'] = DI::l10n()->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
679 $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']))];
681 case Item::PR_COMMENT:
682 $row['direction'] = ['direction' => 5, 'title' => DI::l10n()->t('%s is participating in this thread.', $row['author-name'])];
684 case Item::PR_STORED:
685 $row['direction'] = ['direction' => 8, 'title' => DI::l10n()->t('Stored')];
687 case Item::PR_GLOBAL:
688 $row['direction'] = ['direction' => 9, 'title' => DI::l10n()->t('Global')];
691 $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']))];
693 case Item::PR_FETCHED:
694 $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']))];
698 DI::profiler()->stopRecording();
703 * Add comments to top level entries that had been fetched before
705 * The system will fetch the comments for the local user whenever possible.
706 * This behaviour is currently needed to allow commenting on Friendica posts.
708 * @param array $parents Parent items
710 * @param $block_authors
713 * @return array items with parents and comments
714 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
716 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
717 DI::profiler()->startRecording('rendering');
718 if (count($parents) > 1) {
719 $max_comments = DI::config()->get('system', 'max_comments', 100);
721 $max_comments = DI::config()->get('system', 'max_display_comments', 1000);
724 $params = ['order' => ['uri-id' => true, 'uid' => true]];
728 $commentcounter = [];
729 $activitycounter = [];
731 foreach ($parents AS $parent) {
732 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == GRAVITY_ACTIVITY)) {
733 $uriid = $parent['thr-parent-id'];
734 if (!empty($parent['author-id'])) {
735 $activities[$uriid] = ['causer-id' => $parent['author-id']];
736 foreach (['commented', 'received', 'created'] as $orderfields) {
737 if (!empty($parent[$orderfields])) {
738 $activities[$uriid][$orderfields] = $parent[$orderfields];
743 $uriid = $parent['uri-id'];
747 $commentcounter[$uriid] = 0;
748 $activitycounter[$uriid] = 0;
751 $condition = ['parent-uri-id' => $uriids];
752 if ($block_authors) {
753 $condition['author-hidden'] = false;
756 $condition = DBA::mergeConditions($condition,
757 ["`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW)]);
759 $thread_items = Post::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['pinned', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
763 while ($row = Post::fetch($thread_items)) {
764 if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
768 if ($max_comments > 0) {
769 if (($row['gravity'] == GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
772 if (($row['gravity'] == GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
776 $items[$row['uri-id']] = conversation_add_row_information($row, $activities[$row['uri-id']] ?? []);
779 DBA::close($thread_items);
781 $items = conv_sort($items, $order);
783 DI::profiler()->stopRecording();
787 function item_photo_menu($item, string $formSecurityToken)
789 DI::profiler()->startRecording('rendering');
800 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
801 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
804 $author = ['uid' => 0, 'id' => $item['author-id'],
805 'network' => $item['author-network'], 'url' => $item['author-link']];
806 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
807 $sparkle = (strpos($profile_link, 'redir/') === 0);
810 $pcid = $item['author-id'];
813 $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
814 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
815 if (DBA::isResult($contact)) {
816 $cid = $contact['id'];
817 $network = $contact['network'];
818 $rel = $contact['rel'];
822 $status_link = $profile_link . '/status';
823 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
824 $profile_link = $profile_link . '/profile';
828 $contact_url = 'contact/' . $pcid;
829 $posts_link = $contact_url . '/posts';
830 $block_link = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
831 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
834 if ($cid && !$item['self']) {
835 $contact_url = 'contact/' . $cid;
836 $poke_link = $contact_url . '/poke';
837 $posts_link = $contact_url . '/posts';
839 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
840 $pm_url = 'message/new/' . $cid;
846 DI::l10n()->t('Follow Thread') => $sub_link,
847 DI::l10n()->t('View Status') => $status_link,
848 DI::l10n()->t('View Profile') => $profile_link,
849 DI::l10n()->t('View Photos') => $photos_link,
850 DI::l10n()->t('Network Posts') => $posts_link,
851 DI::l10n()->t('View Contact') => $contact_url,
852 DI::l10n()->t('Send PM') => $pm_url,
853 DI::l10n()->t('Block') => $block_link,
854 DI::l10n()->t('Ignore') => $ignore_link
857 if (!empty($item['language'])) {
858 $menu[DI::l10n()->t('Languages')] = 'javascript:alert(\'' . Item::getLanguageMessage($item) . '\');';
861 if ($network == Protocol::DFRN) {
862 $menu[DI::l10n()->t("Poke")] = $poke_link;
865 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
866 in_array($item['network'], Protocol::FEDERATED)) {
867 $menu[DI::l10n()->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
870 $menu = [DI::l10n()->t('View Profile') => $item['author-link']];
873 $args = ['item' => $item, 'menu' => $menu];
875 Hook::callAll('item_photo_menu', $args);
877 $menu = $args['menu'];
880 foreach ($menu as $k => $v) {
881 if (strpos($v, 'javascript:') === 0) {
883 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
885 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
888 DI::profiler()->stopRecording();
893 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
895 * Increments the count of each matching activity and adds a link to the author as needed.
897 * @param array $activity
898 * @param array &$conv_responses (already created with builtin activity structure)
900 * @throws ImagickException
901 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
903 function builtin_activity_puller(array $activity, array &$conv_responses)
905 foreach ($conv_responses as $mode => $v) {
910 $verb = Activity::LIKE;
913 $verb = Activity::DISLIKE;
916 $verb = Activity::ATTEND;
919 $verb = Activity::ATTENDNO;
922 $verb = Activity::ATTENDMAYBE;
925 $verb = Activity::ANNOUNCE;
931 if (!empty($activity['verb']) && DI::activity()->match($activity['verb'], $verb) && ($activity['gravity'] != GRAVITY_PARENT)) {
934 'id' => $activity['author-id'],
935 'network' => $activity['author-network'],
936 'url' => $activity['author-link']
938 $url = Contact::magicLinkByContact($author);
939 if (strpos($url, 'redir/') === 0) {
940 $sparkle = ' class="sparkle" ';
943 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
945 if (empty($activity['thr-parent-id'])) {
946 $activity['thr-parent-id'] = $activity['parent-uri-id'];
949 // Skip when the causer of the parent is the same than the author of the announce
950 if (($verb == Activity::ANNOUNCE) && Post::exists(['uri-id' => $activity['thr-parent-id'],
951 'uid' => $activity['uid'], 'causer-id' => $activity['author-id'], 'gravity' => GRAVITY_PARENT])) {
955 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
956 $conv_responses[$mode][$activity['thr-parent-id']] = [
960 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
961 // only list each unique author once
965 if (public_contact() == $activity['author-id']) {
966 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
969 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
971 // there can only be one activity verb per item so if we found anything, we can stop looking
978 * Format the activity text for an item/photo/video
980 * @param array $links = array of pre-linked names of actors
981 * @param string $verb = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
982 * @param int $id = item id
983 * @return string formatted text
984 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
986 function format_activity(array $links, $verb, $id) {
987 DI::profiler()->startRecording('rendering');
992 $total = count($links);
996 // Phrase if there is only one liker. In other cases it will be uses for the expanded
997 // list which show all likers
1000 $phrase = DI::l10n()->t('%s likes this.', $likers);
1003 $phrase = DI::l10n()->t('%s doesn\'t like this.', $likers);
1006 $phrase = DI::l10n()->t('%s attends.', $likers);
1009 $phrase = DI::l10n()->t('%s doesn\'t attend.', $likers);
1011 case 'attendmaybe' :
1012 $phrase = DI::l10n()->t('%s attends maybe.', $likers);
1015 $phrase = DI::l10n()->t('%s reshared this.', $likers);
1018 } elseif ($total > 1) {
1019 if ($total < MAX_LIKERS) {
1020 $likers = implode(', ', array_slice($links, 0, -1));
1021 $likers .= ' ' . DI::l10n()->t('and') . ' ' . $links[count($links)-1];
1023 $likers = implode(', ', array_slice($links, 0, MAX_LIKERS - 1));
1024 $likers .= ' ' . DI::l10n()->t('and %d other people', $total - MAX_LIKERS);
1027 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
1032 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> like this', $spanatts, $total);
1033 $explikers = DI::l10n()->t('%s like this.', $likers);
1036 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $total);
1037 $explikers = DI::l10n()->t('%s don\'t like this.', $likers);
1040 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend', $spanatts, $total);
1041 $explikers = DI::l10n()->t('%s attend.', $likers);
1044 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $total);
1045 $explikers = DI::l10n()->t('%s don\'t attend.', $likers);
1048 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $total);
1049 $explikers = DI::l10n()->t('%s attend maybe.', $likers);
1052 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> reshared this', $spanatts, $total);
1053 $explikers = DI::l10n()->t('%s reshared this.', $likers);
1057 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1060 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1061 '$phrase' => $phrase,
1067 DI::profiler()->stopRecording();
1071 function status_editor(App $a, array $x = [], $notes_cid = 0, $popup = false)
1073 $user = User::getById($a->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
1074 if (empty($user['uid'])) {
1078 DI::profiler()->startRecording('rendering');
1081 $x['allow_location'] = $x['allow_location'] ?? $user['allow_location'];
1082 $x['default_location'] = $x['default_location'] ?? $user['default-location'];
1083 $x['nickname'] = $x['nickname'] ?? $user['nickname'];
1084 $x['lockstate'] = $x['lockstate'] ?? ACL::getLockstateForUserId($user['uid']) ? 'lock' : 'unlock';
1085 $x['acl'] = $x['acl'] ?? ACL::getFullSelectorHTML(DI::page(), $user['uid'], true);
1086 $x['bang'] = $x['bang'] ?? '';
1087 $x['visitor'] = $x['visitor'] ?? 'block';
1088 $x['is_owner'] = $x['is_owner'] ?? true;
1089 $x['profile_uid'] = $x['profile_uid'] ?? local_user();
1092 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1094 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1095 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
1096 '$newpost' => 'true',
1097 '$baseurl' => DI::baseUrl()->get(true),
1098 '$geotag' => $geotag,
1099 '$nickname' => $x['nickname'],
1100 '$ispublic' => DI::l10n()->t('Visible to <strong>everybody</strong>'),
1101 '$linkurl' => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1102 '$term' => DI::l10n()->t('Tag term:'),
1103 '$fileas' => DI::l10n()->t('Save to Folder:'),
1104 '$whereareu' => DI::l10n()->t('Where are you right now?'),
1105 '$delitems' => DI::l10n()->t("Delete item\x28s\x29?"),
1106 '$is_mobile' => DI::mode()->isMobile(),
1110 Hook::callAll('jot_tool', $jotplugins);
1112 $tpl = Renderer::getMarkupTemplate("jot.tpl");
1114 $o .= Renderer::replaceMacros($tpl, [
1115 '$new_post' => DI::l10n()->t('New Post'),
1116 '$return_path' => DI::args()->getQueryString(),
1117 '$action' => 'item',
1118 '$share' => ($x['button'] ?? '') ?: DI::l10n()->t('Share'),
1119 '$loading' => DI::l10n()->t('Loading...'),
1120 '$upload' => DI::l10n()->t('Upload photo'),
1121 '$shortupload' => DI::l10n()->t('upload photo'),
1122 '$attach' => DI::l10n()->t('Attach file'),
1123 '$shortattach' => DI::l10n()->t('attach file'),
1124 '$edbold' => DI::l10n()->t('Bold'),
1125 '$editalic' => DI::l10n()->t('Italic'),
1126 '$eduline' => DI::l10n()->t('Underline'),
1127 '$edquote' => DI::l10n()->t('Quote'),
1128 '$edcode' => DI::l10n()->t('Code'),
1129 '$edimg' => DI::l10n()->t('Image'),
1130 '$edurl' => DI::l10n()->t('Link'),
1131 '$edattach' => DI::l10n()->t('Link or Media'),
1132 '$edvideo' => DI::l10n()->t('Video'),
1133 '$setloc' => DI::l10n()->t('Set your location'),
1134 '$shortsetloc' => DI::l10n()->t('set location'),
1135 '$noloc' => DI::l10n()->t('Clear browser location'),
1136 '$shortnoloc' => DI::l10n()->t('clear location'),
1137 '$title' => $x['title'] ?? '',
1138 '$placeholdertitle' => DI::l10n()->t('Set title'),
1139 '$category' => $x['category'] ?? '',
1140 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1141 '$scheduled_at' => Temporal::getDateTimeField(
1143 DateTime::createFromFormat(DateTimeFormat::MYSQL, DateTimeFormat::local('now + 6 months')),
1145 DI::l10n()->t('Scheduled at'),
1148 '$wait' => DI::l10n()->t('Please wait'),
1149 '$permset' => DI::l10n()->t('Permission settings'),
1150 '$shortpermset' => DI::l10n()->t('Permissions'),
1151 '$wall' => $notes_cid ? 0 : 1,
1152 '$posttype' => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1153 '$content' => $x['content'] ?? '',
1154 '$post_id' => $x['post_id'] ?? '',
1155 '$baseurl' => DI::baseUrl()->get(true),
1156 '$defloc' => $x['default_location'],
1157 '$visitor' => $x['visitor'],
1158 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
1159 '$public' => DI::l10n()->t('Public post'),
1160 '$lockstate' => $x['lockstate'],
1161 '$bang' => $x['bang'],
1162 '$profile_uid' => $x['profile_uid'],
1163 '$preview' => DI::l10n()->t('Preview'),
1164 '$jotplugins' => $jotplugins,
1165 '$notes_cid' => $notes_cid,
1166 '$cancel' => DI::l10n()->t('Cancel'),
1167 '$rand_num' => Crypto::randomDigits(12),
1169 // ACL permissions box
1170 '$acl' => $x['acl'],
1172 //jot nav tab (used in some themes)
1173 '$message' => DI::l10n()->t('Message'),
1174 '$browser' => DI::l10n()->t('Browser'),
1176 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1180 if ($popup == true) {
1181 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1184 DI::profiler()->stopRecording();
1189 * Plucks the children of the given parent from a given item list.
1191 * @param array $item_list
1192 * @param array $parent
1193 * @param bool $recursive
1196 function get_item_children(array &$item_list, array $parent, $recursive = true)
1198 DI::profiler()->startRecording('rendering');
1200 foreach ($item_list as $i => $item) {
1201 if ($item['gravity'] != GRAVITY_PARENT) {
1203 // Fallback to parent-uri if thr-parent is not set
1204 $thr_parent = $item['thr-parent-id'];
1205 if ($thr_parent == '') {
1206 $thr_parent = $item['parent-uri-id'];
1209 if ($thr_parent == $parent['uri-id']) {
1210 $item['children'] = get_item_children($item_list, $item);
1211 $children[] = $item;
1212 unset($item_list[$i]);
1214 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1215 $children[] = $item;
1216 unset($item_list[$i]);
1220 DI::profiler()->stopRecording();
1225 * Recursively sorts a tree-like item array
1227 * @param array $items
1230 function sort_item_children(array $items)
1232 DI::profiler()->startRecording('rendering');
1234 usort($result, 'sort_thr_received_rev');
1235 foreach ($result as $k => $i) {
1236 if (isset($result[$k]['children'])) {
1237 $result[$k]['children'] = sort_item_children($result[$k]['children']);
1240 DI::profiler()->stopRecording();
1245 * Recursively add all children items at the top level of a list
1247 * @param array $children List of items to append
1248 * @param array $item_list
1250 function add_children_to_list(array $children, array &$item_list)
1252 foreach ($children as $child) {
1253 $item_list[] = $child;
1254 if (isset($child['children'])) {
1255 add_children_to_list($child['children'], $item_list);
1261 * Selectively flattens a tree-like item structure to prevent threading stairs
1263 * This recursive function takes the item tree structure created by conv_sort() and
1264 * flatten the extraneous depth levels when people reply sequentially, removing the
1265 * stairs effect in threaded conversations limiting the available content width.
1267 * The basic principle is the following: if a post item has only one reply and is
1268 * the last reply of its parent, then the reply is moved to the parent.
1270 * This process is rendered somewhat more complicated because items can be either
1271 * replies or likes, and these don't factor at all in the reply count/last reply.
1273 * @param array $parent A tree-like array of items
1276 function smart_flatten_conversation(array $parent)
1278 DI::profiler()->startRecording('rendering');
1279 if (!isset($parent['children']) || count($parent['children']) == 0) {
1280 DI::profiler()->stopRecording();
1284 // We use a for loop to ensure we process the newly-moved items
1285 for ($i = 0; $i < count($parent['children']); $i++) {
1286 $child = $parent['children'][$i];
1288 if (isset($child['children']) && count($child['children'])) {
1289 // This helps counting only the regular posts
1290 $count_post_closure = function($var) {
1291 DI::profiler()->stopRecording();
1292 return $var['verb'] === Activity::POST;
1295 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1297 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1299 // If there's only one child's children post and this is the last child post
1300 if ($child_post_count == 1 && $remaining_post_count == 1) {
1302 // Searches the post item in the children
1304 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1308 $moved_item = $child['children'][$j];
1309 unset($parent['children'][$i]['children'][$j]);
1310 $parent['children'][] = $moved_item;
1312 $parent['children'][$i] = smart_flatten_conversation($child);
1317 DI::profiler()->stopRecording();
1323 * Expands a flat list of items into corresponding tree-like conversation structures.
1325 * sort the top-level posts either on "received" or "commented", and finally
1326 * append all the items at the top level (???)
1328 * @param array $item_list A list of items belonging to one or more conversations
1329 * @param string $order Either on "received" or "commented"
1331 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1333 function conv_sort(array $item_list, $order)
1335 DI::profiler()->startRecording('rendering');
1338 if (!(is_array($item_list) && count($item_list))) {
1339 DI::profiler()->stopRecording();
1343 $blocklist = conv_get_blocklist();
1347 // Dedupes the item list on the uri to prevent infinite loops
1348 foreach ($item_list as $item) {
1349 if (in_array($item['author-id'], $blocklist)) {
1353 $item_array[$item['uri-id']] = $item;
1356 // Extract the top level items
1357 foreach ($item_array as $item) {
1358 if ($item['gravity'] == GRAVITY_PARENT) {
1363 if (stristr($order, 'pinned_received')) {
1364 usort($parents, 'sort_thr_pinned_received');
1365 } elseif (stristr($order, 'received')) {
1366 usort($parents, 'sort_thr_received');
1367 } elseif (stristr($order, 'commented')) {
1368 usort($parents, 'sort_thr_commented');
1372 * Plucks children from the item_array, second pass collects eventual orphan
1373 * items and add them as children of their top-level post.
1375 foreach ($parents as $i => $parent) {
1376 $parents[$i]['children'] =
1377 array_merge(get_item_children($item_array, $parent, true),
1378 get_item_children($item_array, $parent, false));
1381 foreach ($parents as $i => $parent) {
1382 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1385 if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
1386 foreach ($parents as $i => $parent) {
1387 $parents[$i] = smart_flatten_conversation($parent);
1391 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1392 /// However, this apparently ensures responses (likes, attendance) display (?!)
1393 foreach ($parents as $parent) {
1394 if (count($parent['children'])) {
1395 add_children_to_list($parent['children'], $parents);
1399 DI::profiler()->stopRecording();
1404 * usort() callback to sort item arrays by pinned and the received key
1410 function sort_thr_pinned_received(array $a, array $b)
1412 if ($b['pinned'] && !$a['pinned']) {
1414 } elseif (!$b['pinned'] && $a['pinned']) {
1418 return strcmp($b['received'], $a['received']);
1422 * usort() callback to sort item arrays by the received key
1428 function sort_thr_received(array $a, array $b)
1430 return strcmp($b['received'], $a['received']);
1434 * usort() callback to reverse sort item arrays by the received key
1440 function sort_thr_received_rev(array $a, array $b)
1442 return strcmp($a['received'], $b['received']);
1446 * usort() callback to sort item arrays by the commented key
1452 function sort_thr_commented(array $a, array $b)
1454 return strcmp($b['commented'], $a['commented']);