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\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Item;
35 use Friendica\Model\Profile;
36 use Friendica\Model\Tag;
37 use Friendica\Model\Verb;
38 use Friendica\Object\Post;
39 use Friendica\Object\Thread;
40 use Friendica\Protocol\Activity;
41 use Friendica\Util\Crypto;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Strings;
44 use Friendica\Util\Temporal;
45 use Friendica\Util\XML;
47 function item_extract_images($body) {
54 $img_start = strpos($orig_body, '[img');
55 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
56 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
57 while (($img_st_close !== false) && ($img_end !== false)) {
59 $img_st_close++; // make it point to AFTER the closing bracket
60 $img_end += $img_start;
62 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
63 // This is an embedded image
65 $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
66 $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
70 $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
73 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
75 if ($orig_body === false) {
76 // in case the body ends on a closing image tag
80 $img_start = strpos($orig_body, '[img');
81 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
82 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
85 $new_body = $new_body . $orig_body;
87 return ['body' => $new_body, 'images' => $saved_image];
90 function item_redir_and_replace_images($body, $images, $cid) {
96 $pos = BBCode::getTagPosition($origbody, 'url', 0);
97 while ($pos !== false && $cnt < 1000) {
99 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
100 $replace = '[url=' . DI::baseUrl() . '/redir/' . $cid
101 . '?url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
103 $newbody .= substr($origbody, 0, $pos['start']['open']);
104 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
105 $origbody = substr($origbody, $pos['end']['close']);
106 if ($origbody === false) {
110 $subject = preg_replace($search, $replace, $subject);
111 $newbody .= $subject;
114 // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
115 $pos = BBCode::getTagPosition($origbody, 'url', 0);
117 $newbody .= $origbody;
120 foreach ($images as $image) {
122 * We're depending on the property of 'foreach' (specified on the PHP website) that
123 * it loops over the array starting from the first element and going sequentially
124 * to the last element.
126 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
133 * Render actions localized
136 * @throws ImagickException
137 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
139 function localize_item(&$item)
141 $extracted = item_extract_images($item['body']);
142 if ($extracted['images']) {
143 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
146 /// @todo The following functionality needs to be cleaned up.
147 if (!empty($item['verb'])) {
148 $activity = DI::activity();
150 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
152 if (stristr($item['verb'], Activity::POKE)) {
153 $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
157 if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
161 $Aname = $item['author-name'];
162 $Alink = $item['author-link'];
164 $obj = XML::parseString($xmlhead . $item['object']);
166 $Bname = $obj->title;
170 foreach ($obj->link as $l) {
171 $atts = $l->attributes();
172 switch ($atts['rel']) {
173 case "alternate": $Blink = $atts['href'];
174 case "photo": $Bphoto = $atts['href'];
178 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
179 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
181 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
185 * we can't have a translation string with three positions but no distinguishable text
186 * So here is the translate string.
188 $txt = DI::l10n()->t('%1$s poked %2$s');
190 // now translate the verb
191 $poked_t = trim(sprintf($txt, '', ''));
192 $txt = str_replace($poked_t, DI::l10n()->t($verb), $txt);
194 // then do the sprintf on the translation string
196 $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
200 if ($activity->match($item['verb'], Activity::TAG)) {
201 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
202 'verb', 'object-type', 'resource-id', 'body', 'plink'];
203 $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
204 if (!DBA::isResult($obj)) {
208 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
209 'network' => $item['author-network'], 'url' => $item['author-link']];
210 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
212 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
213 'network' => $obj['author-network'], 'url' => $obj['author-link']];
214 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
216 switch ($obj['verb']) {
218 switch ($obj['object-type']) {
219 case Activity\ObjectType::EVENT:
220 $post_type = DI::l10n()->t('event');
223 $post_type = DI::l10n()->t('status');
227 if ($obj['resource-id']) {
228 $post_type = DI::l10n()->t('photo');
229 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
230 $rr['plink'] = $m[1];
232 $post_type = DI::l10n()->t('status');
234 // Let's break everthing ... ;-)
237 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
239 $parsedobj = XML::parseString($xmlhead . $item['object']);
241 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
242 $item['body'] = DI::l10n()->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
247 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
248 foreach ($matches as $mtch) {
249 if (!strpos($mtch[1], 'zrl=')) {
250 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
255 // add zrl's to public images
256 $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
257 if (preg_match($photo_pattern, $item['body'])) {
258 $photo_replace = '[url=' . Profile::zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5' . '[/img][/url]';
259 $item['body'] = BBCode::pregReplaceInTag($photo_pattern, $photo_replace, 'url', $item['body']);
262 // add sparkle links to appropriate permalinks
263 $author = ['uid' => 0, 'id' => $item['author-id'],
264 'network' => $item['author-network'], 'url' => $item['author-link']];
266 // Only create a redirection to a magic link when logged in
267 if (!empty($item['plink']) && Session::isAuthenticated()) {
268 $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
273 * Count the total of comments on this item and its desendants
274 * @TODO proper type-hint + doc-tag
278 function count_descendants($item) {
279 $total = count($item['children']);
282 foreach ($item['children'] as $child) {
283 if (!visible_activity($child)) {
286 $total += count_descendants($child);
293 function visible_activity($item) {
295 $activity = DI::activity();
297 if (empty($item['verb']) || $activity->isHidden($item['verb'])) {
301 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
302 if ($activity->match($item['verb'], Activity::FOLLOW) &&
303 $item['object-type'] === Activity\ObjectType::NOTE &&
304 empty($item['self']) &&
305 $item['uid'] == local_user()) {
312 function conv_get_blocklist()
318 $str_blocked = str_replace(["\n", "\r"], ",", DI::pConfig()->get(local_user(), 'system', 'blocked'));
319 if (empty($str_blocked)) {
325 foreach (explode(',', $str_blocked) as $entry) {
326 // The 4th parameter guarantees that there always will be a public contact entry
327 $cid = Contact::getIdForURL(trim($entry), 0, false, ['url' => trim($entry)]);
337 * "Render" a conversation or list of items for HTML display.
338 * There are two major forms of display:
339 * - Sequential or unthreaded ("New Item View" or search results)
340 * - conversation view
341 * The $mode parameter decides between the various renderings and also
342 * figures out how to determine page owner and other contextual items
343 * that are based on unique features of the calling module.
345 * @param array $items
348 * @param bool $preview
349 * @param string $order
352 * @throws ImagickException
353 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
355 function conversation(App $a, array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
357 $ssl_state = (local_user() ? true : false);
360 $live_update_div = '';
362 $blocklist = conv_get_blocklist();
364 $previewing = (($preview) ? ' preview ' : '');
366 if ($mode === 'network') {
367 $items = conversation_add_children($items, false, $order, $uid);
368 $profile_owner = local_user();
371 * The special div is needed for liveUpdate to kick in for this page.
372 * We only launch liveUpdate if you aren't filtering in some incompatible
373 * way and also you aren't writing a comment (discovered in javascript).
375 $live_update_div = '<div id="live-network"></div>' . "\r\n"
376 . "<script> var profile_uid = " . $_SESSION['uid']
377 . "; var netargs = '" . substr(DI::args()->getCommand(), 8)
379 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
380 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
381 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
382 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
383 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
384 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
385 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
386 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
387 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
388 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
389 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
391 . "'; </script>\r\n";
393 } elseif ($mode === 'profile') {
394 $items = conversation_add_children($items, false, $order, $uid);
395 $profile_owner = $a->profile['uid'];
399 if (!empty($_GET['tab'])) {
400 $tab = Strings::escapeTags(trim($_GET['tab']));
402 if ($tab === 'posts') {
404 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
405 * because browser prefetching might change it on us. We have to deliver it with the page.
408 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
409 . "<script> var profile_uid = " . $a->profile['uid']
410 . "; var netargs = '?f='; </script>\r\n";
413 } elseif ($mode === 'notes') {
414 $items = conversation_add_children($items, false, $order, local_user());
415 $profile_owner = local_user();
418 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
419 . "<script> var profile_uid = " . local_user()
420 . "; var netargs = '/?f='; </script>\r\n";
422 } elseif ($mode === 'display') {
423 $items = conversation_add_children($items, false, $order, $uid);
424 $profile_owner = $a->profile['uid'];
427 $live_update_div = '<div id="live-display"></div>' . "\r\n"
428 . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
431 } elseif ($mode === 'community') {
432 $items = conversation_add_children($items, true, $order, $uid);
436 $live_update_div = '<div id="live-community"></div>' . "\r\n"
437 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 10)
438 ."/?f='; </script>\r\n";
440 } elseif ($mode === 'contacts') {
441 $items = conversation_add_children($items, false, $order, $uid);
445 $live_update_div = '<div id="live-contacts"></div>' . "\r\n"
446 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 9)
447 ."/?f='; </script>\r\n";
449 } elseif ($mode === 'search') {
450 $live_update_div = '<div id="live-search"></div>' . "\r\n";
453 $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
456 $_SESSION['return_path'] = DI::args()->getQueryString();
459 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
460 Hook::callAll('conversation_start',$cb);
462 $items = $cb['items'];
473 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
474 unset($conv_responses['dislike']);
477 // array with html for each thread (parent+comments)
481 $page_template = Renderer::getMarkupTemplate("conversation.tpl");
483 if (!empty($items)) {
484 if (in_array($mode, ['community', 'contacts'])) {
487 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
494 if (in_array($mode, ['network-new', 'search', 'contact-posts'])) {
497 * "New Item View" on network page or search page results
498 * - just loop through the items and format them minimally for display
501 $tpl = 'search_item.tpl';
503 foreach ($items as $item) {
505 if (!visible_activity($item)) {
509 if (in_array($item['author-id'], $blocklist)) {
519 // prevent private email from leaking.
520 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
524 $profile_name = $item['author-name'];
525 if (!empty($item['author-link']) && empty($item['author-name'])) {
526 $profile_name = $item['author-link'];
529 $tags = Tag::populateFromItem($item);
531 $author = ['uid' => 0, 'id' => $item['author-id'],
532 'network' => $item['author-network'], 'url' => $item['author-link']];
533 $profile_link = Contact::magicLinkByContact($author);
535 if (strpos($profile_link, 'redir/') === 0) {
536 $sparkle = ' sparkle';
539 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
540 Hook::callAll('render_location',$locate);
542 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
544 localize_item($item);
545 if ($mode === 'network-new') {
552 'dropping' => $dropping,
553 'pagedrop' => $page_dropping,
554 'select' => DI::l10n()->t('Select'),
555 'delete' => DI::l10n()->t('Delete'),
559 $isstarred = "unstarred";
568 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
569 unset($likebuttons['dislike']);
572 $body = Item::prepareBody($item, true, $preview);
574 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
576 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
577 $title = ucfirst($item['content-warning']);
579 $title = $item['title'];
584 'id' => ($preview ? 'P0' : $item['id']),
585 'guid' => ($preview ? 'Q0' : $item['guid']),
586 'network' => $item['network'],
587 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
588 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link']),
589 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
590 'profile_url' => $profile_link,
591 'item_photo_menu' => item_photo_menu($item),
592 'name' => $profile_name,
593 'sparkle' => $sparkle,
595 'thumb' => DI::baseUrl()->remove($item['author-avatar']),
598 'tags' => $tags['tags'],
599 'hashtags' => $tags['hashtags'],
600 'mentions' => $tags['mentions'],
601 'implicit_mentions' => $tags['implicit_mentions'],
602 'txt_cats' => DI::l10n()->t('Categories:'),
603 'txt_folders' => DI::l10n()->t('Filed under:'),
604 'has_cats' => ((count($categories)) ? 'true' : ''),
605 'has_folders' => ((count($folders)) ? 'true' : ''),
606 'categories' => $categories,
607 'folders' => $folders,
608 'text' => strip_tags($body),
609 'localtime' => DateTimeFormat::local($item['created'], 'r'),
610 'ago' => (($item['app']) ? DI::l10n()->t('%s from %s', Temporal::getRelativeDate($item['created']),$item['app']) : Temporal::getRelativeDate($item['created'])),
611 'location' => $location,
613 'owner_name' => $owner_name,
614 'owner_url' => $owner_url,
615 'owner_photo' => DI::baseUrl()->remove($item['owner-avatar']),
616 'plink' => Item::getPlink($item),
618 'isstarred' => $isstarred,
621 'vote' => $likebuttons,
625 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> DI::l10n()->t('View in context')]),
626 'previewing' => $previewing,
627 'wait' => DI::l10n()->t('Please wait'),
631 $arr = ['item' => $item, 'output' => $tmp_item];
632 Hook::callAll('display_item', $arr);
634 $threads[$threadsid]['id'] = $item['id'];
635 $threads[$threadsid]['network'] = $item['network'];
636 $threads[$threadsid]['items'] = [$arr['output']];
641 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
643 $conv = new Thread($mode, $preview, $writable);
646 * get all the topmost parents
647 * this shouldn't be needed, as we should have only them in our array
648 * But for now, this array respects the old style, just in case
650 foreach ($items as $item) {
651 if (in_array($item['author-id'], $blocklist)) {
655 // Can we put this after the visibility check?
656 builtin_activity_puller($item, $conv_responses);
658 // Only add what is visible
659 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
663 if (!visible_activity($item)) {
667 /// @todo Check if this call is needed or not
668 $arr = ['item' => $item];
669 Hook::callAll('display_item', $arr);
671 $item['pagedrop'] = $page_dropping;
673 if ($item['gravity'] == GRAVITY_PARENT) {
674 $item_object = new Post($item);
675 $conv->addParent($item_object);
679 $threads = $conv->getTemplateData($conv_responses);
681 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
687 $o = Renderer::replaceMacros($page_template, [
688 '$baseurl' => DI::baseUrl()->get($ssl_state),
689 '$return_path' => DI::args()->getQueryString(),
690 '$live_update' => $live_update_div,
691 '$remove' => DI::l10n()->t('remove'),
694 '$threads' => $threads,
695 '$dropping' => ($page_dropping ? DI::l10n()->t('Delete Selected Items') : False),
702 * Fetch all comments from a query. Additionally set the newest resharer as thread owner.
704 * @param mixed $thread_items Database statement with thread posts
705 * @param boolean $pinned Is the item pinned?
707 * @return array items with parents and comments
709 function conversation_fetch_comments($thread_items, $pinned) {
717 while ($row = Item::fetch($thread_items)) {
718 if (($row['verb'] == Activity::ANNOUNCE) && ($row['author-link'] == $owner)) {
722 if (($row['verb'] == Activity::ANNOUNCE) && !empty($row['contact-uid']) && ($row['received'] > $received) && ($row['thr-parent'] == $row['parent-uri'])) {
723 $actor = ['link' => $row['author-link'], 'avatar' => $row['author-avatar'], 'name' => $row['author-name']];
724 $received = $row['received'];
727 if ((($row['gravity'] == GRAVITY_PARENT) && !$row['origin'] && !in_array($row['network'], [Protocol::DIASPORA])) &&
728 (empty($row['contact-uid']) || !in_array($row['network'], Protocol::NATIVE_SUPPORT))) {
729 $parentlines[] = $lineno;
732 if (($row['gravity'] == GRAVITY_PARENT) && ($row['author-link'] != $row['owner-link'])) {
733 $owner = $row['owner-link'];
736 if ($row['gravity'] == GRAVITY_PARENT) {
737 $row['pinned'] = $pinned;
744 DBA::close($thread_items);
746 if (!empty($actor)) {
747 foreach ($parentlines as $line) {
748 $comments[$line]['owner-link'] = $actor['link'];
749 $comments[$line]['owner-avatar'] = $actor['avatar'];
750 $comments[$line]['owner-name'] = $actor['name'];
757 * Add comments to top level entries that had been fetched before
759 * The system will fetch the comments for the local user whenever possible.
760 * This behaviour is currently needed to allow commenting on Friendica posts.
762 * @param array $parents Parent items
764 * @param $block_authors
767 * @return array items with parents and comments
768 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
770 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
771 if (count($parents) > 1) {
772 $max_comments = DI::config()->get('system', 'max_comments', 100);
774 $max_comments = DI::config()->get('system', 'max_display_comments', 1000);
777 $params = ['order' => ['gravity', 'uid', 'commented' => true]];
779 if ($max_comments > 0) {
780 $params['limit'] = $max_comments;
785 foreach ($parents AS $parent) {
786 $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
787 $parent['uri'], $uid, Verb::getID(Activity::FOLLOW)];
788 $items = conversation_fetch_items($parent, $items, $condition, $block_authors, $params);
791 foreach ($items as $index => $item) {
792 if ($item['uid'] == 0) {
793 $items[$index]['writable'] = in_array($item['network'], Protocol::FEDERATED);
797 $items = conv_sort($items, $order);
803 * Fetch conversation items
805 * @param array $parent
806 * @param array $items
807 * @param array $condition
808 * @param boolean $block_authors
809 * @param array $params
812 function conversation_fetch_items(array $parent, array $items, array $condition, bool $block_authors, array $params) {
813 if ($block_authors) {
814 $condition[0] .= " AND NOT `author`.`hidden`";
817 $thread_items = Item::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['contact-uid', 'gravity']), $condition, $params);
819 $comments = conversation_fetch_comments($thread_items, $parent['pinned'] ?? false);
821 if (count($comments) != 0) {
822 $items = array_merge($items, $comments);
827 function item_photo_menu($item) {
838 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self']) {
839 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
842 $author = ['uid' => 0, 'id' => $item['author-id'],
843 'network' => $item['author-network'], 'url' => $item['author-link']];
844 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
845 $sparkle = (strpos($profile_link, 'redir/') === 0);
848 $pcid = Contact::getIdForURL($item['author-link'], 0, false);
851 $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
852 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
853 if (DBA::isResult($contact)) {
854 $cid = $contact['id'];
855 $network = $contact['network'];
856 $rel = $contact['rel'];
860 $status_link = $profile_link . '/status';
861 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
862 $profile_link = $profile_link . '/profile';
866 $contact_url = 'contact/' . $pcid;
867 $posts_link = $contact_url . '/posts';
868 $block_link = $contact_url . '/block';
869 $ignore_link = $contact_url . '/ignore';
872 if ($cid && !$item['self']) {
873 $contact_url = 'contact/' . $cid;
874 $poke_link = $contact_url . '/poke';
875 $posts_link = $contact_url . '/posts';
877 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
878 $pm_url = 'message/new/' . $cid;
884 DI::l10n()->t('Follow Thread') => $sub_link,
885 DI::l10n()->t('View Status') => $status_link,
886 DI::l10n()->t('View Profile') => $profile_link,
887 DI::l10n()->t('View Photos') => $photos_link,
888 DI::l10n()->t('Network Posts') => $posts_link,
889 DI::l10n()->t('View Contact') => $contact_url,
890 DI::l10n()->t('Send PM') => $pm_url,
891 DI::l10n()->t('Block') => $block_link,
892 DI::l10n()->t('Ignore') => $ignore_link
895 if ($network == Protocol::DFRN) {
896 $menu[DI::l10n()->t("Poke")] = $poke_link;
899 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
900 in_array($item['network'], Protocol::FEDERATED)) {
901 $menu[DI::l10n()->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
904 $menu = [DI::l10n()->t('View Profile') => $item['author-link']];
907 $args = ['item' => $item, 'menu' => $menu];
909 Hook::callAll('item_photo_menu', $args);
911 $menu = $args['menu'];
914 foreach ($menu as $k => $v) {
915 if (strpos($v, 'javascript:') === 0) {
917 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
919 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
926 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
928 * Increments the count of each matching activity and adds a link to the author as needed.
931 * @param array &$conv_responses (already created with builtin activity structure)
933 * @throws ImagickException
934 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
936 function builtin_activity_puller($item, &$conv_responses) {
937 foreach ($conv_responses as $mode => $v) {
942 $verb = Activity::LIKE;
945 $verb = Activity::DISLIKE;
948 $verb = Activity::ATTEND;
951 $verb = Activity::ATTENDNO;
954 $verb = Activity::ATTENDMAYBE;
957 $verb = Activity::ANNOUNCE;
963 if (!empty($item['verb']) && DI::activity()->match($item['verb'], $verb) && ($item['gravity'] != GRAVITY_PARENT)) {
964 $author = ['uid' => 0, 'id' => $item['author-id'],
965 'network' => $item['author-network'], 'url' => $item['author-link']];
966 $url = Contact::magicLinkByContact($author);
967 if (strpos($url, 'redir/') === 0) {
968 $sparkle = ' class="sparkle" ';
971 $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
973 if (empty($item['thr-parent'])) {
974 $item['thr-parent'] = $item['parent-uri'];
977 if (!(isset($conv_responses[$mode][$item['thr-parent'] . '-l'])
978 && is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))) {
979 $conv_responses[$mode][$item['thr-parent'] . '-l'] = [];
982 // only list each unique author once
983 if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
987 if (!isset($conv_responses[$mode][$item['thr-parent']])) {
988 $conv_responses[$mode][$item['thr-parent']] = 1;
990 $conv_responses[$mode][$item['thr-parent']] ++;
993 if (public_contact() == $item['author-id']) {
994 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
997 $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
999 // there can only be one activity verb per item so if we found anything, we can stop looking
1006 * Format the vote text for a profile item
1008 * @param int $cnt = number of people who vote the item
1009 * @param array $arr = array of pre-linked names of likers/dislikers
1010 * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1011 * @param int $id = item id
1012 * @return string formatted text
1013 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1015 function format_like($cnt, array $arr, $type, $id) {
1023 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1024 // list which show all likers
1027 $phrase = DI::l10n()->t('%s likes this.', $likers);
1030 $phrase = DI::l10n()->t('%s doesn\'t like this.', $likers);
1033 $phrase = DI::l10n()->t('%s attends.', $likers);
1036 $phrase = DI::l10n()->t('%s doesn\'t attend.', $likers);
1038 case 'attendmaybe' :
1039 $phrase = DI::l10n()->t('%s attends maybe.', $likers);
1042 $phrase = DI::l10n()->t('%s reshared this.', $likers);
1048 $total = count($arr);
1049 if ($total < MAX_LIKERS) {
1050 $last = DI::l10n()->t('and') . ' ' . $arr[count($arr)-1];
1051 $arr2 = array_slice($arr, 0, -1);
1052 $likers = implode(', ', $arr2) . ' ' . $last;
1054 $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1055 $likers = implode(', ', $arr);
1056 $likers .= DI::l10n()->t('and %d other people', $total - MAX_LIKERS);
1059 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1064 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> like this', $spanatts, $cnt);
1065 $explikers = DI::l10n()->t('%s like this.', $likers);
1068 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $cnt);
1069 $explikers = DI::l10n()->t('%s don\'t like this.', $likers);
1072 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend', $spanatts, $cnt);
1073 $explikers = DI::l10n()->t('%s attend.', $likers);
1076 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $cnt);
1077 $explikers = DI::l10n()->t('%s don\'t attend.', $likers);
1080 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $cnt);
1081 $explikers = DI::l10n()->t('%s attend maybe.', $likers);
1084 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> reshared this', $spanatts, $cnt);
1085 $explikers = DI::l10n()->t('%s reshared this.', $likers);
1089 $expanded .= "\t" . '<p class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1092 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1093 '$phrase' => $phrase,
1102 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1106 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1108 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1109 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
1110 '$newpost' => 'true',
1111 '$baseurl' => DI::baseUrl()->get(true),
1112 '$geotag' => $geotag,
1113 '$nickname' => $x['nickname'],
1114 '$ispublic' => DI::l10n()->t('Visible to <strong>everybody</strong>'),
1115 '$linkurl' => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1116 '$term' => DI::l10n()->t('Tag term:'),
1117 '$fileas' => DI::l10n()->t('Save to Folder:'),
1118 '$whereareu' => DI::l10n()->t('Where are you right now?'),
1119 '$delitems' => DI::l10n()->t("Delete item\x28s\x29?")
1123 Hook::callAll('jot_tool', $jotplugins);
1125 // Private/public post links for the non-JS ACL form
1127 if (!empty($_REQUEST['public'])) {
1131 $query_str = DI::args()->getQueryString();
1132 if (strpos($query_str, 'public=1') !== false) {
1133 $query_str = str_replace(['?public=1', '&public=1'], ['', ''], $query_str);
1137 * I think $a->query_string may never have ? in it, but I could be wrong
1138 * It looks like it's from the index.php?q=[etc] rewrite that the web
1139 * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1141 if (strpos($query_str, '?') === false) {
1142 $public_post_link = '?public=1';
1144 $public_post_link = '&public=1';
1147 // $tpl = Renderer::replaceMacros($tpl,array('$jotplugins' => $jotplugins));
1148 $tpl = Renderer::getMarkupTemplate("jot.tpl");
1150 $o .= Renderer::replaceMacros($tpl,[
1151 '$new_post' => DI::l10n()->t('New Post'),
1152 '$return_path' => $query_str,
1153 '$action' => 'item',
1154 '$share' => ($x['button'] ?? '') ?: DI::l10n()->t('Share'),
1155 '$loading' => DI::l10n()->t('Loading...'),
1156 '$upload' => DI::l10n()->t('Upload photo'),
1157 '$shortupload' => DI::l10n()->t('upload photo'),
1158 '$attach' => DI::l10n()->t('Attach file'),
1159 '$shortattach' => DI::l10n()->t('attach file'),
1160 '$edbold' => DI::l10n()->t('Bold'),
1161 '$editalic' => DI::l10n()->t('Italic'),
1162 '$eduline' => DI::l10n()->t('Underline'),
1163 '$edquote' => DI::l10n()->t('Quote'),
1164 '$edcode' => DI::l10n()->t('Code'),
1165 '$edimg' => DI::l10n()->t('Image'),
1166 '$edurl' => DI::l10n()->t('Link'),
1167 '$edattach' => DI::l10n()->t('Link or Media'),
1168 '$setloc' => DI::l10n()->t('Set your location'),
1169 '$shortsetloc' => DI::l10n()->t('set location'),
1170 '$noloc' => DI::l10n()->t('Clear browser location'),
1171 '$shortnoloc' => DI::l10n()->t('clear location'),
1172 '$title' => $x['title'] ?? '',
1173 '$placeholdertitle' => DI::l10n()->t('Set title'),
1174 '$category' => $x['category'] ?? '',
1175 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1176 '$wait' => DI::l10n()->t('Please wait'),
1177 '$permset' => DI::l10n()->t('Permission settings'),
1178 '$shortpermset' => DI::l10n()->t('permissions'),
1179 '$wall' => $notes_cid ? 0 : 1,
1180 '$posttype' => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1181 '$content' => $x['content'] ?? '',
1182 '$post_id' => $x['post_id'] ?? '',
1183 '$baseurl' => DI::baseUrl()->get(true),
1184 '$defloc' => $x['default_location'],
1185 '$visitor' => $x['visitor'],
1186 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
1187 '$public' => DI::l10n()->t('Public post'),
1188 '$lockstate' => $x['lockstate'],
1189 '$bang' => $x['bang'],
1190 '$profile_uid' => $x['profile_uid'],
1191 '$preview' => DI::l10n()->t('Preview'),
1192 '$jotplugins' => $jotplugins,
1193 '$notes_cid' => $notes_cid,
1194 '$sourceapp' => DI::l10n()->t($a->sourcename),
1195 '$cancel' => DI::l10n()->t('Cancel'),
1196 '$rand_num' => Crypto::randomDigits(12),
1198 // ACL permissions box
1199 '$acl' => $x['acl'],
1200 '$group_perms' => DI::l10n()->t('Post to Groups'),
1201 '$contact_perms' => DI::l10n()->t('Post to Contacts'),
1202 '$private' => DI::l10n()->t('Private post'),
1203 '$is_private' => $private_post,
1204 '$public_link' => $public_post_link,
1206 //jot nav tab (used in some themes)
1207 '$message' => DI::l10n()->t('Message'),
1208 '$browser' => DI::l10n()->t('Browser'),
1210 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1214 if ($popup == true) {
1215 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1222 * Plucks the children of the given parent from a given item list.
1224 * @param array $item_list
1225 * @param array $parent
1226 * @param bool $recursive
1229 function get_item_children(array &$item_list, array $parent, $recursive = true)
1232 foreach ($item_list as $i => $item) {
1233 if ($item['gravity'] != GRAVITY_PARENT) {
1235 // Fallback to parent-uri if thr-parent is not set
1236 $thr_parent = $item['thr-parent'];
1237 if ($thr_parent == '') {
1238 $thr_parent = $item['parent-uri'];
1241 if ($thr_parent == $parent['uri']) {
1242 $item['children'] = get_item_children($item_list, $item);
1243 $children[] = $item;
1244 unset($item_list[$i]);
1246 } elseif ($item['parent'] == $parent['id']) {
1247 $children[] = $item;
1248 unset($item_list[$i]);
1256 * Recursively sorts a tree-like item array
1258 * @param array $items
1261 function sort_item_children(array $items)
1264 usort($result, 'sort_thr_received_rev');
1265 foreach ($result as $k => $i) {
1266 if (isset($result[$k]['children'])) {
1267 $result[$k]['children'] = sort_item_children($result[$k]['children']);
1274 * Recursively add all children items at the top level of a list
1276 * @param array $children List of items to append
1277 * @param array $item_list
1279 function add_children_to_list(array $children, array &$item_list)
1281 foreach ($children as $child) {
1282 $item_list[] = $child;
1283 if (isset($child['children'])) {
1284 add_children_to_list($child['children'], $item_list);
1290 * Selectively flattens a tree-like item structure to prevent threading stairs
1292 * This recursive function takes the item tree structure created by conv_sort() and
1293 * flatten the extraneous depth levels when people reply sequentially, removing the
1294 * stairs effect in threaded conversations limiting the available content width.
1296 * The basic principle is the following: if a post item has only one reply and is
1297 * the last reply of its parent, then the reply is moved to the parent.
1299 * This process is rendered somewhat more complicated because items can be either
1300 * replies or likes, and these don't factor at all in the reply count/last reply.
1302 * @param array $parent A tree-like array of items
1305 function smart_flatten_conversation(array $parent)
1307 if (!isset($parent['children']) || count($parent['children']) == 0) {
1311 // We use a for loop to ensure we process the newly-moved items
1312 for ($i = 0; $i < count($parent['children']); $i++) {
1313 $child = $parent['children'][$i];
1315 if (isset($child['children']) && count($child['children'])) {
1316 // This helps counting only the regular posts
1317 $count_post_closure = function($var) {
1318 return $var['verb'] === Activity::POST;
1321 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1323 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1325 // If there's only one child's children post and this is the last child post
1326 if ($child_post_count == 1 && $remaining_post_count == 1) {
1328 // Searches the post item in the children
1330 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1334 $moved_item = $child['children'][$j];
1335 unset($parent['children'][$i]['children'][$j]);
1336 $parent['children'][] = $moved_item;
1338 $parent['children'][$i] = smart_flatten_conversation($child);
1348 * Expands a flat list of items into corresponding tree-like conversation structures.
1350 * sort the top-level posts either on "received" or "commented", and finally
1351 * append all the items at the top level (???)
1353 * @param array $item_list A list of items belonging to one or more conversations
1354 * @param string $order Either on "received" or "commented"
1356 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1358 function conv_sort(array $item_list, $order)
1362 if (!(is_array($item_list) && count($item_list))) {
1366 $blocklist = conv_get_blocklist();
1370 // Dedupes the item list on the uri to prevent infinite loops
1371 foreach ($item_list as $item) {
1372 if (in_array($item['author-id'], $blocklist)) {
1376 $item_array[$item['uri']] = $item;
1379 // Extract the top level items
1380 foreach ($item_array as $item) {
1381 if ($item['gravity'] == GRAVITY_PARENT) {
1386 if (stristr($order, 'pinned_received')) {
1387 usort($parents, 'sort_thr_pinned_received');
1388 } elseif (stristr($order, 'received')) {
1389 usort($parents, 'sort_thr_received');
1390 } elseif (stristr($order, 'commented')) {
1391 usort($parents, 'sort_thr_commented');
1395 * Plucks children from the item_array, second pass collects eventual orphan
1396 * items and add them as children of their top-level post.
1398 foreach ($parents as $i => $parent) {
1399 $parents[$i]['children'] =
1400 array_merge(get_item_children($item_array, $parent, true),
1401 get_item_children($item_array, $parent, false));
1404 foreach ($parents as $i => $parent) {
1405 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1408 if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
1409 foreach ($parents as $i => $parent) {
1410 $parents[$i] = smart_flatten_conversation($parent);
1414 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1415 /// However, this apparently ensures responses (likes, attendance) display (?!)
1416 foreach ($parents as $parent) {
1417 if (count($parent['children'])) {
1418 add_children_to_list($parent['children'], $parents);
1426 * usort() callback to sort item arrays by pinned and the received key
1432 function sort_thr_pinned_received(array $a, array $b)
1434 if ($b['pinned'] && !$a['pinned']) {
1436 } elseif (!$b['pinned'] && $a['pinned']) {
1440 return strcmp($b['received'], $a['received']);
1444 * usort() callback to sort item arrays by the received key
1450 function sort_thr_received(array $a, array $b)
1452 return strcmp($b['received'], $a['received']);
1456 * usort() callback to reverse sort item arrays by the received key
1462 function sort_thr_received_rev(array $a, array $b)
1464 return strcmp($a['received'], $b['received']);
1468 * usort() callback to sort item arrays by the commented key
1474 function sort_thr_commented(array $a, array $b)
1476 return strcmp($b['commented'], $a['commented']);
1479 function render_location_dummy(array $item) {
1480 if (!empty($item['location']) && !empty($item['location'])) {
1481 return $item['location'];
1484 if (!empty($item['coord']) && !empty($item['coord'])) {
1485 return $item['coord'];