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\Content\ContactSelector;
24 use Friendica\Content\Feature;
25 use Friendica\Core\Hook;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\Renderer;
29 use Friendica\Core\Session;
30 use Friendica\Core\Theme;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Item;
35 use Friendica\Model\Post;
36 use Friendica\Model\Tag;
37 use Friendica\Model\Verb;
38 use Friendica\Object\Post as PostObject;
39 use Friendica\Object\Thread;
40 use Friendica\Protocol\Activity;
41 use Friendica\Util\Crypto;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Proxy;
44 use Friendica\Util\Strings;
45 use Friendica\Util\Temporal;
46 use Friendica\Util\XML;
49 * Render actions localized
52 * @throws ImagickException
53 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
55 function localize_item(&$item)
57 DI::profiler()->startRecording('rendering');
58 /// @todo The following functionality needs to be cleaned up.
59 if (!empty($item['verb'])) {
60 $activity = DI::activity();
62 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
64 if (stristr($item['verb'], Activity::POKE)) {
65 $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
67 DI::profiler()->stopRecording();
70 if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
71 DI::profiler()->stopRecording();
75 $obj = XML::parseString($xmlhead . $item['object']);
81 foreach ($obj->link as $l) {
82 $atts = $l->attributes();
83 switch ($atts['rel']) {
84 case "alternate": $Blink = $atts['href'];
85 case "photo": $Bphoto = $atts['href'];
89 $author = ['uid' => 0, 'id' => $item['author-id'],
90 'network' => $item['author-network'], 'url' => $item['author-link']];
91 $A = '[url=' . Contact::magicLinkByContact($author) . ']' . $item['author-name'] . '[/url]';
94 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
99 if ($Bphoto != "" && !empty($Blink)) {
100 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
104 * we can't have a translation string with three positions but no distinguishable text
105 * So here is the translate string.
107 $txt = DI::l10n()->t('%1$s poked %2$s');
109 // now translate the verb
110 $poked_t = trim(sprintf($txt, '', ''));
111 $txt = str_replace($poked_t, DI::l10n()->t($verb), $txt);
113 // then do the sprintf on the translation string
115 $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
119 if ($activity->match($item['verb'], Activity::TAG)) {
120 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
121 'verb', 'object-type', 'resource-id', 'body', 'plink'];
122 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
123 if (!DBA::isResult($obj)) {
124 DI::profiler()->stopRecording();
128 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
129 'network' => $item['author-network'], 'url' => $item['author-link']];
130 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
132 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
133 'network' => $obj['author-network'], 'url' => $obj['author-link']];
134 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
136 switch ($obj['verb']) {
138 switch ($obj['object-type']) {
139 case Activity\ObjectType::EVENT:
140 $post_type = DI::l10n()->t('event');
143 $post_type = DI::l10n()->t('status');
147 if ($obj['resource-id']) {
148 $post_type = DI::l10n()->t('photo');
149 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
150 $rr['plink'] = $m[1];
152 $post_type = DI::l10n()->t('status');
154 // Let's break everthing ... ;-)
157 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
159 $parsedobj = XML::parseString($xmlhead . $item['object']);
161 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
162 $item['body'] = DI::l10n()->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
167 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
168 foreach ($matches as $mtch) {
169 if (!strpos($mtch[1], 'zrl=')) {
170 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
175 // add sparkle links to appropriate permalinks
176 // Only create a redirection to a magic link when logged in
177 if (!empty($item['plink']) && Session::isAuthenticated()) {
178 $author = ['uid' => 0, 'id' => $item['author-id'],
179 'network' => $item['author-network'], 'url' => $item['author-link']];
180 $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
182 DI::profiler()->stopRecording();
186 * Count the total of comments on this item and its desendants
187 * @TODO proper type-hint + doc-tag
191 function count_descendants($item) {
192 $total = count($item['children']);
195 foreach ($item['children'] as $child) {
196 if (!visible_activity($child)) {
199 $total += count_descendants($child);
206 function visible_activity($item) {
208 $activity = DI::activity();
210 if (empty($item['verb']) || $activity->isHidden($item['verb'])) {
214 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
215 if ($activity->match($item['verb'], Activity::FOLLOW) &&
216 $item['object-type'] === Activity\ObjectType::NOTE &&
217 empty($item['self']) &&
218 $item['uid'] == local_user()) {
225 function conv_get_blocklist()
231 $str_blocked = str_replace(["\n", "\r"], ",", DI::pConfig()->get(local_user(), 'system', 'blocked'));
232 if (empty($str_blocked)) {
238 foreach (explode(',', $str_blocked) as $entry) {
239 $cid = Contact::getIdForURL(trim($entry), 0, false);
249 * "Render" a conversation or list of items for HTML display.
250 * There are two major forms of display:
251 * - Sequential or unthreaded ("New Item View" or search results)
252 * - conversation view
253 * The $mode parameter decides between the various renderings and also
254 * figures out how to determine page owner and other contextual items
255 * that are based on unique features of the calling module.
257 * @param array $items
260 * @param bool $preview
261 * @param string $order
264 * @throws ImagickException
265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
267 function conversation(App $a, array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
269 DI::profiler()->startRecording('rendering');
272 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
273 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
274 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
275 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
277 $ssl_state = (local_user() ? true : false);
279 $live_update_div = '';
281 $blocklist = conv_get_blocklist();
283 $previewing = (($preview) ? ' preview ' : '');
285 if ($mode === 'network') {
286 $items = conversation_add_children($items, false, $order, $uid);
289 * The special div is needed for liveUpdate to kick in for this page.
290 * We only launch liveUpdate if you aren't filtering in some incompatible
291 * way and also you aren't writing a comment (discovered in javascript).
293 $live_update_div = '<div id="live-network"></div>' . "\r\n"
294 . "<script> var profile_uid = " . $_SESSION['uid']
295 . "; var netargs = '" . substr(DI::args()->getCommand(), 8)
297 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
298 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
299 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
300 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
301 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
302 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
303 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
304 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
305 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
306 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
307 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
309 . "'; </script>\r\n";
311 } elseif ($mode === 'profile') {
312 $items = conversation_add_children($items, false, $order, $uid);
316 if (!empty($_GET['tab'])) {
317 $tab = Strings::escapeTags(trim($_GET['tab']));
319 if ($tab === 'posts') {
321 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
322 * because browser prefetching might change it on us. We have to deliver it with the page.
325 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
326 . "<script> var profile_uid = " . $uid
327 . "; var netargs = '?f='; </script>\r\n";
330 } elseif ($mode === 'notes') {
331 $items = conversation_add_children($items, false, $order, local_user());
334 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
335 . "<script> var profile_uid = " . local_user()
336 . "; var netargs = '/?f='; </script>\r\n";
338 } elseif ($mode === 'display') {
339 $items = conversation_add_children($items, false, $order, $uid);
342 $live_update_div = '<div id="live-display"></div>' . "\r\n"
343 . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
346 } elseif ($mode === 'community') {
347 $items = conversation_add_children($items, true, $order, $uid);
350 $live_update_div = '<div id="live-community"></div>' . "\r\n"
351 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 10)
353 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
354 . "'; </script>\r\n";
356 } elseif ($mode === 'contacts') {
357 $items = conversation_add_children($items, false, $order, $uid);
360 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
361 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 8)
362 ."/?f='; </script>\r\n";
364 } elseif ($mode === 'search') {
365 $live_update_div = '<div id="live-search"></div>' . "\r\n";
368 $page_dropping = ((local_user() && local_user() == $uid) ? true : false);
371 $_SESSION['return_path'] = DI::args()->getQueryString();
374 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
375 Hook::callAll('conversation_start', $cb);
377 $items = $cb['items'];
388 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
389 unset($conv_responses['dislike']);
392 // array with html for each thread (parent+comments)
396 $page_template = Renderer::getMarkupTemplate("conversation.tpl");
398 if (!empty($items)) {
399 if (in_array($mode, ['community', 'contacts'])) {
402 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
409 if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
412 * "New Item View" on network page or search page results
413 * - just loop through the items and format them minimally for display
416 $tpl = 'search_item.tpl';
418 foreach ($items as $item) {
420 if (!visible_activity($item)) {
424 if (in_array($item['author-id'], $blocklist)) {
430 // prevent private email from leaking.
431 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
435 $profile_name = $item['author-name'];
436 if (!empty($item['author-link']) && empty($item['author-name'])) {
437 $profile_name = $item['author-link'];
440 $tags = Tag::populateFromItem($item);
442 $author = ['uid' => 0, 'id' => $item['author-id'],
443 'network' => $item['author-network'], 'url' => $item['author-link']];
444 $profile_link = Contact::magicLinkByContact($author);
447 if (strpos($profile_link, 'redir/') === 0) {
448 $sparkle = ' sparkle';
451 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
452 Hook::callAll('render_location', $locate);
453 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
455 localize_item($item);
456 if ($mode === 'filed') {
463 'dropping' => $dropping,
464 'pagedrop' => $page_dropping,
465 'select' => DI::l10n()->t('Select'),
466 'delete' => DI::l10n()->t('Delete'),
476 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
477 unset($likebuttons['dislike']);
480 $body_html = Item::prepareBody($item, true, $preview);
482 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
484 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
485 $title = ucfirst($item['content-warning']);
487 $title = $item['title'];
492 'id' => ($preview ? 'P0' : $item['id']),
493 'guid' => ($preview ? 'Q0' : $item['guid']),
494 'commented' => $item['commented'],
495 'received' => $item['received'],
496 'created_date' => $item['created'],
497 'uriid' => $item['uri-id'],
498 'network' => $item['network'],
499 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
500 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link']),
501 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
502 'profile_url' => $profile_link,
503 'item_photo_menu_html' => item_photo_menu($item),
504 'name' => $profile_name,
505 'sparkle' => $sparkle,
507 'thumb' => DI::baseUrl()->remove(Contact::getAvatarUrlForUrl($item['author-link'], $item['uid'], Proxy::SIZE_THUMB)),
509 'body_html' => $body_html,
510 'tags' => $tags['tags'],
511 'hashtags' => $tags['hashtags'],
512 'mentions' => $tags['mentions'],
513 'implicit_mentions' => $tags['implicit_mentions'],
514 'txt_cats' => DI::l10n()->t('Categories:'),
515 'txt_folders' => DI::l10n()->t('Filed under:'),
516 'has_cats' => ((count($categories)) ? 'true' : ''),
517 'has_folders' => ((count($folders)) ? 'true' : ''),
518 'categories' => $categories,
519 'folders' => $folders,
520 'text' => strip_tags($body_html),
521 'localtime' => DateTimeFormat::local($item['created'], 'r'),
522 'ago' => (($item['app']) ? DI::l10n()->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
523 'location_html' => $location_html,
527 'owner_photo' => DI::baseUrl()->remove(Contact::getAvatarUrlForUrl($item['owner-link'], $item['uid'], Proxy::SIZE_THUMB)),
528 'plink' => Item::getPlink($item),
530 'isstarred' => 'unstarred',
533 'vote' => $likebuttons,
535 'dislike_html' => '',
536 'comment_html' => '',
537 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> DI::l10n()->t('View in context')]),
538 'previewing' => $previewing,
539 'wait' => DI::l10n()->t('Please wait'),
543 $arr = ['item' => $item, 'output' => $tmp_item];
544 Hook::callAll('display_item', $arr);
546 $threads[$threadsid]['id'] = $item['id'];
547 $threads[$threadsid]['network'] = $item['network'];
548 $threads[$threadsid]['items'] = [$arr['output']];
553 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
555 $conv = new Thread($mode, $preview, $writable);
558 * get all the topmost parents
559 * this shouldn't be needed, as we should have only them in our array
560 * But for now, this array respects the old style, just in case
562 foreach ($items as $item) {
563 if (in_array($item['author-id'], $blocklist)) {
567 // Can we put this after the visibility check?
568 builtin_activity_puller($item, $conv_responses);
570 // Only add what is visible
571 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
575 if (!visible_activity($item)) {
579 /// @todo Check if this call is needed or not
580 $arr = ['item' => $item];
581 Hook::callAll('display_item', $arr);
583 $item['pagedrop'] = $page_dropping;
585 if ($item['gravity'] == GRAVITY_PARENT) {
586 $item_object = new PostObject($item);
587 $conv->addParent($item_object);
591 $threads = $conv->getTemplateData($conv_responses);
593 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
599 $o = Renderer::replaceMacros($page_template, [
600 '$baseurl' => DI::baseUrl()->get($ssl_state),
601 '$return_path' => DI::args()->getQueryString(),
602 '$live_update' => $live_update_div,
603 '$remove' => DI::l10n()->t('remove'),
605 '$update' => $update,
606 '$threads' => $threads,
607 '$dropping' => ($page_dropping ? DI::l10n()->t('Delete Selected Items') : False),
610 DI::profiler()->stopRecording();
615 * Adds some information (Causer, post reason, direction) to the fetched post row.
617 * @param array $row Post row
618 * @param array $activity Contact data of the resharer
620 * @return array items with parents and comments
622 function conversation_add_row_information(array $row, array $activity) {
623 DI::profiler()->startRecording('rendering');
625 if ($row['uid'] == 0) {
626 $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
629 if (!empty($activity)) {
630 if (($row['gravity'] == GRAVITY_PARENT)) {
631 $row['post-reason'] = Item::PR_ANNOUNCEMENT;
632 $row = array_merge($row, $activity);
633 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
634 $row['causer-link'] = $contact['url'];
635 $row['causer-avatar'] = $contact['thumb'];
636 $row['causer-name'] = $contact['name'];
637 } elseif (($row['gravity'] == GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
638 ($row['author-id'] == $activity['causer-id'])) {
643 switch ($row['post-reason']) {
645 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'to')];
648 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'cc')];
651 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bto')];
654 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bcc')];
656 case Item::PR_FOLLOWER:
657 $row['direction'] = ['direction' => 6, 'title' => DI::l10n()->t('You are following %s.', $row['author-name'])];
660 $row['direction'] = ['direction' => 4, 'title' => DI::l10n()->t('Tagged')];
662 case Item::PR_ANNOUNCEMENT:
663 if (!empty($row['causer-id']) && DI::pConfig()->get(local_user(), 'system', 'display_resharer')) {
664 $row['owner-id'] = $row['causer-id'];
665 $row['owner-link'] = $row['causer-link'];
666 $row['owner-avatar'] = $row['causer-avatar'];
667 $row['owner-name'] = $row['causer-name'];
670 if (($row['gravity'] == GRAVITY_PARENT) && !empty($row['causer-id'])) {
671 $causer = ['uid' => 0, 'id' => $row['causer-id'],
672 'network' => $row['causer-network'], 'url' => $row['causer-link']];
673 $row['reshared'] = DI::l10n()->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
675 $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']))];
677 case Item::PR_COMMENT:
678 $row['direction'] = ['direction' => 5, 'title' => DI::l10n()->t('%s is participating in this thread.', $row['author-name'])];
680 case Item::PR_STORED:
681 $row['direction'] = ['direction' => 8, 'title' => DI::l10n()->t('Stored')];
683 case Item::PR_GLOBAL:
684 $row['direction'] = ['direction' => 9, 'title' => DI::l10n()->t('Global')];
687 $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']))];
689 case Item::PR_FETCHED:
690 $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']))];
694 DI::profiler()->stopRecording();
699 * Add comments to top level entries that had been fetched before
701 * The system will fetch the comments for the local user whenever possible.
702 * This behaviour is currently needed to allow commenting on Friendica posts.
704 * @param array $parents Parent items
706 * @param $block_authors
709 * @return array items with parents and comments
710 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
712 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
713 DI::profiler()->startRecording('rendering');
714 if (count($parents) > 1) {
715 $max_comments = DI::config()->get('system', 'max_comments', 100);
717 $max_comments = DI::config()->get('system', 'max_display_comments', 1000);
720 $params = ['order' => ['uri-id' => true, 'uid' => true]];
724 $commentcounter = [];
725 $activitycounter = [];
727 foreach ($parents AS $parent) {
728 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == GRAVITY_ACTIVITY)) {
729 $uriid = $parent['thr-parent-id'];
730 if (!empty($parent['author-id'])) {
731 $activities[$uriid] = ['causer-id' => $parent['author-id']];
732 foreach (['commented', 'received', 'created'] as $orderfields) {
733 if (!empty($parent[$orderfields])) {
734 $activities[$uriid][$orderfields] = $parent[$orderfields];
739 $uriid = $parent['uri-id'];
743 $commentcounter[$uriid] = 0;
744 $activitycounter[$uriid] = 0;
747 $condition = ['parent-uri-id' => $uriids];
748 if ($block_authors) {
749 $condition['author-hidden'] = false;
752 $condition = DBA::mergeConditions($condition,
753 ["`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW)]);
755 $thread_items = Post::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['pinned', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
759 while ($row = Post::fetch($thread_items)) {
760 if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
764 if ($max_comments > 0) {
765 if (($row['gravity'] == GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
768 if (($row['gravity'] == GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
772 $items[$row['uri-id']] = conversation_add_row_information($row, $activities[$row['uri-id']] ?? []);
775 DBA::close($thread_items);
777 $items = conv_sort($items, $order);
779 DI::profiler()->stopRecording();
783 function item_photo_menu($item)
785 DI::profiler()->startRecording('rendering');
796 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
797 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
800 $author = ['uid' => 0, 'id' => $item['author-id'],
801 'network' => $item['author-network'], 'url' => $item['author-link']];
802 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
803 $sparkle = (strpos($profile_link, 'redir/') === 0);
806 $pcid = $item['author-id'];
809 $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
810 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
811 if (DBA::isResult($contact)) {
812 $cid = $contact['id'];
813 $network = $contact['network'];
814 $rel = $contact['rel'];
818 $status_link = $profile_link . '/status';
819 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
820 $profile_link = $profile_link . '/profile';
824 $contact_url = 'contact/' . $pcid;
825 $posts_link = $contact_url . '/posts';
826 $block_link = $item['self'] ? '' : $contact_url . '/block';
827 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore';
830 if ($cid && !$item['self']) {
831 $contact_url = 'contact/' . $cid;
832 $poke_link = $contact_url . '/poke';
833 $posts_link = $contact_url . '/posts';
835 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
836 $pm_url = 'message/new/' . $cid;
842 DI::l10n()->t('Follow Thread') => $sub_link,
843 DI::l10n()->t('View Status') => $status_link,
844 DI::l10n()->t('View Profile') => $profile_link,
845 DI::l10n()->t('View Photos') => $photos_link,
846 DI::l10n()->t('Network Posts') => $posts_link,
847 DI::l10n()->t('View Contact') => $contact_url,
848 DI::l10n()->t('Send PM') => $pm_url,
849 DI::l10n()->t('Block') => $block_link,
850 DI::l10n()->t('Ignore') => $ignore_link
853 if (!empty($item['language'])) {
854 $menu[DI::l10n()->t('Languages')] = 'javascript:alert(\'' . Item::getLanguageMessage($item) . '\');';
857 if ($network == Protocol::DFRN) {
858 $menu[DI::l10n()->t("Poke")] = $poke_link;
861 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
862 in_array($item['network'], Protocol::FEDERATED)) {
863 $menu[DI::l10n()->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
866 $menu = [DI::l10n()->t('View Profile') => $item['author-link']];
869 $args = ['item' => $item, 'menu' => $menu];
871 Hook::callAll('item_photo_menu', $args);
873 $menu = $args['menu'];
876 foreach ($menu as $k => $v) {
877 if (strpos($v, 'javascript:') === 0) {
879 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
881 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
884 DI::profiler()->stopRecording();
889 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
891 * Increments the count of each matching activity and adds a link to the author as needed.
893 * @param array $activity
894 * @param array &$conv_responses (already created with builtin activity structure)
896 * @throws ImagickException
897 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
899 function builtin_activity_puller(array $activity, array &$conv_responses)
901 foreach ($conv_responses as $mode => $v) {
906 $verb = Activity::LIKE;
909 $verb = Activity::DISLIKE;
912 $verb = Activity::ATTEND;
915 $verb = Activity::ATTENDNO;
918 $verb = Activity::ATTENDMAYBE;
921 $verb = Activity::ANNOUNCE;
927 if (!empty($activity['verb']) && DI::activity()->match($activity['verb'], $verb) && ($activity['gravity'] != GRAVITY_PARENT)) {
930 'id' => $activity['author-id'],
931 'network' => $activity['author-network'],
932 'url' => $activity['author-link']
934 $url = Contact::magicLinkByContact($author);
935 if (strpos($url, 'redir/') === 0) {
936 $sparkle = ' class="sparkle" ';
939 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
941 if (empty($activity['thr-parent-id'])) {
942 $activity['thr-parent-id'] = $activity['parent-uri-id'];
945 // Skip when the causer of the parent is the same than the author of the announce
946 if (($verb == Activity::ANNOUNCE) && Post::exists(['uri-id' => $activity['thr-parent-id'],
947 'uid' => $activity['uid'], 'causer-id' => $activity['author-id'], 'gravity' => GRAVITY_PARENT])) {
951 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
952 $conv_responses[$mode][$activity['thr-parent-id']] = [
956 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
957 // only list each unique author once
961 if (public_contact() == $activity['author-id']) {
962 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
965 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
967 // there can only be one activity verb per item so if we found anything, we can stop looking
974 * Format the activity text for an item/photo/video
976 * @param array $links = array of pre-linked names of actors
977 * @param string $verb = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
978 * @param int $id = item id
979 * @return string formatted text
980 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
982 function format_activity(array $links, $verb, $id) {
983 DI::profiler()->startRecording('rendering');
988 $total = count($links);
992 // Phrase if there is only one liker. In other cases it will be uses for the expanded
993 // list which show all likers
996 $phrase = DI::l10n()->t('%s likes this.', $likers);
999 $phrase = DI::l10n()->t('%s doesn\'t like this.', $likers);
1002 $phrase = DI::l10n()->t('%s attends.', $likers);
1005 $phrase = DI::l10n()->t('%s doesn\'t attend.', $likers);
1007 case 'attendmaybe' :
1008 $phrase = DI::l10n()->t('%s attends maybe.', $likers);
1011 $phrase = DI::l10n()->t('%s reshared this.', $likers);
1014 } elseif ($total > 1) {
1015 if ($total < MAX_LIKERS) {
1016 $likers = implode(', ', array_slice($links, 0, -1));
1017 $likers .= ' ' . DI::l10n()->t('and') . ' ' . $links[count($links)-1];
1019 $likers = implode(', ', array_slice($links, 0, MAX_LIKERS - 1));
1020 $likers .= ' ' . DI::l10n()->t('and %d other people', $total - MAX_LIKERS);
1023 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
1028 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> like this', $spanatts, $total);
1029 $explikers = DI::l10n()->t('%s like this.', $likers);
1032 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $total);
1033 $explikers = DI::l10n()->t('%s don\'t like this.', $likers);
1036 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend', $spanatts, $total);
1037 $explikers = DI::l10n()->t('%s attend.', $likers);
1040 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $total);
1041 $explikers = DI::l10n()->t('%s don\'t attend.', $likers);
1044 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $total);
1045 $explikers = DI::l10n()->t('%s attend maybe.', $likers);
1048 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> reshared this', $spanatts, $total);
1049 $explikers = DI::l10n()->t('%s reshared this.', $likers);
1053 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1056 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1057 '$phrase' => $phrase,
1063 DI::profiler()->stopRecording();
1067 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1069 DI::profiler()->startRecording('rendering');
1072 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1074 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1075 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
1076 '$newpost' => 'true',
1077 '$baseurl' => DI::baseUrl()->get(true),
1078 '$geotag' => $geotag,
1079 '$nickname' => $x['nickname'],
1080 '$ispublic' => DI::l10n()->t('Visible to <strong>everybody</strong>'),
1081 '$linkurl' => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1082 '$term' => DI::l10n()->t('Tag term:'),
1083 '$fileas' => DI::l10n()->t('Save to Folder:'),
1084 '$whereareu' => DI::l10n()->t('Where are you right now?'),
1085 '$delitems' => DI::l10n()->t("Delete item\x28s\x29?"),
1086 '$is_mobile' => DI::mode()->isMobile(),
1090 Hook::callAll('jot_tool', $jotplugins);
1092 $tpl = Renderer::getMarkupTemplate("jot.tpl");
1094 $o .= Renderer::replaceMacros($tpl, [
1095 '$new_post' => DI::l10n()->t('New Post'),
1096 '$return_path' => DI::args()->getQueryString(),
1097 '$action' => 'item',
1098 '$share' => ($x['button'] ?? '') ?: DI::l10n()->t('Share'),
1099 '$loading' => DI::l10n()->t('Loading...'),
1100 '$upload' => DI::l10n()->t('Upload photo'),
1101 '$shortupload' => DI::l10n()->t('upload photo'),
1102 '$attach' => DI::l10n()->t('Attach file'),
1103 '$shortattach' => DI::l10n()->t('attach file'),
1104 '$edbold' => DI::l10n()->t('Bold'),
1105 '$editalic' => DI::l10n()->t('Italic'),
1106 '$eduline' => DI::l10n()->t('Underline'),
1107 '$edquote' => DI::l10n()->t('Quote'),
1108 '$edcode' => DI::l10n()->t('Code'),
1109 '$edimg' => DI::l10n()->t('Image'),
1110 '$edurl' => DI::l10n()->t('Link'),
1111 '$edattach' => DI::l10n()->t('Link or Media'),
1112 '$edvideo' => DI::l10n()->t('Video'),
1113 '$setloc' => DI::l10n()->t('Set your location'),
1114 '$shortsetloc' => DI::l10n()->t('set location'),
1115 '$noloc' => DI::l10n()->t('Clear browser location'),
1116 '$shortnoloc' => DI::l10n()->t('clear location'),
1117 '$title' => $x['title'] ?? '',
1118 '$placeholdertitle' => DI::l10n()->t('Set title'),
1119 '$category' => $x['category'] ?? '',
1120 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1121 '$scheduled_at' => Temporal::getDateTimeField(
1123 DateTime::createFromFormat(DateTimeFormat::MYSQL, DateTimeFormat::local('now + 6 months')),
1125 DI::l10n()->t('Scheduled at'),
1128 '$wait' => DI::l10n()->t('Please wait'),
1129 '$permset' => DI::l10n()->t('Permission settings'),
1130 '$shortpermset' => DI::l10n()->t('Permissions'),
1131 '$wall' => $notes_cid ? 0 : 1,
1132 '$posttype' => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1133 '$content' => $x['content'] ?? '',
1134 '$post_id' => $x['post_id'] ?? '',
1135 '$baseurl' => DI::baseUrl()->get(true),
1136 '$defloc' => $x['default_location'],
1137 '$visitor' => $x['visitor'],
1138 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
1139 '$public' => DI::l10n()->t('Public post'),
1140 '$lockstate' => $x['lockstate'],
1141 '$bang' => $x['bang'],
1142 '$profile_uid' => $x['profile_uid'],
1143 '$preview' => DI::l10n()->t('Preview'),
1144 '$jotplugins' => $jotplugins,
1145 '$notes_cid' => $notes_cid,
1146 '$cancel' => DI::l10n()->t('Cancel'),
1147 '$rand_num' => Crypto::randomDigits(12),
1149 // ACL permissions box
1150 '$acl' => $x['acl'],
1152 //jot nav tab (used in some themes)
1153 '$message' => DI::l10n()->t('Message'),
1154 '$browser' => DI::l10n()->t('Browser'),
1156 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1160 if ($popup == true) {
1161 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1164 DI::profiler()->stopRecording();
1169 * Plucks the children of the given parent from a given item list.
1171 * @param array $item_list
1172 * @param array $parent
1173 * @param bool $recursive
1176 function get_item_children(array &$item_list, array $parent, $recursive = true)
1178 DI::profiler()->startRecording('rendering');
1180 foreach ($item_list as $i => $item) {
1181 if ($item['gravity'] != GRAVITY_PARENT) {
1183 // Fallback to parent-uri if thr-parent is not set
1184 $thr_parent = $item['thr-parent-id'];
1185 if ($thr_parent == '') {
1186 $thr_parent = $item['parent-uri-id'];
1189 if ($thr_parent == $parent['uri-id']) {
1190 $item['children'] = get_item_children($item_list, $item);
1191 $children[] = $item;
1192 unset($item_list[$i]);
1194 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1195 $children[] = $item;
1196 unset($item_list[$i]);
1200 DI::profiler()->stopRecording();
1205 * Recursively sorts a tree-like item array
1207 * @param array $items
1210 function sort_item_children(array $items)
1212 DI::profiler()->startRecording('rendering');
1214 usort($result, 'sort_thr_received_rev');
1215 foreach ($result as $k => $i) {
1216 if (isset($result[$k]['children'])) {
1217 $result[$k]['children'] = sort_item_children($result[$k]['children']);
1220 DI::profiler()->stopRecording();
1225 * Recursively add all children items at the top level of a list
1227 * @param array $children List of items to append
1228 * @param array $item_list
1230 function add_children_to_list(array $children, array &$item_list)
1232 foreach ($children as $child) {
1233 $item_list[] = $child;
1234 if (isset($child['children'])) {
1235 add_children_to_list($child['children'], $item_list);
1241 * Selectively flattens a tree-like item structure to prevent threading stairs
1243 * This recursive function takes the item tree structure created by conv_sort() and
1244 * flatten the extraneous depth levels when people reply sequentially, removing the
1245 * stairs effect in threaded conversations limiting the available content width.
1247 * The basic principle is the following: if a post item has only one reply and is
1248 * the last reply of its parent, then the reply is moved to the parent.
1250 * This process is rendered somewhat more complicated because items can be either
1251 * replies or likes, and these don't factor at all in the reply count/last reply.
1253 * @param array $parent A tree-like array of items
1256 function smart_flatten_conversation(array $parent)
1258 DI::profiler()->startRecording('rendering');
1259 if (!isset($parent['children']) || count($parent['children']) == 0) {
1260 DI::profiler()->stopRecording();
1264 // We use a for loop to ensure we process the newly-moved items
1265 for ($i = 0; $i < count($parent['children']); $i++) {
1266 $child = $parent['children'][$i];
1268 if (isset($child['children']) && count($child['children'])) {
1269 // This helps counting only the regular posts
1270 $count_post_closure = function($var) {
1271 DI::profiler()->stopRecording();
1272 return $var['verb'] === Activity::POST;
1275 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1277 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1279 // If there's only one child's children post and this is the last child post
1280 if ($child_post_count == 1 && $remaining_post_count == 1) {
1282 // Searches the post item in the children
1284 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1288 $moved_item = $child['children'][$j];
1289 unset($parent['children'][$i]['children'][$j]);
1290 $parent['children'][] = $moved_item;
1292 $parent['children'][$i] = smart_flatten_conversation($child);
1297 DI::profiler()->stopRecording();
1303 * Expands a flat list of items into corresponding tree-like conversation structures.
1305 * sort the top-level posts either on "received" or "commented", and finally
1306 * append all the items at the top level (???)
1308 * @param array $item_list A list of items belonging to one or more conversations
1309 * @param string $order Either on "received" or "commented"
1311 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1313 function conv_sort(array $item_list, $order)
1315 DI::profiler()->startRecording('rendering');
1318 if (!(is_array($item_list) && count($item_list))) {
1319 DI::profiler()->stopRecording();
1323 $blocklist = conv_get_blocklist();
1327 // Dedupes the item list on the uri to prevent infinite loops
1328 foreach ($item_list as $item) {
1329 if (in_array($item['author-id'], $blocklist)) {
1333 $item_array[$item['uri-id']] = $item;
1336 // Extract the top level items
1337 foreach ($item_array as $item) {
1338 if ($item['gravity'] == GRAVITY_PARENT) {
1343 if (stristr($order, 'pinned_received')) {
1344 usort($parents, 'sort_thr_pinned_received');
1345 } elseif (stristr($order, 'received')) {
1346 usort($parents, 'sort_thr_received');
1347 } elseif (stristr($order, 'commented')) {
1348 usort($parents, 'sort_thr_commented');
1352 * Plucks children from the item_array, second pass collects eventual orphan
1353 * items and add them as children of their top-level post.
1355 foreach ($parents as $i => $parent) {
1356 $parents[$i]['children'] =
1357 array_merge(get_item_children($item_array, $parent, true),
1358 get_item_children($item_array, $parent, false));
1361 foreach ($parents as $i => $parent) {
1362 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1365 if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
1366 foreach ($parents as $i => $parent) {
1367 $parents[$i] = smart_flatten_conversation($parent);
1371 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1372 /// However, this apparently ensures responses (likes, attendance) display (?!)
1373 foreach ($parents as $parent) {
1374 if (count($parent['children'])) {
1375 add_children_to_list($parent['children'], $parents);
1379 DI::profiler()->stopRecording();
1384 * usort() callback to sort item arrays by pinned and the received key
1390 function sort_thr_pinned_received(array $a, array $b)
1392 if ($b['pinned'] && !$a['pinned']) {
1394 } elseif (!$b['pinned'] && $a['pinned']) {
1398 return strcmp($b['received'], $a['received']);
1402 * usort() callback to sort item arrays by the received key
1408 function sort_thr_received(array $a, array $b)
1410 return strcmp($b['received'], $a['received']);
1414 * usort() callback to reverse sort item arrays by the received key
1420 function sort_thr_received_rev(array $a, array $b)
1422 return strcmp($a['received'], $b['received']);
1426 * usort() callback to sort item arrays by the commented key
1432 function sort_thr_commented(array $a, array $b)
1434 return strcmp($b['commented'], $a['commented']);