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\Content\Text\BBCode;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Session;
31 use Friendica\Core\Theme;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Post;
37 use Friendica\Model\Profile;
38 use Friendica\Model\Tag;
39 use Friendica\Model\Verb;
40 use Friendica\Object\Post as PostObject;
41 use Friendica\Object\Thread;
42 use Friendica\Protocol\Activity;
43 use Friendica\Util\Crypto;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Strings;
46 use Friendica\Util\Temporal;
47 use Friendica\Util\XML;
49 function item_extract_images($body) {
56 $img_start = strpos($orig_body, '[img');
57 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
58 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
59 while (($img_st_close !== false) && ($img_end !== false)) {
61 $img_st_close++; // make it point to AFTER the closing bracket
62 $img_end += $img_start;
64 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
65 // This is an embedded image
67 $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
68 $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
72 $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
75 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
77 if ($orig_body === false) {
78 // in case the body ends on a closing image tag
82 $img_start = strpos($orig_body, '[img');
83 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
84 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
87 $new_body = $new_body . $orig_body;
89 return ['body' => $new_body, 'images' => $saved_image];
92 function item_redir_and_replace_images($body, $images, $cid) {
98 $pos = BBCode::getTagPosition($origbody, 'url', 0);
99 while ($pos !== false && $cnt < 1000) {
101 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
102 $replace = '[url=' . DI::baseUrl() . '/redir/' . $cid
103 . '?url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
105 $newbody .= substr($origbody, 0, $pos['start']['open']);
106 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
107 $origbody = substr($origbody, $pos['end']['close']);
108 if ($origbody === false) {
112 $subject = preg_replace($search, $replace, $subject);
113 $newbody .= $subject;
116 // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
117 $pos = BBCode::getTagPosition($origbody, 'url', 0);
119 $newbody .= $origbody;
122 foreach ($images as $image) {
124 * We're depending on the property of 'foreach' (specified on the PHP website) that
125 * it loops over the array starting from the first element and going sequentially
126 * to the last element.
128 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
135 * Render actions localized
138 * @throws ImagickException
139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
141 function localize_item(&$item)
143 $extracted = item_extract_images($item['body']);
144 if ($extracted['images']) {
145 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
148 /// @todo The following functionality needs to be cleaned up.
149 if (!empty($item['verb'])) {
150 $activity = DI::activity();
152 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
154 if (stristr($item['verb'], Activity::POKE)) {
155 $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
159 if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
163 $obj = XML::parseString($xmlhead . $item['object']);
165 $Bname = $obj->title;
169 foreach ($obj->link as $l) {
170 $atts = $l->attributes();
171 switch ($atts['rel']) {
172 case "alternate": $Blink = $atts['href'];
173 case "photo": $Bphoto = $atts['href'];
177 $author = ['uid' => 0, 'id' => $item['author-id'],
178 'network' => $item['author-network'], 'url' => $item['author-link']];
179 $A = '[url=' . Contact::magicLinkByContact($author) . ']' . $item['author-name'] . '[/url]';
181 if (!empty($Blink)) {
182 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
187 if ($Bphoto != "" && !empty($Blink)) {
188 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
192 * we can't have a translation string with three positions but no distinguishable text
193 * So here is the translate string.
195 $txt = DI::l10n()->t('%1$s poked %2$s');
197 // now translate the verb
198 $poked_t = trim(sprintf($txt, '', ''));
199 $txt = str_replace($poked_t, DI::l10n()->t($verb), $txt);
201 // then do the sprintf on the translation string
203 $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
207 if ($activity->match($item['verb'], Activity::TAG)) {
208 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
209 'verb', 'object-type', 'resource-id', 'body', 'plink'];
210 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
211 if (!DBA::isResult($obj)) {
215 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
216 'network' => $item['author-network'], 'url' => $item['author-link']];
217 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
219 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
220 'network' => $obj['author-network'], 'url' => $obj['author-link']];
221 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
223 switch ($obj['verb']) {
225 switch ($obj['object-type']) {
226 case Activity\ObjectType::EVENT:
227 $post_type = DI::l10n()->t('event');
230 $post_type = DI::l10n()->t('status');
234 if ($obj['resource-id']) {
235 $post_type = DI::l10n()->t('photo');
236 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
237 $rr['plink'] = $m[1];
239 $post_type = DI::l10n()->t('status');
241 // Let's break everthing ... ;-)
244 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
246 $parsedobj = XML::parseString($xmlhead . $item['object']);
248 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
249 $item['body'] = DI::l10n()->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
254 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
255 foreach ($matches as $mtch) {
256 if (!strpos($mtch[1], 'zrl=')) {
257 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
262 // add zrl's to public images
263 $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
264 if (preg_match($photo_pattern, $item['body'])) {
265 $photo_replace = '[url=' . Profile::zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' , true) . '][img' . '$4' . ']h' . '$5' . '[/img][/url]';
266 $item['body'] = BBCode::pregReplaceInTag($photo_pattern, $photo_replace, 'url', $item['body']);
269 // add sparkle links to appropriate permalinks
270 // Only create a redirection to a magic link when logged in
271 if (!empty($item['plink']) && Session::isAuthenticated()) {
272 $author = ['uid' => 0, 'id' => $item['author-id'],
273 'network' => $item['author-network'], 'url' => $item['author-link']];
274 $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
279 * Count the total of comments on this item and its desendants
280 * @TODO proper type-hint + doc-tag
284 function count_descendants($item) {
285 $total = count($item['children']);
288 foreach ($item['children'] as $child) {
289 if (!visible_activity($child)) {
292 $total += count_descendants($child);
299 function visible_activity($item) {
301 $activity = DI::activity();
303 if (empty($item['verb']) || $activity->isHidden($item['verb'])) {
307 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
308 if ($activity->match($item['verb'], Activity::FOLLOW) &&
309 $item['object-type'] === Activity\ObjectType::NOTE &&
310 empty($item['self']) &&
311 $item['uid'] == local_user()) {
318 function conv_get_blocklist()
324 $str_blocked = str_replace(["\n", "\r"], ",", DI::pConfig()->get(local_user(), 'system', 'blocked'));
325 if (empty($str_blocked)) {
331 foreach (explode(',', $str_blocked) as $entry) {
332 $cid = Contact::getIdForURL(trim($entry), 0, false);
342 * "Render" a conversation or list of items for HTML display.
343 * There are two major forms of display:
344 * - Sequential or unthreaded ("New Item View" or search results)
345 * - conversation view
346 * The $mode parameter decides between the various renderings and also
347 * figures out how to determine page owner and other contextual items
348 * that are based on unique features of the calling module.
350 * @param array $items
353 * @param bool $preview
354 * @param string $order
357 * @throws ImagickException
358 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
360 function conversation(App $a, array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
364 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
365 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
366 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
367 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
369 $ssl_state = (local_user() ? true : false);
372 $live_update_div = '';
374 $blocklist = conv_get_blocklist();
376 $previewing = (($preview) ? ' preview ' : '');
378 if ($mode === 'network') {
379 $items = conversation_add_children($items, false, $order, $uid);
380 $profile_owner = local_user();
383 * The special div is needed for liveUpdate to kick in for this page.
384 * We only launch liveUpdate if you aren't filtering in some incompatible
385 * way and also you aren't writing a comment (discovered in javascript).
387 $live_update_div = '<div id="live-network"></div>' . "\r\n"
388 . "<script> var profile_uid = " . $_SESSION['uid']
389 . "; var netargs = '" . substr(DI::args()->getCommand(), 8)
391 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
392 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
393 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
394 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
395 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
396 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
397 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
398 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
399 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
400 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
401 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
403 . "'; </script>\r\n";
405 } elseif ($mode === 'profile') {
406 $items = conversation_add_children($items, false, $order, $uid);
407 $profile_owner = $a->profile['uid'];
411 if (!empty($_GET['tab'])) {
412 $tab = Strings::escapeTags(trim($_GET['tab']));
414 if ($tab === 'posts') {
416 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
417 * because browser prefetching might change it on us. We have to deliver it with the page.
420 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
421 . "<script> var profile_uid = " . $a->profile['uid']
422 . "; var netargs = '?f='; </script>\r\n";
425 } elseif ($mode === 'notes') {
426 $items = conversation_add_children($items, false, $order, local_user());
427 $profile_owner = local_user();
430 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
431 . "<script> var profile_uid = " . local_user()
432 . "; var netargs = '/?f='; </script>\r\n";
434 } elseif ($mode === 'display') {
435 $items = conversation_add_children($items, false, $order, $uid);
436 $profile_owner = $a->profile['uid'];
439 $live_update_div = '<div id="live-display"></div>' . "\r\n"
440 . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
443 } elseif ($mode === 'community') {
444 $items = conversation_add_children($items, true, $order, $uid);
448 $live_update_div = '<div id="live-community"></div>' . "\r\n"
449 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 10)
451 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
452 . "'; </script>\r\n";
454 } elseif ($mode === 'contacts') {
455 $items = conversation_add_children($items, false, $order, $uid);
459 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
460 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 8)
461 ."/?f='; </script>\r\n";
463 } elseif ($mode === 'search') {
464 $live_update_div = '<div id="live-search"></div>' . "\r\n";
467 $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
470 $_SESSION['return_path'] = DI::args()->getQueryString();
473 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
474 Hook::callAll('conversation_start', $cb);
476 $items = $cb['items'];
487 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
488 unset($conv_responses['dislike']);
491 // array with html for each thread (parent+comments)
495 $page_template = Renderer::getMarkupTemplate("conversation.tpl");
497 if (!empty($items)) {
498 if (in_array($mode, ['community', 'contacts'])) {
501 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
508 if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
511 * "New Item View" on network page or search page results
512 * - just loop through the items and format them minimally for display
515 $tpl = 'search_item.tpl';
517 foreach ($items as $item) {
519 if (!visible_activity($item)) {
523 if (in_array($item['author-id'], $blocklist)) {
529 // prevent private email from leaking.
530 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
534 $profile_name = $item['author-name'];
535 if (!empty($item['author-link']) && empty($item['author-name'])) {
536 $profile_name = $item['author-link'];
539 $tags = Tag::populateFromItem($item);
541 $author = ['uid' => 0, 'id' => $item['author-id'],
542 'network' => $item['author-network'], 'url' => $item['author-link']];
543 $profile_link = Contact::magicLinkByContact($author);
546 if (strpos($profile_link, 'redir/') === 0) {
547 $sparkle = ' sparkle';
550 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
551 Hook::callAll('render_location', $locate);
552 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
554 localize_item($item);
555 if ($mode === 'filed') {
562 'dropping' => $dropping,
563 'pagedrop' => $page_dropping,
564 'select' => DI::l10n()->t('Select'),
565 'delete' => DI::l10n()->t('Delete'),
575 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
576 unset($likebuttons['dislike']);
579 $body_html = Item::prepareBody($item, true, $preview);
581 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
583 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
584 $title = ucfirst($item['content-warning']);
586 $title = $item['title'];
591 'id' => ($preview ? 'P0' : $item['id']),
592 'guid' => ($preview ? 'Q0' : $item['guid']),
593 'commented' => $item['commented'],
594 'received' => $item['received'],
595 'created_date' => $item['created'],
596 'uriid' => $item['uri-id'],
597 'network' => $item['network'],
598 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
599 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link']),
600 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
601 'profile_url' => $profile_link,
602 'item_photo_menu_html' => item_photo_menu($item),
603 'name' => $profile_name,
604 'sparkle' => $sparkle,
606 'thumb' => DI::baseUrl()->remove($item['author-avatar']),
608 'body_html' => $body_html,
609 'tags' => $tags['tags'],
610 'hashtags' => $tags['hashtags'],
611 'mentions' => $tags['mentions'],
612 'implicit_mentions' => $tags['implicit_mentions'],
613 'txt_cats' => DI::l10n()->t('Categories:'),
614 'txt_folders' => DI::l10n()->t('Filed under:'),
615 'has_cats' => ((count($categories)) ? 'true' : ''),
616 'has_folders' => ((count($folders)) ? 'true' : ''),
617 'categories' => $categories,
618 'folders' => $folders,
619 'text' => strip_tags($body_html),
620 'localtime' => DateTimeFormat::local($item['created'], 'r'),
621 'ago' => (($item['app']) ? DI::l10n()->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
622 'location_html' => $location_html,
626 'owner_photo' => DI::baseUrl()->remove($item['owner-avatar']),
627 'plink' => Item::getPlink($item),
629 'isstarred' => 'unstarred',
632 'vote' => $likebuttons,
634 'dislike_html' => '',
635 'comment_html' => '',
636 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> DI::l10n()->t('View in context')]),
637 'previewing' => $previewing,
638 'wait' => DI::l10n()->t('Please wait'),
642 $arr = ['item' => $item, 'output' => $tmp_item];
643 Hook::callAll('display_item', $arr);
645 $threads[$threadsid]['id'] = $item['id'];
646 $threads[$threadsid]['network'] = $item['network'];
647 $threads[$threadsid]['items'] = [$arr['output']];
652 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
654 $conv = new Thread($mode, $preview, $writable);
657 * get all the topmost parents
658 * this shouldn't be needed, as we should have only them in our array
659 * But for now, this array respects the old style, just in case
661 foreach ($items as $item) {
662 if (in_array($item['author-id'], $blocklist)) {
666 // Can we put this after the visibility check?
667 builtin_activity_puller($item, $conv_responses);
669 // Only add what is visible
670 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
674 if (!visible_activity($item)) {
678 /// @todo Check if this call is needed or not
679 $arr = ['item' => $item];
680 Hook::callAll('display_item', $arr);
682 $item['pagedrop'] = $page_dropping;
684 if ($item['gravity'] == GRAVITY_PARENT) {
685 $item_object = new PostObject($item);
686 $conv->addParent($item_object);
690 $threads = $conv->getTemplateData($conv_responses);
692 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
698 $o = Renderer::replaceMacros($page_template, [
699 '$baseurl' => DI::baseUrl()->get($ssl_state),
700 '$return_path' => DI::args()->getQueryString(),
701 '$live_update' => $live_update_div,
702 '$remove' => DI::l10n()->t('remove'),
704 '$update' => $update,
706 '$threads' => $threads,
707 '$dropping' => ($page_dropping ? DI::l10n()->t('Delete Selected Items') : False),
714 * Fetch all comments from a query. Additionally set the newest resharer as thread owner.
716 * @param mixed $thread_items Database statement with thread posts
717 * @param boolean $pinned Is the item pinned?
718 * @param array $activity Contact data of the resharer
720 * @return array items with parents and comments
722 function conversation_fetch_comments($thread_items, bool $pinned, array $activity) {
725 while ($row = Post::fetch($thread_items)) {
726 if (!empty($activity)) {
727 if (($row['gravity'] == GRAVITY_PARENT)) {
728 $row['post-reason'] = Item::PR_ANNOUNCEMENT;
729 $row = array_merge($row, $activity);
730 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
731 $row['causer-link'] = $contact['url'];
732 $row['causer-avatar'] = $contact['thumb'];
733 $row['causer-name'] = $contact['name'];
734 } elseif (($row['gravity'] == GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
735 ($row['author-id'] == $activity['causer-id'])) {
740 switch ($row['post-reason']) {
742 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'to')];
745 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'cc')];
748 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bto')];
751 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bcc')];
753 case Item::PR_FOLLOWER:
754 $row['direction'] = ['direction' => 6, 'title' => DI::l10n()->t('You are following %s.', $row['author-name'])];
757 $row['direction'] = ['direction' => 4, 'title' => DI::l10n()->t('Tagged')];
759 case Item::PR_ANNOUNCEMENT:
760 if (!empty($row['causer-id']) && DI::pConfig()->get(local_user(), 'system', 'display_resharer')) {
761 $row['owner-id'] = $row['causer-id'];
762 $row['owner-link'] = $row['causer-link'];
763 $row['owner-avatar'] = $row['causer-avatar'];
764 $row['owner-name'] = $row['causer-name'];
767 if (($row['gravity'] == GRAVITY_PARENT) && !empty($row['causer-id'])) {
768 $causer = ['uid' => 0, 'id' => $row['causer-id'],
769 'network' => $row['causer-network'], 'url' => $row['causer-link']];
770 $row['reshared'] = DI::l10n()->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
772 $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']))];
774 case Item::PR_COMMENT:
775 $row['direction'] = ['direction' => 5, 'title' => DI::l10n()->t('%s is participating in this thread.', $row['author-name'])];
777 case Item::PR_STORED:
778 $row['direction'] = ['direction' => 8, 'title' => DI::l10n()->t('Stored')];
780 case Item::PR_GLOBAL:
781 $row['direction'] = ['direction' => 9, 'title' => DI::l10n()->t('Global')];
784 $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']))];
786 case Item::PR_FETCHED:
787 $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']))];
791 if ($row['gravity'] == GRAVITY_PARENT) {
792 $row['pinned'] = $pinned;
798 DBA::close($thread_items);
804 * Add comments to top level entries that had been fetched before
806 * The system will fetch the comments for the local user whenever possible.
807 * This behaviour is currently needed to allow commenting on Friendica posts.
809 * @param array $parents Parent items
811 * @param $block_authors
814 * @return array items with parents and comments
815 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
817 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
818 if (count($parents) > 1) {
819 $max_comments = DI::config()->get('system', 'max_comments', 100);
821 $max_comments = DI::config()->get('system', 'max_display_comments', 1000);
824 $params = ['order' => ['gravity', 'uid', 'commented' => true]];
826 if ($max_comments > 0) {
827 $params['limit'] = $max_comments;
832 foreach ($parents AS $parent) {
833 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == GRAVITY_ACTIVITY)) {
834 $condition = ["`parent-uri-id` = ? AND `uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
835 $parent['thr-parent-id'], $uid, Verb::getID(Activity::FOLLOW)];
836 if (!empty($parent['author-id'])) {
837 $activity = ['causer-id' => $parent['author-id']];
838 foreach (['commented', 'received', 'created'] as $orderfields) {
839 if (!empty($parent[$orderfields])) {
840 $activity[$orderfields] = $parent[$orderfields];
845 $condition = ["`parent-uri-id` = ? AND `uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
846 $parent['uri-id'], $uid, Verb::getID(Activity::FOLLOW)];
849 $items = conversation_fetch_items($parent, $items, $condition, $block_authors, $params, $activity);
852 foreach ($items as $index => $item) {
853 if ($item['uid'] == 0) {
854 $items[$index]['writable'] = in_array($item['network'], Protocol::FEDERATED);
858 $items = conv_sort($items, $order);
864 * Fetch conversation items
866 * @param array $parent Parent Item array
867 * @param array $items Item array
868 * @param array $condition SQL condition
869 * @param boolean $block_authors Don't show posts from contacts that are hidden (used on the community page)
870 * @param array $params SQL parameters
871 * @param array $activity Contact data of the resharer
874 function conversation_fetch_items(array $parent, array $items, array $condition, bool $block_authors, array $params, array $activity) {
875 if ($block_authors) {
876 $condition[0] .= " AND NOT `author-hidden`";
879 $thread_items = Post::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['pinned', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
881 $comments = conversation_fetch_comments($thread_items, $parent['pinned'] ?? false, $activity);
883 if (count($comments) != 0) {
884 $items = array_merge($items, $comments);
889 function item_photo_menu($item)
901 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
902 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
905 $author = ['uid' => 0, 'id' => $item['author-id'],
906 'network' => $item['author-network'], 'url' => $item['author-link']];
907 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
908 $sparkle = (strpos($profile_link, 'redir/') === 0);
911 $pcid = $item['author-id'];
914 $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
915 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
916 if (DBA::isResult($contact)) {
917 $cid = $contact['id'];
918 $network = $contact['network'];
919 $rel = $contact['rel'];
923 $status_link = $profile_link . '/status';
924 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
925 $profile_link = $profile_link . '/profile';
929 $contact_url = 'contact/' . $pcid;
930 $posts_link = $contact_url . '/posts';
931 $block_link = $item['self'] ? '' : $contact_url . '/block';
932 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore';
935 if ($cid && !$item['self']) {
936 $contact_url = 'contact/' . $cid;
937 $poke_link = $contact_url . '/poke';
938 $posts_link = $contact_url . '/posts';
940 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
941 $pm_url = 'message/new/' . $cid;
947 DI::l10n()->t('Follow Thread') => $sub_link,
948 DI::l10n()->t('View Status') => $status_link,
949 DI::l10n()->t('View Profile') => $profile_link,
950 DI::l10n()->t('View Photos') => $photos_link,
951 DI::l10n()->t('Network Posts') => $posts_link,
952 DI::l10n()->t('View Contact') => $contact_url,
953 DI::l10n()->t('Send PM') => $pm_url,
954 DI::l10n()->t('Block') => $block_link,
955 DI::l10n()->t('Ignore') => $ignore_link
958 if (!empty($item['language'])) {
959 $menu[DI::l10n()->t('Languages')] = 'javascript:alert(\'' . Item::getLanguageMessage($item) . '\');';
962 if ($network == Protocol::DFRN) {
963 $menu[DI::l10n()->t("Poke")] = $poke_link;
966 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
967 in_array($item['network'], Protocol::FEDERATED)) {
968 $menu[DI::l10n()->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
971 $menu = [DI::l10n()->t('View Profile') => $item['author-link']];
974 $args = ['item' => $item, 'menu' => $menu];
976 Hook::callAll('item_photo_menu', $args);
978 $menu = $args['menu'];
981 foreach ($menu as $k => $v) {
982 if (strpos($v, 'javascript:') === 0) {
984 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
986 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
993 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
995 * Increments the count of each matching activity and adds a link to the author as needed.
997 * @param array $activity
998 * @param array &$conv_responses (already created with builtin activity structure)
1000 * @throws ImagickException
1001 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1003 function builtin_activity_puller(array $activity, array &$conv_responses)
1005 foreach ($conv_responses as $mode => $v) {
1010 $verb = Activity::LIKE;
1013 $verb = Activity::DISLIKE;
1016 $verb = Activity::ATTEND;
1019 $verb = Activity::ATTENDNO;
1022 $verb = Activity::ATTENDMAYBE;
1025 $verb = Activity::ANNOUNCE;
1031 if (!empty($activity['verb']) && DI::activity()->match($activity['verb'], $verb) && ($activity['gravity'] != GRAVITY_PARENT)) {
1034 'id' => $activity['author-id'],
1035 'network' => $activity['author-network'],
1036 'url' => $activity['author-link']
1038 $url = Contact::magicLinkByContact($author);
1039 if (strpos($url, 'redir/') === 0) {
1040 $sparkle = ' class="sparkle" ';
1043 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
1045 if (empty($activity['thr-parent-id'])) {
1046 $activity['thr-parent-id'] = $activity['parent-uri-id'];
1049 // Skip when the causer of the parent is the same than the author of the announce
1050 if (($verb == Activity::ANNOUNCE) && Post::exists(['uri-id' => $activity['thr-parent-id'],
1051 'uid' => $activity['uid'], 'causer-id' => $activity['author-id'], 'gravity' => GRAVITY_PARENT])) {
1055 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
1056 $conv_responses[$mode][$activity['thr-parent-id']] = [
1060 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
1061 // only list each unique author once
1065 if (public_contact() == $activity['author-id']) {
1066 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
1069 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
1071 // there can only be one activity verb per item so if we found anything, we can stop looking
1078 * Format the activity text for an item/photo/video
1080 * @param array $links = array of pre-linked names of actors
1081 * @param string $verb = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1082 * @param int $id = item id
1083 * @return string formatted text
1084 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1086 function format_activity(array $links, $verb, $id) {
1091 $total = count($links);
1093 $likers = $links[0];
1095 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1096 // list which show all likers
1099 $phrase = DI::l10n()->t('%s likes this.', $likers);
1102 $phrase = DI::l10n()->t('%s doesn\'t like this.', $likers);
1105 $phrase = DI::l10n()->t('%s attends.', $likers);
1108 $phrase = DI::l10n()->t('%s doesn\'t attend.', $likers);
1110 case 'attendmaybe' :
1111 $phrase = DI::l10n()->t('%s attends maybe.', $likers);
1114 $phrase = DI::l10n()->t('%s reshared this.', $likers);
1117 } elseif ($total > 1) {
1118 if ($total < MAX_LIKERS) {
1119 $likers = implode(', ', array_slice($links, 0, -1));
1120 $likers .= ' ' . DI::l10n()->t('and') . ' ' . $links[count($links)-1];
1122 $likers = implode(', ', array_slice($links, 0, MAX_LIKERS - 1));
1123 $likers .= ' ' . DI::l10n()->t('and %d other people', $total - MAX_LIKERS);
1126 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
1131 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> like this', $spanatts, $total);
1132 $explikers = DI::l10n()->t('%s like this.', $likers);
1135 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $total);
1136 $explikers = DI::l10n()->t('%s don\'t like this.', $likers);
1139 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend', $spanatts, $total);
1140 $explikers = DI::l10n()->t('%s attend.', $likers);
1143 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $total);
1144 $explikers = DI::l10n()->t('%s don\'t attend.', $likers);
1147 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $total);
1148 $explikers = DI::l10n()->t('%s attend maybe.', $likers);
1151 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> reshared this', $spanatts, $total);
1152 $explikers = DI::l10n()->t('%s reshared this.', $likers);
1156 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1159 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1160 '$phrase' => $phrase,
1169 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1173 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1175 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1176 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
1177 '$newpost' => 'true',
1178 '$baseurl' => DI::baseUrl()->get(true),
1179 '$geotag' => $geotag,
1180 '$nickname' => $x['nickname'],
1181 '$ispublic' => DI::l10n()->t('Visible to <strong>everybody</strong>'),
1182 '$linkurl' => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1183 '$term' => DI::l10n()->t('Tag term:'),
1184 '$fileas' => DI::l10n()->t('Save to Folder:'),
1185 '$whereareu' => DI::l10n()->t('Where are you right now?'),
1186 '$delitems' => DI::l10n()->t("Delete item\x28s\x29?"),
1187 '$is_mobile' => DI::mode()->isMobile(),
1191 Hook::callAll('jot_tool', $jotplugins);
1193 $tpl = Renderer::getMarkupTemplate("jot.tpl");
1195 $o .= Renderer::replaceMacros($tpl, [
1196 '$new_post' => DI::l10n()->t('New Post'),
1197 '$return_path' => DI::args()->getQueryString(),
1198 '$action' => 'item',
1199 '$share' => ($x['button'] ?? '') ?: DI::l10n()->t('Share'),
1200 '$loading' => DI::l10n()->t('Loading...'),
1201 '$upload' => DI::l10n()->t('Upload photo'),
1202 '$shortupload' => DI::l10n()->t('upload photo'),
1203 '$attach' => DI::l10n()->t('Attach file'),
1204 '$shortattach' => DI::l10n()->t('attach file'),
1205 '$edbold' => DI::l10n()->t('Bold'),
1206 '$editalic' => DI::l10n()->t('Italic'),
1207 '$eduline' => DI::l10n()->t('Underline'),
1208 '$edquote' => DI::l10n()->t('Quote'),
1209 '$edcode' => DI::l10n()->t('Code'),
1210 '$edimg' => DI::l10n()->t('Image'),
1211 '$edurl' => DI::l10n()->t('Link'),
1212 '$edattach' => DI::l10n()->t('Link or Media'),
1213 '$edvideo' => DI::l10n()->t('Video'),
1214 '$setloc' => DI::l10n()->t('Set your location'),
1215 '$shortsetloc' => DI::l10n()->t('set location'),
1216 '$noloc' => DI::l10n()->t('Clear browser location'),
1217 '$shortnoloc' => DI::l10n()->t('clear location'),
1218 '$title' => $x['title'] ?? '',
1219 '$placeholdertitle' => DI::l10n()->t('Set title'),
1220 '$category' => $x['category'] ?? '',
1221 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1222 '$wait' => DI::l10n()->t('Please wait'),
1223 '$permset' => DI::l10n()->t('Permission settings'),
1224 '$shortpermset' => DI::l10n()->t('Permissions'),
1225 '$wall' => $notes_cid ? 0 : 1,
1226 '$posttype' => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1227 '$content' => $x['content'] ?? '',
1228 '$post_id' => $x['post_id'] ?? '',
1229 '$baseurl' => DI::baseUrl()->get(true),
1230 '$defloc' => $x['default_location'],
1231 '$visitor' => $x['visitor'],
1232 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
1233 '$public' => DI::l10n()->t('Public post'),
1234 '$lockstate' => $x['lockstate'],
1235 '$bang' => $x['bang'],
1236 '$profile_uid' => $x['profile_uid'],
1237 '$preview' => DI::l10n()->t('Preview'),
1238 '$jotplugins' => $jotplugins,
1239 '$notes_cid' => $notes_cid,
1240 '$sourceapp' => DI::l10n()->t($a->sourcename),
1241 '$cancel' => DI::l10n()->t('Cancel'),
1242 '$rand_num' => Crypto::randomDigits(12),
1244 // ACL permissions box
1245 '$acl' => $x['acl'],
1247 //jot nav tab (used in some themes)
1248 '$message' => DI::l10n()->t('Message'),
1249 '$browser' => DI::l10n()->t('Browser'),
1251 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1255 if ($popup == true) {
1256 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1263 * Plucks the children of the given parent from a given item list.
1265 * @param array $item_list
1266 * @param array $parent
1267 * @param bool $recursive
1270 function get_item_children(array &$item_list, array $parent, $recursive = true)
1273 foreach ($item_list as $i => $item) {
1274 if ($item['gravity'] != GRAVITY_PARENT) {
1276 // Fallback to parent-uri if thr-parent is not set
1277 $thr_parent = $item['thr-parent-id'];
1278 if ($thr_parent == '') {
1279 $thr_parent = $item['parent-uri-id'];
1282 if ($thr_parent == $parent['uri-id']) {
1283 $item['children'] = get_item_children($item_list, $item);
1284 $children[] = $item;
1285 unset($item_list[$i]);
1287 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1288 $children[] = $item;
1289 unset($item_list[$i]);
1297 * Recursively sorts a tree-like item array
1299 * @param array $items
1302 function sort_item_children(array $items)
1305 usort($result, 'sort_thr_received_rev');
1306 foreach ($result as $k => $i) {
1307 if (isset($result[$k]['children'])) {
1308 $result[$k]['children'] = sort_item_children($result[$k]['children']);
1315 * Recursively add all children items at the top level of a list
1317 * @param array $children List of items to append
1318 * @param array $item_list
1320 function add_children_to_list(array $children, array &$item_list)
1322 foreach ($children as $child) {
1323 $item_list[] = $child;
1324 if (isset($child['children'])) {
1325 add_children_to_list($child['children'], $item_list);
1331 * Selectively flattens a tree-like item structure to prevent threading stairs
1333 * This recursive function takes the item tree structure created by conv_sort() and
1334 * flatten the extraneous depth levels when people reply sequentially, removing the
1335 * stairs effect in threaded conversations limiting the available content width.
1337 * The basic principle is the following: if a post item has only one reply and is
1338 * the last reply of its parent, then the reply is moved to the parent.
1340 * This process is rendered somewhat more complicated because items can be either
1341 * replies or likes, and these don't factor at all in the reply count/last reply.
1343 * @param array $parent A tree-like array of items
1346 function smart_flatten_conversation(array $parent)
1348 if (!isset($parent['children']) || count($parent['children']) == 0) {
1352 // We use a for loop to ensure we process the newly-moved items
1353 for ($i = 0; $i < count($parent['children']); $i++) {
1354 $child = $parent['children'][$i];
1356 if (isset($child['children']) && count($child['children'])) {
1357 // This helps counting only the regular posts
1358 $count_post_closure = function($var) {
1359 return $var['verb'] === Activity::POST;
1362 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1364 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1366 // If there's only one child's children post and this is the last child post
1367 if ($child_post_count == 1 && $remaining_post_count == 1) {
1369 // Searches the post item in the children
1371 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1375 $moved_item = $child['children'][$j];
1376 unset($parent['children'][$i]['children'][$j]);
1377 $parent['children'][] = $moved_item;
1379 $parent['children'][$i] = smart_flatten_conversation($child);
1389 * Expands a flat list of items into corresponding tree-like conversation structures.
1391 * sort the top-level posts either on "received" or "commented", and finally
1392 * append all the items at the top level (???)
1394 * @param array $item_list A list of items belonging to one or more conversations
1395 * @param string $order Either on "received" or "commented"
1397 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1399 function conv_sort(array $item_list, $order)
1403 if (!(is_array($item_list) && count($item_list))) {
1407 $blocklist = conv_get_blocklist();
1411 // Dedupes the item list on the uri to prevent infinite loops
1412 foreach ($item_list as $item) {
1413 if (in_array($item['author-id'], $blocklist)) {
1417 $item_array[$item['uri-id']] = $item;
1420 // Extract the top level items
1421 foreach ($item_array as $item) {
1422 if ($item['gravity'] == GRAVITY_PARENT) {
1427 if (stristr($order, 'pinned_received')) {
1428 usort($parents, 'sort_thr_pinned_received');
1429 } elseif (stristr($order, 'received')) {
1430 usort($parents, 'sort_thr_received');
1431 } elseif (stristr($order, 'commented')) {
1432 usort($parents, 'sort_thr_commented');
1436 * Plucks children from the item_array, second pass collects eventual orphan
1437 * items and add them as children of their top-level post.
1439 foreach ($parents as $i => $parent) {
1440 $parents[$i]['children'] =
1441 array_merge(get_item_children($item_array, $parent, true),
1442 get_item_children($item_array, $parent, false));
1445 foreach ($parents as $i => $parent) {
1446 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1449 if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
1450 foreach ($parents as $i => $parent) {
1451 $parents[$i] = smart_flatten_conversation($parent);
1455 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1456 /// However, this apparently ensures responses (likes, attendance) display (?!)
1457 foreach ($parents as $parent) {
1458 if (count($parent['children'])) {
1459 add_children_to_list($parent['children'], $parents);
1467 * usort() callback to sort item arrays by pinned and the received key
1473 function sort_thr_pinned_received(array $a, array $b)
1475 if ($b['pinned'] && !$a['pinned']) {
1477 } elseif (!$b['pinned'] && $a['pinned']) {
1481 return strcmp($b['received'], $a['received']);
1485 * usort() callback to sort item arrays by the received key
1491 function sort_thr_received(array $a, array $b)
1493 return strcmp($b['received'], $a['received']);
1497 * usort() callback to reverse sort item arrays by the received key
1503 function sort_thr_received_rev(array $a, array $b)
1505 return strcmp($a['received'], $b['received']);
1509 * usort() callback to sort item arrays by the commented key
1515 function sort_thr_commented(array $a, array $b)
1517 return strcmp($b['commented'], $a['commented']);