3 * @copyright Copyright (C) 2020, Friendica
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\Profile;
37 use Friendica\Model\Tag;
38 use Friendica\Model\Verb;
39 use Friendica\Object\Post;
40 use Friendica\Object\Thread;
41 use Friendica\Protocol\Activity;
42 use Friendica\Util\Crypto;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Strings;
45 use Friendica\Util\Temporal;
46 use Friendica\Util\XML;
48 function item_extract_images($body) {
55 $img_start = strpos($orig_body, '[img');
56 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
57 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
58 while (($img_st_close !== false) && ($img_end !== false)) {
60 $img_st_close++; // make it point to AFTER the closing bracket
61 $img_end += $img_start;
63 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
64 // This is an embedded image
66 $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
67 $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
71 $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
74 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
76 if ($orig_body === false) {
77 // in case the body ends on a closing image tag
81 $img_start = strpos($orig_body, '[img');
82 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
83 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
86 $new_body = $new_body . $orig_body;
88 return ['body' => $new_body, 'images' => $saved_image];
91 function item_redir_and_replace_images($body, $images, $cid) {
97 $pos = BBCode::getTagPosition($origbody, 'url', 0);
98 while ($pos !== false && $cnt < 1000) {
100 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
101 $replace = '[url=' . DI::baseUrl() . '/redir/' . $cid
102 . '?url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
104 $newbody .= substr($origbody, 0, $pos['start']['open']);
105 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
106 $origbody = substr($origbody, $pos['end']['close']);
107 if ($origbody === false) {
111 $subject = preg_replace($search, $replace, $subject);
112 $newbody .= $subject;
115 // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
116 $pos = BBCode::getTagPosition($origbody, 'url', 0);
118 $newbody .= $origbody;
121 foreach ($images as $image) {
123 * We're depending on the property of 'foreach' (specified on the PHP website) that
124 * it loops over the array starting from the first element and going sequentially
125 * to the last element.
127 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
134 * Render actions localized
137 * @throws ImagickException
138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
140 function localize_item(&$item)
142 $extracted = item_extract_images($item['body']);
143 if ($extracted['images']) {
144 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
147 /// @todo The following functionality needs to be cleaned up.
148 if (!empty($item['verb'])) {
149 $activity = DI::activity();
151 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
153 if (stristr($item['verb'], Activity::POKE)) {
154 $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
158 if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
162 $Aname = $item['author-name'];
163 $Alink = $item['author-link'];
165 $obj = XML::parseString($xmlhead . $item['object']);
167 $Bname = $obj->title;
171 foreach ($obj->link as $l) {
172 $atts = $l->attributes();
173 switch ($atts['rel']) {
174 case "alternate": $Blink = $atts['href'];
175 case "photo": $Bphoto = $atts['href'];
179 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
180 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
182 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
186 * we can't have a translation string with three positions but no distinguishable text
187 * So here is the translate string.
189 $txt = DI::l10n()->t('%1$s poked %2$s');
191 // now translate the verb
192 $poked_t = trim(sprintf($txt, '', ''));
193 $txt = str_replace($poked_t, DI::l10n()->t($verb), $txt);
195 // then do the sprintf on the translation string
197 $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
201 if ($activity->match($item['verb'], Activity::TAG)) {
202 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
203 'verb', 'object-type', 'resource-id', 'body', 'plink'];
204 $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
205 if (!DBA::isResult($obj)) {
209 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
210 'network' => $item['author-network'], 'url' => $item['author-link']];
211 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
213 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
214 'network' => $obj['author-network'], 'url' => $obj['author-link']];
215 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
217 switch ($obj['verb']) {
219 switch ($obj['object-type']) {
220 case Activity\ObjectType::EVENT:
221 $post_type = DI::l10n()->t('event');
224 $post_type = DI::l10n()->t('status');
228 if ($obj['resource-id']) {
229 $post_type = DI::l10n()->t('photo');
230 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
231 $rr['plink'] = $m[1];
233 $post_type = DI::l10n()->t('status');
235 // Let's break everthing ... ;-)
238 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
240 $parsedobj = XML::parseString($xmlhead . $item['object']);
242 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
243 $item['body'] = DI::l10n()->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
248 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
249 foreach ($matches as $mtch) {
250 if (!strpos($mtch[1], 'zrl=')) {
251 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
256 // add zrl's to public images
257 $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
258 if (preg_match($photo_pattern, $item['body'])) {
259 $photo_replace = '[url=' . Profile::zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5' . '[/img][/url]';
260 $item['body'] = BBCode::pregReplaceInTag($photo_pattern, $photo_replace, 'url', $item['body']);
263 // add sparkle links to appropriate permalinks
264 $author = ['uid' => 0, 'id' => $item['author-id'],
265 'network' => $item['author-network'], 'url' => $item['author-link']];
267 // Only create a redirection to a magic link when logged in
268 if (!empty($item['plink']) && Session::isAuthenticated()) {
269 $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
274 * Count the total of comments on this item and its desendants
275 * @TODO proper type-hint + doc-tag
279 function count_descendants($item) {
280 $total = count($item['children']);
283 foreach ($item['children'] as $child) {
284 if (!visible_activity($child)) {
287 $total += count_descendants($child);
294 function visible_activity($item) {
296 $activity = DI::activity();
298 if (empty($item['verb']) || $activity->isHidden($item['verb'])) {
302 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
303 if ($activity->match($item['verb'], Activity::FOLLOW) &&
304 $item['object-type'] === Activity\ObjectType::NOTE &&
305 empty($item['self']) &&
306 $item['uid'] == local_user()) {
313 function conv_get_blocklist()
319 $str_blocked = str_replace(["\n", "\r"], ",", DI::pConfig()->get(local_user(), 'system', 'blocked'));
320 if (empty($str_blocked)) {
326 foreach (explode(',', $str_blocked) as $entry) {
327 // The 4th parameter guarantees that there always will be a public contact entry
328 $cid = Contact::getIdForURL(trim($entry), 0, false, ['url' => trim($entry)]);
338 * "Render" a conversation or list of items for HTML display.
339 * There are two major forms of display:
340 * - Sequential or unthreaded ("New Item View" or search results)
341 * - conversation view
342 * The $mode parameter decides between the various renderings and also
343 * figures out how to determine page owner and other contextual items
344 * that are based on unique features of the calling module.
346 * @param array $items
349 * @param bool $preview
350 * @param string $order
353 * @throws ImagickException
354 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
356 function conversation(App $a, array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
360 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
361 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
362 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
363 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
365 $ssl_state = (local_user() ? true : false);
368 $live_update_div = '';
370 $blocklist = conv_get_blocklist();
372 $previewing = (($preview) ? ' preview ' : '');
374 if ($mode === 'network') {
375 $items = conversation_add_children($items, false, $order, $uid);
376 $profile_owner = local_user();
379 * The special div is needed for liveUpdate to kick in for this page.
380 * We only launch liveUpdate if you aren't filtering in some incompatible
381 * way and also you aren't writing a comment (discovered in javascript).
383 $live_update_div = '<div id="live-network"></div>' . "\r\n"
384 . "<script> var profile_uid = " . $_SESSION['uid']
385 . "; var netargs = '" . substr(DI::args()->getCommand(), 8)
387 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
388 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
389 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
390 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
391 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
392 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
393 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
394 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
395 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
396 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
397 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
399 . "'; </script>\r\n";
401 } elseif ($mode === 'profile') {
402 $items = conversation_add_children($items, false, $order, $uid);
403 $profile_owner = $a->profile['uid'];
407 if (!empty($_GET['tab'])) {
408 $tab = Strings::escapeTags(trim($_GET['tab']));
410 if ($tab === 'posts') {
412 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
413 * because browser prefetching might change it on us. We have to deliver it with the page.
416 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
417 . "<script> var profile_uid = " . $a->profile['uid']
418 . "; var netargs = '?f='; </script>\r\n";
421 } elseif ($mode === 'notes') {
422 $items = conversation_add_children($items, false, $order, local_user());
423 $profile_owner = local_user();
426 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
427 . "<script> var profile_uid = " . local_user()
428 . "; var netargs = '/?f='; </script>\r\n";
430 } elseif ($mode === 'display') {
431 $items = conversation_add_children($items, false, $order, $uid);
432 $profile_owner = $a->profile['uid'];
435 $live_update_div = '<div id="live-display"></div>' . "\r\n"
436 . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
439 } elseif ($mode === 'community') {
440 $items = conversation_add_children($items, true, $order, $uid);
444 $live_update_div = '<div id="live-community"></div>' . "\r\n"
445 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 10)
447 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
448 . "'; </script>\r\n";
450 } elseif ($mode === 'contacts') {
451 $items = conversation_add_children($items, false, $order, $uid);
455 $live_update_div = '<div id="live-contacts"></div>' . "\r\n"
456 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 9)
457 ."/?f='; </script>\r\n";
459 } elseif ($mode === 'search') {
460 $live_update_div = '<div id="live-search"></div>' . "\r\n";
463 $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
466 $_SESSION['return_path'] = DI::args()->getQueryString();
469 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
470 Hook::callAll('conversation_start',$cb);
472 $items = $cb['items'];
483 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
484 unset($conv_responses['dislike']);
487 // array with html for each thread (parent+comments)
491 $page_template = Renderer::getMarkupTemplate("conversation.tpl");
493 if (!empty($items)) {
494 if (in_array($mode, ['community', 'contacts'])) {
497 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
504 if (in_array($mode, ['network-new', 'search', 'contact-posts'])) {
507 * "New Item View" on network page or search page results
508 * - just loop through the items and format them minimally for display
511 $tpl = 'search_item.tpl';
513 foreach ($items as $item) {
515 if (!visible_activity($item)) {
519 if (in_array($item['author-id'], $blocklist)) {
525 // prevent private email from leaking.
526 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
530 $profile_name = $item['author-name'];
531 if (!empty($item['author-link']) && empty($item['author-name'])) {
532 $profile_name = $item['author-link'];
535 $tags = Tag::populateFromItem($item);
537 $author = ['uid' => 0, 'id' => $item['author-id'],
538 'network' => $item['author-network'], 'url' => $item['author-link']];
539 $profile_link = Contact::magicLinkByContact($author);
542 if (strpos($profile_link, 'redir/') === 0) {
543 $sparkle = ' sparkle';
546 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
547 Hook::callAll('render_location',$locate);
548 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
550 localize_item($item);
551 if ($mode === 'network-new') {
558 'dropping' => $dropping,
559 'pagedrop' => $page_dropping,
560 'select' => DI::l10n()->t('Select'),
561 'delete' => DI::l10n()->t('Delete'),
570 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
571 unset($likebuttons['dislike']);
574 $body_html = Item::prepareBody($item, true, $preview);
576 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
578 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
579 $title = ucfirst($item['content-warning']);
581 $title = $item['title'];
586 'id' => ($preview ? 'P0' : $item['id']),
587 'guid' => ($preview ? 'Q0' : $item['guid']),
588 'commented' => $item['commented'],
589 'received' => $item['received'],
590 'created_date' => $item['created'],
591 'uriid' => $item['uri-id'],
592 'network' => $item['network'],
593 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
594 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link']),
595 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
596 'profile_url' => $profile_link,
597 'item_photo_menu_html' => item_photo_menu($item),
598 'name' => $profile_name,
599 'sparkle' => $sparkle,
601 'thumb' => DI::baseUrl()->remove($item['author-avatar']),
603 'body_html' => $body_html,
604 'tags' => $tags['tags'],
605 'hashtags' => $tags['hashtags'],
606 'mentions' => $tags['mentions'],
607 'implicit_mentions' => $tags['implicit_mentions'],
608 'txt_cats' => DI::l10n()->t('Categories:'),
609 'txt_folders' => DI::l10n()->t('Filed under:'),
610 'has_cats' => ((count($categories)) ? 'true' : ''),
611 'has_folders' => ((count($folders)) ? 'true' : ''),
612 'categories' => $categories,
613 'folders' => $folders,
614 'text' => strip_tags($body_html),
615 'localtime' => DateTimeFormat::local($item['created'], 'r'),
616 'ago' => (($item['app']) ? DI::l10n()->t('%s from %s', Temporal::getRelativeDate($item['created']),$item['app']) : Temporal::getRelativeDate($item['created'])),
617 'location_html' => $location_html,
621 'owner_photo' => DI::baseUrl()->remove($item['owner-avatar']),
622 'plink' => Item::getPlink($item),
624 'isstarred' => 'unstarred',
627 'vote' => $likebuttons,
629 'dislike_html' => '',
630 'comment_html' => '',
631 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> DI::l10n()->t('View in context')]),
632 'previewing' => $previewing,
633 'wait' => DI::l10n()->t('Please wait'),
637 $arr = ['item' => $item, 'output' => $tmp_item];
638 Hook::callAll('display_item', $arr);
640 $threads[$threadsid]['id'] = $item['id'];
641 $threads[$threadsid]['network'] = $item['network'];
642 $threads[$threadsid]['items'] = [$arr['output']];
647 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
649 $conv = new Thread($mode, $preview, $writable);
652 * get all the topmost parents
653 * this shouldn't be needed, as we should have only them in our array
654 * But for now, this array respects the old style, just in case
656 foreach ($items as $item) {
657 if (in_array($item['author-id'], $blocklist)) {
661 // Can we put this after the visibility check?
662 builtin_activity_puller($item, $conv_responses);
664 // Only add what is visible
665 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
669 if (!visible_activity($item)) {
673 /// @todo Check if this call is needed or not
674 $arr = ['item' => $item];
675 Hook::callAll('display_item', $arr);
677 $item['pagedrop'] = $page_dropping;
679 if ($item['gravity'] == GRAVITY_PARENT) {
680 $item_object = new Post($item);
681 $conv->addParent($item_object);
685 $threads = $conv->getTemplateData($conv_responses);
687 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
693 $o = Renderer::replaceMacros($page_template, [
694 '$baseurl' => DI::baseUrl()->get($ssl_state),
695 '$return_path' => DI::args()->getQueryString(),
696 '$live_update' => $live_update_div,
697 '$remove' => DI::l10n()->t('remove'),
700 '$threads' => $threads,
701 '$dropping' => ($page_dropping ? DI::l10n()->t('Delete Selected Items') : False),
708 * Fetch all comments from a query. Additionally set the newest resharer as thread owner.
710 * @param mixed $thread_items Database statement with thread posts
711 * @param boolean $pinned Is the item pinned?
713 * @return array items with parents and comments
715 function conversation_fetch_comments($thread_items, $pinned) {
718 while ($row = Item::fetch($thread_items)) {
719 $name = $row['causer-contact-type'] == Contact::TYPE_RELAY ? $row['causer-link'] : $row['causer-name'];
721 switch ($row['post-type']) {
723 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'to')];
726 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'cc')];
729 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bto')];
732 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bcc')];
734 case Item::PT_FOLLOWER:
735 $row['direction'] = ['direction' => 6, 'title' => DI::l10n()->t('You are following %s.', $row['author-name'])];
738 $row['direction'] = ['direction' => 4, 'title' => DI::l10n()->t('Tagged')];
740 case Item::PT_ANNOUNCEMENT:
741 if (!empty($row['causer-id']) && DI::pConfig()->get(local_user(), 'system', 'display_resharer')) {
742 $row['owner-link'] = $row['causer-link'];
743 $row['owner-avatar'] = $row['causer-avatar'];
744 $row['owner-name'] = $row['causer-name'];
747 if (($row['gravity'] == GRAVITY_PARENT) && !empty($row['causer-id'])) {
748 $row['reshared'] = DI::l10n()->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkbyId($row['causer-id'])) .'">' . htmlentities($name) . '</a>');
750 $row['direction'] = ['direction' => 3, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Reshared') : DI::l10n()->t('Reshared by %s', $name))];
752 case Item::PT_COMMENT:
753 $row['direction'] = ['direction' => 5, 'title' => DI::l10n()->t('%s is participating in this thread.', $row['author-name'])];
755 case Item::PT_STORED:
756 $row['direction'] = ['direction' => 8, 'title' => DI::l10n()->t('Stored')];
758 case Item::PT_GLOBAL:
759 $row['direction'] = ['direction' => 9, 'title' => DI::l10n()->t('Global')];
762 $row['direction'] = ['direction' => 10, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Relayed') : DI::l10n()->t('Relayed by %s.', $name))];
764 case Item::PT_FETCHED:
765 $row['direction'] = ['direction' => 2, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Fetched') : DI::l10n()->t('Fetched because of %s', $name))];
769 if ($row['gravity'] == GRAVITY_PARENT) {
770 $row['pinned'] = $pinned;
776 DBA::close($thread_items);
782 * Add comments to top level entries that had been fetched before
784 * The system will fetch the comments for the local user whenever possible.
785 * This behaviour is currently needed to allow commenting on Friendica posts.
787 * @param array $parents Parent items
789 * @param $block_authors
792 * @return array items with parents and comments
793 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
795 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
796 if (count($parents) > 1) {
797 $max_comments = DI::config()->get('system', 'max_comments', 100);
799 $max_comments = DI::config()->get('system', 'max_display_comments', 1000);
802 $params = ['order' => ['gravity', 'uid', 'commented' => true]];
804 if ($max_comments > 0) {
805 $params['limit'] = $max_comments;
810 foreach ($parents AS $parent) {
811 $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
812 $parent['uri'], $uid, Verb::getID(Activity::FOLLOW)];
813 $items = conversation_fetch_items($parent, $items, $condition, $block_authors, $params);
816 foreach ($items as $index => $item) {
817 if ($item['uid'] == 0) {
818 $items[$index]['writable'] = in_array($item['network'], Protocol::FEDERATED);
822 $items = conv_sort($items, $order);
828 * Fetch conversation items
830 * @param array $parent
831 * @param array $items
832 * @param array $condition
833 * @param boolean $block_authors
834 * @param array $params
837 function conversation_fetch_items(array $parent, array $items, array $condition, bool $block_authors, array $params) {
838 if ($block_authors) {
839 $condition[0] .= " AND NOT `author`.`hidden`";
842 $thread_items = Item::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['contact-uid', 'gravity', 'post-type']), $condition, $params);
844 $comments = conversation_fetch_comments($thread_items, $parent['pinned'] ?? false);
846 if (count($comments) != 0) {
847 $items = array_merge($items, $comments);
852 function item_photo_menu($item) {
863 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self']) {
864 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
867 $author = ['uid' => 0, 'id' => $item['author-id'],
868 'network' => $item['author-network'], 'url' => $item['author-link']];
869 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
870 $sparkle = (strpos($profile_link, 'redir/') === 0);
873 $pcid = Contact::getIdForURL($item['author-link'], 0, false);
876 $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
877 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
878 if (DBA::isResult($contact)) {
879 $cid = $contact['id'];
880 $network = $contact['network'];
881 $rel = $contact['rel'];
885 $status_link = $profile_link . '/status';
886 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
887 $profile_link = $profile_link . '/profile';
891 $contact_url = 'contact/' . $pcid;
892 $posts_link = $contact_url . '/posts';
893 $block_link = $contact_url . '/block';
894 $ignore_link = $contact_url . '/ignore';
897 if ($cid && !$item['self']) {
898 $contact_url = 'contact/' . $cid;
899 $poke_link = $contact_url . '/poke';
900 $posts_link = $contact_url . '/posts';
902 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
903 $pm_url = 'message/new/' . $cid;
909 DI::l10n()->t('Follow Thread') => $sub_link,
910 DI::l10n()->t('View Status') => $status_link,
911 DI::l10n()->t('View Profile') => $profile_link,
912 DI::l10n()->t('View Photos') => $photos_link,
913 DI::l10n()->t('Network Posts') => $posts_link,
914 DI::l10n()->t('View Contact') => $contact_url,
915 DI::l10n()->t('Send PM') => $pm_url,
916 DI::l10n()->t('Block') => $block_link,
917 DI::l10n()->t('Ignore') => $ignore_link
920 if ($network == Protocol::DFRN) {
921 $menu[DI::l10n()->t("Poke")] = $poke_link;
924 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
925 in_array($item['network'], Protocol::FEDERATED)) {
926 $menu[DI::l10n()->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
929 $menu = [DI::l10n()->t('View Profile') => $item['author-link']];
932 $args = ['item' => $item, 'menu' => $menu];
934 Hook::callAll('item_photo_menu', $args);
936 $menu = $args['menu'];
939 foreach ($menu as $k => $v) {
940 if (strpos($v, 'javascript:') === 0) {
942 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
944 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
951 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
953 * Increments the count of each matching activity and adds a link to the author as needed.
956 * @param array &$conv_responses (already created with builtin activity structure)
958 * @throws ImagickException
959 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
961 function builtin_activity_puller($item, &$conv_responses) {
962 foreach ($conv_responses as $mode => $v) {
967 $verb = Activity::LIKE;
970 $verb = Activity::DISLIKE;
973 $verb = Activity::ATTEND;
976 $verb = Activity::ATTENDNO;
979 $verb = Activity::ATTENDMAYBE;
982 $verb = Activity::ANNOUNCE;
988 if (!empty($item['verb']) && DI::activity()->match($item['verb'], $verb) && ($item['gravity'] != GRAVITY_PARENT)) {
989 $author = ['uid' => 0, 'id' => $item['author-id'],
990 'network' => $item['author-network'], 'url' => $item['author-link']];
991 $url = Contact::magicLinkByContact($author);
992 if (strpos($url, 'redir/') === 0) {
993 $sparkle = ' class="sparkle" ';
996 $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
998 if (empty($item['thr-parent'])) {
999 $item['thr-parent'] = $item['parent-uri'];
1002 if (!(isset($conv_responses[$mode][$item['thr-parent'] . '-l'])
1003 && is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))) {
1004 $conv_responses[$mode][$item['thr-parent'] . '-l'] = [];
1007 // only list each unique author once
1008 if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
1012 // Skip when the causer of the parent is the same than the author of the announce
1013 if (($verb == Activity::ANNOUNCE) && Item::exists(['uri' => $item['thr-parent'],
1014 'uid' => $item['uid'], 'causer-id' => $item['author-id'], 'gravity' => GRAVITY_PARENT])) {
1018 if (!isset($conv_responses[$mode][$item['thr-parent']])) {
1019 $conv_responses[$mode][$item['thr-parent']] = 1;
1021 $conv_responses[$mode][$item['thr-parent']] ++;
1024 if (public_contact() == $item['author-id']) {
1025 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
1028 $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
1030 // there can only be one activity verb per item so if we found anything, we can stop looking
1037 * Format the vote text for a profile item
1039 * @param int $cnt = number of people who vote the item
1040 * @param array $arr = array of pre-linked names of likers/dislikers
1041 * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1042 * @param int $id = item id
1043 * @return string formatted text
1044 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1046 function format_like($cnt, array $arr, $type, $id) {
1054 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1055 // list which show all likers
1058 $phrase = DI::l10n()->t('%s likes this.', $likers);
1061 $phrase = DI::l10n()->t('%s doesn\'t like this.', $likers);
1064 $phrase = DI::l10n()->t('%s attends.', $likers);
1067 $phrase = DI::l10n()->t('%s doesn\'t attend.', $likers);
1069 case 'attendmaybe' :
1070 $phrase = DI::l10n()->t('%s attends maybe.', $likers);
1073 $phrase = DI::l10n()->t('%s reshared this.', $likers);
1079 $total = count($arr);
1080 if ($total < MAX_LIKERS) {
1081 $last = DI::l10n()->t('and') . ' ' . $arr[count($arr)-1];
1082 $arr2 = array_slice($arr, 0, -1);
1083 $likers = implode(', ', $arr2) . ' ' . $last;
1085 $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1086 $likers = implode(', ', $arr);
1087 $likers .= DI::l10n()->t('and %d other people', $total - MAX_LIKERS);
1090 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1095 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> like this', $spanatts, $cnt);
1096 $explikers = DI::l10n()->t('%s like this.', $likers);
1099 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $cnt);
1100 $explikers = DI::l10n()->t('%s don\'t like this.', $likers);
1103 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend', $spanatts, $cnt);
1104 $explikers = DI::l10n()->t('%s attend.', $likers);
1107 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $cnt);
1108 $explikers = DI::l10n()->t('%s don\'t attend.', $likers);
1111 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $cnt);
1112 $explikers = DI::l10n()->t('%s attend maybe.', $likers);
1115 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> reshared this', $spanatts, $cnt);
1116 $explikers = DI::l10n()->t('%s reshared this.', $likers);
1120 $expanded .= "\t" . '<p class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1123 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1124 '$phrase' => $phrase,
1133 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1137 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1139 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1140 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
1141 '$newpost' => 'true',
1142 '$baseurl' => DI::baseUrl()->get(true),
1143 '$geotag' => $geotag,
1144 '$nickname' => $x['nickname'],
1145 '$ispublic' => DI::l10n()->t('Visible to <strong>everybody</strong>'),
1146 '$linkurl' => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1147 '$term' => DI::l10n()->t('Tag term:'),
1148 '$fileas' => DI::l10n()->t('Save to Folder:'),
1149 '$whereareu' => DI::l10n()->t('Where are you right now?'),
1150 '$delitems' => DI::l10n()->t("Delete item\x28s\x29?")
1154 Hook::callAll('jot_tool', $jotplugins);
1156 // $tpl = Renderer::replaceMacros($tpl,array('$jotplugins' => $jotplugins));
1157 $tpl = Renderer::getMarkupTemplate("jot.tpl");
1159 $o .= Renderer::replaceMacros($tpl,[
1160 '$new_post' => DI::l10n()->t('New Post'),
1161 '$return_path' => DI::args()->getQueryString(),
1162 '$action' => 'item',
1163 '$share' => ($x['button'] ?? '') ?: DI::l10n()->t('Share'),
1164 '$loading' => DI::l10n()->t('Loading...'),
1165 '$upload' => DI::l10n()->t('Upload photo'),
1166 '$shortupload' => DI::l10n()->t('upload photo'),
1167 '$attach' => DI::l10n()->t('Attach file'),
1168 '$shortattach' => DI::l10n()->t('attach file'),
1169 '$edbold' => DI::l10n()->t('Bold'),
1170 '$editalic' => DI::l10n()->t('Italic'),
1171 '$eduline' => DI::l10n()->t('Underline'),
1172 '$edquote' => DI::l10n()->t('Quote'),
1173 '$edcode' => DI::l10n()->t('Code'),
1174 '$edimg' => DI::l10n()->t('Image'),
1175 '$edurl' => DI::l10n()->t('Link'),
1176 '$edattach' => DI::l10n()->t('Link or Media'),
1177 '$setloc' => DI::l10n()->t('Set your location'),
1178 '$shortsetloc' => DI::l10n()->t('set location'),
1179 '$noloc' => DI::l10n()->t('Clear browser location'),
1180 '$shortnoloc' => DI::l10n()->t('clear location'),
1181 '$title' => $x['title'] ?? '',
1182 '$placeholdertitle' => DI::l10n()->t('Set title'),
1183 '$category' => $x['category'] ?? '',
1184 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1185 '$wait' => DI::l10n()->t('Please wait'),
1186 '$permset' => DI::l10n()->t('Permission settings'),
1187 '$shortpermset' => DI::l10n()->t('Permissions'),
1188 '$wall' => $notes_cid ? 0 : 1,
1189 '$posttype' => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1190 '$content' => $x['content'] ?? '',
1191 '$post_id' => $x['post_id'] ?? '',
1192 '$baseurl' => DI::baseUrl()->get(true),
1193 '$defloc' => $x['default_location'],
1194 '$visitor' => $x['visitor'],
1195 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
1196 '$public' => DI::l10n()->t('Public post'),
1197 '$lockstate' => $x['lockstate'],
1198 '$bang' => $x['bang'],
1199 '$profile_uid' => $x['profile_uid'],
1200 '$preview' => DI::l10n()->t('Preview'),
1201 '$jotplugins' => $jotplugins,
1202 '$notes_cid' => $notes_cid,
1203 '$sourceapp' => DI::l10n()->t($a->sourcename),
1204 '$cancel' => DI::l10n()->t('Cancel'),
1205 '$rand_num' => Crypto::randomDigits(12),
1207 // ACL permissions box
1208 '$acl' => $x['acl'],
1210 //jot nav tab (used in some themes)
1211 '$message' => DI::l10n()->t('Message'),
1212 '$browser' => DI::l10n()->t('Browser'),
1214 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1218 if ($popup == true) {
1219 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1226 * Plucks the children of the given parent from a given item list.
1228 * @param array $item_list
1229 * @param array $parent
1230 * @param bool $recursive
1233 function get_item_children(array &$item_list, array $parent, $recursive = true)
1236 foreach ($item_list as $i => $item) {
1237 if ($item['gravity'] != GRAVITY_PARENT) {
1239 // Fallback to parent-uri if thr-parent is not set
1240 $thr_parent = $item['thr-parent'];
1241 if ($thr_parent == '') {
1242 $thr_parent = $item['parent-uri'];
1245 if ($thr_parent == $parent['uri']) {
1246 $item['children'] = get_item_children($item_list, $item);
1247 $children[] = $item;
1248 unset($item_list[$i]);
1250 } elseif ($item['parent'] == $parent['id']) {
1251 $children[] = $item;
1252 unset($item_list[$i]);
1260 * Recursively sorts a tree-like item array
1262 * @param array $items
1265 function sort_item_children(array $items)
1268 usort($result, 'sort_thr_received_rev');
1269 foreach ($result as $k => $i) {
1270 if (isset($result[$k]['children'])) {
1271 $result[$k]['children'] = sort_item_children($result[$k]['children']);
1278 * Recursively add all children items at the top level of a list
1280 * @param array $children List of items to append
1281 * @param array $item_list
1283 function add_children_to_list(array $children, array &$item_list)
1285 foreach ($children as $child) {
1286 $item_list[] = $child;
1287 if (isset($child['children'])) {
1288 add_children_to_list($child['children'], $item_list);
1294 * Selectively flattens a tree-like item structure to prevent threading stairs
1296 * This recursive function takes the item tree structure created by conv_sort() and
1297 * flatten the extraneous depth levels when people reply sequentially, removing the
1298 * stairs effect in threaded conversations limiting the available content width.
1300 * The basic principle is the following: if a post item has only one reply and is
1301 * the last reply of its parent, then the reply is moved to the parent.
1303 * This process is rendered somewhat more complicated because items can be either
1304 * replies or likes, and these don't factor at all in the reply count/last reply.
1306 * @param array $parent A tree-like array of items
1309 function smart_flatten_conversation(array $parent)
1311 if (!isset($parent['children']) || count($parent['children']) == 0) {
1315 // We use a for loop to ensure we process the newly-moved items
1316 for ($i = 0; $i < count($parent['children']); $i++) {
1317 $child = $parent['children'][$i];
1319 if (isset($child['children']) && count($child['children'])) {
1320 // This helps counting only the regular posts
1321 $count_post_closure = function($var) {
1322 return $var['verb'] === Activity::POST;
1325 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1327 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1329 // If there's only one child's children post and this is the last child post
1330 if ($child_post_count == 1 && $remaining_post_count == 1) {
1332 // Searches the post item in the children
1334 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1338 $moved_item = $child['children'][$j];
1339 unset($parent['children'][$i]['children'][$j]);
1340 $parent['children'][] = $moved_item;
1342 $parent['children'][$i] = smart_flatten_conversation($child);
1352 * Expands a flat list of items into corresponding tree-like conversation structures.
1354 * sort the top-level posts either on "received" or "commented", and finally
1355 * append all the items at the top level (???)
1357 * @param array $item_list A list of items belonging to one or more conversations
1358 * @param string $order Either on "received" or "commented"
1360 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1362 function conv_sort(array $item_list, $order)
1366 if (!(is_array($item_list) && count($item_list))) {
1370 $blocklist = conv_get_blocklist();
1374 // Dedupes the item list on the uri to prevent infinite loops
1375 foreach ($item_list as $item) {
1376 if (in_array($item['author-id'], $blocklist)) {
1380 $item_array[$item['uri']] = $item;
1383 // Extract the top level items
1384 foreach ($item_array as $item) {
1385 if ($item['gravity'] == GRAVITY_PARENT) {
1390 if (stristr($order, 'pinned_received')) {
1391 usort($parents, 'sort_thr_pinned_received');
1392 } elseif (stristr($order, 'received')) {
1393 usort($parents, 'sort_thr_received');
1394 } elseif (stristr($order, 'commented')) {
1395 usort($parents, 'sort_thr_commented');
1399 * Plucks children from the item_array, second pass collects eventual orphan
1400 * items and add them as children of their top-level post.
1402 foreach ($parents as $i => $parent) {
1403 $parents[$i]['children'] =
1404 array_merge(get_item_children($item_array, $parent, true),
1405 get_item_children($item_array, $parent, false));
1408 foreach ($parents as $i => $parent) {
1409 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1412 if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
1413 foreach ($parents as $i => $parent) {
1414 $parents[$i] = smart_flatten_conversation($parent);
1418 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1419 /// However, this apparently ensures responses (likes, attendance) display (?!)
1420 foreach ($parents as $parent) {
1421 if (count($parent['children'])) {
1422 add_children_to_list($parent['children'], $parents);
1430 * usort() callback to sort item arrays by pinned and the received key
1436 function sort_thr_pinned_received(array $a, array $b)
1438 if ($b['pinned'] && !$a['pinned']) {
1440 } elseif (!$b['pinned'] && $a['pinned']) {
1444 return strcmp($b['received'], $a['received']);
1448 * usort() callback to sort item arrays by the received key
1454 function sort_thr_received(array $a, array $b)
1456 return strcmp($b['received'], $a['received']);
1460 * usort() callback to reverse sort item arrays by the received key
1466 function sort_thr_received_rev(array $a, array $b)
1468 return strcmp($a['received'], $b['received']);
1472 * usort() callback to sort item arrays by the commented key
1478 function sort_thr_commented(array $a, array $b)
1480 return strcmp($b['commented'], $a['commented']);