]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
b25fae4f71683b47317bba6bde90583a5124c613
[friendica.git] / include / conversation.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 use Friendica\App;
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;
33 use Friendica\DI;
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;
47
48 function item_extract_images($body) {
49
50         $saved_image = [];
51         $orig_body = $body;
52         $new_body = '';
53
54         $cnt = 0;
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)) {
59
60                 $img_st_close++; // make it point to AFTER the closing bracket
61                 $img_end += $img_start;
62
63                 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
64                         // This is an embedded image
65
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 . '#!]';
68
69                         $cnt++;
70                 } else {
71                         $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
72                 }
73
74                 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
75
76                 if ($orig_body === false) {
77                         // in case the body ends on a closing image tag
78                         $orig_body = '';
79                 }
80
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);
84         }
85
86         $new_body = $new_body . $orig_body;
87
88         return ['body' => $new_body, 'images' => $saved_image];
89 }
90
91 function item_redir_and_replace_images($body, $images, $cid) {
92
93         $origbody = $body;
94         $newbody = '';
95
96         $cnt = 1;
97         $pos = BBCode::getTagPosition($origbody, 'url', 0);
98         while ($pos !== false && $cnt < 1000) {
99
100                 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
101                 $replace = '[url=' . DI::baseUrl() . '/redir/' . $cid
102                                    . '?url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
103
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) {
108                         $origbody = '';
109                 }
110
111                 $subject = preg_replace($search, $replace, $subject);
112                 $newbody .= $subject;
113
114                 $cnt++;
115                 // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
116                 $pos = BBCode::getTagPosition($origbody, 'url', 0);
117         }
118         $newbody .= $origbody;
119
120         $cnt = 0;
121         foreach ($images as $image) {
122                 /*
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.
126                  */
127                 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
128                 $cnt++;
129         }
130         return $newbody;
131 }
132
133 /**
134  * Render actions localized
135  *
136  * @param $item
137  * @throws ImagickException
138  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
139  */
140 function localize_item(&$item)
141 {
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']);
145         }
146
147         /// @todo The following functionality needs to be cleaned up. 
148         if (!empty($item['verb'])) {
149                 $activity = DI::activity();
150
151                 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
152
153                 if (stristr($item['verb'], Activity::POKE)) {
154                         $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
155                         if (!$verb) {
156                                 return;
157                         }
158                         if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
159                                 return;
160                         }
161
162                         $Aname = $item['author-name'];
163                         $Alink = $item['author-link'];
164
165                         $obj = XML::parseString($xmlhead . $item['object']);
166
167                         $Bname = $obj->title;
168                         $Blink = $obj->id;
169                         $Bphoto = "";
170
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'];
176                                 }
177                         }
178
179                         $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
180                         $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
181                         if ($Bphoto != "") {
182                                 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
183                         }
184
185                         /*
186                          * we can't have a translation string with three positions but no distinguishable text
187                          * So here is the translate string.
188                          */
189                         $txt = DI::l10n()->t('%1$s poked %2$s');
190
191                         // now translate the verb
192                         $poked_t = trim(sprintf($txt, '', ''));
193                         $txt = str_replace($poked_t, DI::l10n()->t($verb), $txt);
194
195                         // then do the sprintf on the translation string
196
197                         $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
198
199                 }
200
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)) {
206                                 return;
207                         }
208
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]';
212
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]';
216
217                         switch ($obj['verb']) {
218                                 case Activity::POST:
219                                         switch ($obj['object-type']) {
220                                                 case Activity\ObjectType::EVENT:
221                                                         $post_type = DI::l10n()->t('event');
222                                                         break;
223                                                 default:
224                                                         $post_type = DI::l10n()->t('status');
225                                         }
226                                         break;
227                                 default:
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];
232                                         } else {
233                                                 $post_type = DI::l10n()->t('status');
234                                         }
235                                         // Let's break everthing ... ;-)
236                                         break;
237                         }
238                         $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
239
240                         $parsedobj = XML::parseString($xmlhead . $item['object']);
241
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);
244                 }
245         }
246
247         $matches = null;
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']);
252                         }
253                 }
254         }
255
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']);
261         }
262
263         // add sparkle links to appropriate permalinks
264         $author = ['uid' => 0, 'id' => $item['author-id'],
265                 'network' => $item['author-network'], 'url' => $item['author-link']];
266
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']);
270         }
271 }
272
273 /**
274  * Count the total of comments on this item and its desendants
275  * @TODO proper type-hint + doc-tag
276  * @param $item
277  * @return int
278  */
279 function count_descendants($item) {
280         $total = count($item['children']);
281
282         if ($total > 0) {
283                 foreach ($item['children'] as $child) {
284                         if (!visible_activity($child)) {
285                                 $total --;
286                         }
287                         $total += count_descendants($child);
288                 }
289         }
290
291         return $total;
292 }
293
294 function visible_activity($item) {
295
296         $activity = DI::activity();
297
298         if (empty($item['verb']) || $activity->isHidden($item['verb'])) {
299                 return false;
300         }
301
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()) {
307                 return false;
308         }
309
310         return true;
311 }
312
313 function conv_get_blocklist()
314 {
315         if (!local_user()) {
316                 return [];
317         }
318
319         $str_blocked = str_replace(["\n", "\r"], ",", DI::pConfig()->get(local_user(), 'system', 'blocked'));
320         if (empty($str_blocked)) {
321                 return [];
322         }
323
324         $blocklist = [];
325
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)]);
329                 if (!empty($cid)) {
330                         $blocklist[] = $cid;
331                 }
332         }
333
334         return $blocklist;
335 }
336
337 /**
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.
345  * @param App    $a
346  * @param array  $items
347  * @param        $mode
348  * @param        $update
349  * @param bool   $preview
350  * @param string $order
351  * @param int    $uid
352  * @return string
353  * @throws ImagickException
354  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
355  */
356 function conversation(App $a, array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
357 {
358         $page = DI::page();
359
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'));
364
365         $ssl_state = (local_user() ? true : false);
366
367         $profile_owner = 0;
368         $live_update_div = '';
369
370         $blocklist = conv_get_blocklist();
371
372         $previewing = (($preview) ? ' preview ' : '');
373
374         if ($mode === 'network') {
375                 $items = conversation_add_children($items, false, $order, $uid);
376                 $profile_owner = local_user();
377                 if (!$update) {
378                         /*
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).
382                          */
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)
386                                 . '?f='
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'])      : '')
398
399                                 . "'; </script>\r\n";
400                 }
401         } elseif ($mode === 'profile') {
402                 $items = conversation_add_children($items, false, $order, $uid);
403                 $profile_owner = $a->profile['uid'];
404
405                 if (!$update) {
406                         $tab = 'posts';
407                         if (!empty($_GET['tab'])) {
408                                 $tab = Strings::escapeTags(trim($_GET['tab']));
409                         }
410                         if ($tab === 'posts') {
411                                 /*
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.
414                                  */
415
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";
419                         }
420                 }
421         } elseif ($mode === 'notes') {
422                 $items = conversation_add_children($items, false, $order, local_user());
423                 $profile_owner = local_user();
424
425                 if (!$update) {
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";
429                 }
430         } elseif ($mode === 'display') {
431                 $items = conversation_add_children($items, false, $order, $uid);
432                 $profile_owner = $a->profile['uid'];
433
434                 if (!$update) {
435                         $live_update_div = '<div id="live-display"></div>' . "\r\n"
436                                 . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
437                                 . "</script>";
438                 }
439         } elseif ($mode === 'community') {
440                 $items = conversation_add_children($items, true, $order, $uid);
441                 $profile_owner = 0;
442
443                 if (!$update) {
444                         $live_update_div = '<div id="live-community"></div>' . "\r\n"
445                                 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 10)
446                                 ."/?f='; </script>\r\n";
447                 }
448         } elseif ($mode === 'contacts') {
449                 $items = conversation_add_children($items, false, $order, $uid);
450                 $profile_owner = 0;
451
452                 if (!$update) {
453                         $live_update_div = '<div id="live-contacts"></div>' . "\r\n"
454                                 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 9)
455                                 ."/?f='; </script>\r\n";
456                 }
457         } elseif ($mode === 'search') {
458                 $live_update_div = '<div id="live-search"></div>' . "\r\n";
459         }
460
461         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
462
463         if (!$update) {
464                 $_SESSION['return_path'] = DI::args()->getQueryString();
465         }
466
467         $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
468         Hook::callAll('conversation_start',$cb);
469
470         $items = $cb['items'];
471
472         $conv_responses = [
473                 'like'        => [],
474                 'dislike'     => [],
475                 'attendyes'   => [],
476                 'attendno'    => [],
477                 'attendmaybe' => [],
478                 'announce'    => [],    
479         ];
480
481         if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
482                 unset($conv_responses['dislike']);
483         }
484
485         // array with html for each thread (parent+comments)
486         $threads = [];
487         $threadsid = -1;
488
489         $page_template = Renderer::getMarkupTemplate("conversation.tpl");
490
491         if (!empty($items)) {
492                 if (in_array($mode, ['community', 'contacts'])) {
493                         $writable = true;
494                 } else {
495                         $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
496                 }
497
498                 if (!local_user()) {
499                         $writable = false;
500                 }
501
502                 if (in_array($mode, ['network-new', 'search', 'contact-posts'])) {
503
504                         /*
505                          * "New Item View" on network page or search page results
506                          * - just loop through the items and format them minimally for display
507                          */
508
509                         $tpl = 'search_item.tpl';
510
511                         foreach ($items as $item) {
512
513                                 if (!visible_activity($item)) {
514                                         continue;
515                                 }
516
517                                 if (in_array($item['author-id'], $blocklist)) {
518                                         continue;
519                                 }
520
521                                 $threadsid++;
522
523                                 // prevent private email from leaking.
524                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
525                                         continue;
526                                 }
527
528                                 $profile_name = $item['author-name'];
529                                 if (!empty($item['author-link']) && empty($item['author-name'])) {
530                                         $profile_name = $item['author-link'];
531                                 }
532
533                                 $tags = Tag::populateFromItem($item);
534
535                                 $author = ['uid' => 0, 'id' => $item['author-id'],
536                                         'network' => $item['author-network'], 'url' => $item['author-link']];
537                                 $profile_link = Contact::magicLinkByContact($author);
538
539                                 $sparkle = '';
540                                 if (strpos($profile_link, 'redir/') === 0) {
541                                         $sparkle = ' sparkle';
542                                 }
543
544                                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
545                                 Hook::callAll('render_location',$locate);
546                                 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
547
548                                 localize_item($item);
549                                 if ($mode === 'network-new') {
550                                         $dropping = true;
551                                 } else {
552                                         $dropping = false;
553                                 }
554
555                                 $drop = [
556                                         'dropping' => $dropping,
557                                         'pagedrop' => $page_dropping,
558                                         'select' => DI::l10n()->t('Select'),
559                                         'delete' => DI::l10n()->t('Delete'),
560                                 ];
561
562                                 $likebuttons = [
563                                         'like'    => null,
564                                         'dislike' => null,
565                                         'share'   => null,
566                                 ];
567
568                                 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
569                                         unset($likebuttons['dislike']);
570                                 }
571
572                                 $body_html = Item::prepareBody($item, true, $preview);
573
574                                 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
575
576                                 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
577                                         $title = ucfirst($item['content-warning']);
578                                 } else {
579                                         $title = $item['title'];
580                                 }
581
582                                 $tmp_item = [
583                                         'template' => $tpl,
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_html' => item_photo_menu($item),
592                                         'name' => $profile_name,
593                                         'sparkle' => $sparkle,
594                                         'lock' => false,
595                                         'thumb' => DI::baseUrl()->remove($item['author-avatar']),
596                                         'title' => $title,
597                                         'body_html' => $body_html,
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_html),
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_html' => $location_html,
612                                         'indent' => '',
613                                         'owner_name' => '',
614                                         'owner_url' => '',
615                                         'owner_photo' => DI::baseUrl()->remove($item['owner-avatar']),
616                                         'plink' => Item::getPlink($item),
617                                         'edpost' => false,
618                                         'isstarred' => 'unstarred',
619                                         'star' => false,
620                                         'drop' => $drop,
621                                         'vote' => $likebuttons,
622                                         'like_html' => '',
623                                         'dislike_html' => '',
624                                         'comment_html' => '',
625                                         'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> DI::l10n()->t('View in context')]),
626                                         'previewing' => $previewing,
627                                         'wait' => DI::l10n()->t('Please wait'),
628                                         'thread_level' => 1,
629                                 ];
630
631                                 $arr = ['item' => $item, 'output' => $tmp_item];
632                                 Hook::callAll('display_item', $arr);
633
634                                 $threads[$threadsid]['id'] = $item['id'];
635                                 $threads[$threadsid]['network'] = $item['network'];
636                                 $threads[$threadsid]['items'] = [$arr['output']];
637
638                         }
639                 } else {
640                         // Normal View
641                         $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
642
643                         $conv = new Thread($mode, $preview, $writable);
644
645                         /*
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
649                          */
650                         foreach ($items as $item) {
651                                 if (in_array($item['author-id'], $blocklist)) {
652                                         continue;
653                                 }
654
655                                 // Can we put this after the visibility check?
656                                 builtin_activity_puller($item, $conv_responses);
657
658                                 // Only add what is visible
659                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
660                                         continue;
661                                 }
662
663                                 if (!visible_activity($item)) {
664                                         continue;
665                                 }
666
667                                 /// @todo Check if this call is needed or not
668                                 $arr = ['item' => $item];
669                                 Hook::callAll('display_item', $arr);
670
671                                 $item['pagedrop'] = $page_dropping;
672
673                                 if ($item['gravity'] == GRAVITY_PARENT) {
674                                         $item_object = new Post($item);
675                                         $conv->addParent($item_object);
676                                 }
677                         }
678
679                         $threads = $conv->getTemplateData($conv_responses);
680                         if (!$threads) {
681                                 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
682                                 $threads = [];
683                         }
684                 }
685         }
686
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'),
692                 '$mode' => $mode,
693                 '$user' => $a->user,
694                 '$threads' => $threads,
695                 '$dropping' => ($page_dropping ? DI::l10n()->t('Delete Selected Items') : False),
696         ]);
697
698         return $o;
699 }
700
701 /**
702  * Fetch all comments from a query. Additionally set the newest resharer as thread owner.
703  *
704  * @param mixed   $thread_items Database statement with thread posts
705  * @param boolean $pinned       Is the item pinned?
706  *
707  * @return array items with parents and comments
708  */
709 function conversation_fetch_comments($thread_items, $pinned) {
710         $comments = [];
711         $parentlines = [];
712         $lineno = 0;
713         $direction = [];
714         $actor = [];
715         $received = '';
716
717         while ($row = Item::fetch($thread_items)) {
718                 if (!empty($parentlines) && ($row['verb'] == Activity::ANNOUNCE)
719                         && ($row['thr-parent'] == $row['parent-uri']) && ($row['received'] > $received)
720                         && Contact::isSharing($row['author-id'], $row['uid'])) {
721                         $direction = ['direction' => 3, 'title' => DI::l10n()->t('%s reshared this.', $row['author-name'])];
722
723                         $author = ['uid' => 0, 'id' => $row['author-id'],
724                                 'network' => $row['author-network'], 'url' => $row['author-link']];
725                         $url = '<a href="'. htmlentities(Contact::magicLinkByContact($author)) .'">' . htmlentities($row['author-name']) . '</a>';
726
727                         $actor = ['url' => $url, 'link' => $row['author-link'], 'avatar' => $row['author-avatar'], 'name' => $row['author-name']];
728                         $received = $row['received'];
729                 }
730
731                 if (!empty($parentlines) && empty($direction) && ($row['gravity'] == GRAVITY_COMMENT)
732                         && Contact::isSharing($row['author-id'], $row['uid'])) {
733                         $direction = ['direction' => 5, 'title' => DI::l10n()->t('%s commented on this.', $row['author-name'])];
734                 }
735
736                 switch ($row['post-type']) {
737                         case Item::PT_TO:
738                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'to')];
739                                 break;
740                         case Item::PT_CC:
741                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'cc')];
742                                 break;
743                         case Item::PT_BTO:
744                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bto')];
745                                 break;
746                         case Item::PT_BCC:
747                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bcc')];
748                                 break;
749                         case Item::PT_FOLLOWER:
750                                 $row['direction'] = ['direction' => 6, 'title' => DI::l10n()->t('You are following %s.', $row['author-name'])];
751                                 break;
752                         case Item::PT_TAG:
753                                 $row['direction'] = ['direction' => 4, 'title' => DI::l10n()->t('Tagged')];
754                                 break;
755                         case Item::PT_ANNOUNCEMENT:
756                                 $row['direction'] = ['direction' => 3, 'title' => DI::l10n()->t('Reshared')];
757                                 break;
758                         case Item::PT_COMMENT:
759                                 $row['direction'] = ['direction' => 5, 'title' => DI::l10n()->t('%s is participating in this thread.', $row['author-name'])];
760                                 break;
761                         case Item::PT_STORED:
762                                 $row['direction'] = ['direction' => 8, 'title' => DI::l10n()->t('Stored')];
763                                 break;
764                         case Item::PT_GLOBAL:
765                                 $row['direction'] = ['direction' => 9, 'title' => DI::l10n()->t('Global')];
766                                 break;
767                         case Item::PT_RELAY:
768                                 $row['direction'] = ['direction' => 10, 'title' => DI::l10n()->t('Relay')];
769                                 break;
770                         case Item::PT_FETCHED:
771                                 $row['direction'] = ['direction' => 2, 'title' => DI::l10n()->t('Fetched')];
772                                 break;
773                         }
774
775                 if (($row['gravity'] == GRAVITY_PARENT) && !$row['origin'] && ($row['author-id'] == $row['owner-id']) &&
776                         !Contact::isSharing($row['author-id'], $row['uid'])) {
777                         $parentlines[] = $lineno;
778                 }
779
780                 if ($row['gravity'] == GRAVITY_PARENT) {
781                         $row['pinned'] = $pinned;
782                 }
783
784                 $comments[] = $row;
785                 $lineno++;
786         }
787
788         DBA::close($thread_items);
789
790         if (!empty($direction)) {
791                 foreach ($parentlines as $line) {
792                         $comments[$line]['direction'] = $direction;
793                         if (!empty($actor)) {
794                                 $comments[$line]['reshared'] = DI::l10n()->t('%s reshared this.', $actor['url']);
795                                 if (DI::pConfig()->get(local_user(), 'system', 'display_resharer')  ) {
796                                         $comments[$line]['owner-link'] = $actor['link'];
797                                         $comments[$line]['owner-avatar'] = $actor['avatar'];
798                                         $comments[$line]['owner-name'] = $actor['name'];
799                                 }
800                         }
801                 }
802         }
803         return $comments;
804 }
805
806 /**
807  * Add comments to top level entries that had been fetched before
808  *
809  * The system will fetch the comments for the local user whenever possible.
810  * This behaviour is currently needed to allow commenting on Friendica posts.
811  *
812  * @param array $parents Parent items
813  *
814  * @param       $block_authors
815  * @param       $order
816  * @param       $uid
817  * @return array items with parents and comments
818  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
819  */
820 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
821         if (count($parents) > 1) {
822                 $max_comments = DI::config()->get('system', 'max_comments', 100);
823         } else {
824                 $max_comments = DI::config()->get('system', 'max_display_comments', 1000);
825         }
826
827         $params = ['order' => ['gravity', 'uid', 'commented' => true]];
828
829         if ($max_comments > 0) {
830                 $params['limit'] = $max_comments;
831         }
832
833         $items = [];
834
835         foreach ($parents AS $parent) {
836                 $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
837                         $parent['uri'], $uid, Verb::getID(Activity::FOLLOW)];
838                 $items = conversation_fetch_items($parent, $items, $condition, $block_authors, $params);
839         }
840
841         foreach ($items as $index => $item) {
842                 if ($item['uid'] == 0) {
843                         $items[$index]['writable'] = in_array($item['network'], Protocol::FEDERATED);
844                 }
845         }
846
847         $items = conv_sort($items, $order);
848
849         return $items;
850 }
851
852 /**
853  * Fetch conversation items
854  *
855  * @param array $parent
856  * @param array $items
857  * @param array $condition
858  * @param boolean $block_authors
859  * @param array $params
860  * @return array
861  */
862 function conversation_fetch_items(array $parent, array $items, array $condition, bool $block_authors, array $params) {
863         if ($block_authors) {
864                 $condition[0] .= " AND NOT `author`.`hidden`";
865         }
866
867         $thread_items = Item::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['contact-uid', 'gravity', 'post-type']), $condition, $params);
868
869         $comments = conversation_fetch_comments($thread_items, $parent['pinned'] ?? false);
870
871         if (count($comments) != 0) {
872                 $items = array_merge($items, $comments);
873         }
874         return $items;
875 }
876
877 function item_photo_menu($item) {
878         $sub_link = '';
879         $poke_link = '';
880         $contact_url = '';
881         $pm_url = '';
882         $status_link = '';
883         $photos_link = '';
884         $posts_link = '';
885         $block_link = '';
886         $ignore_link = '';
887
888         if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self']) {
889                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
890         }
891
892         $author = ['uid' => 0, 'id' => $item['author-id'],
893                 'network' => $item['author-network'], 'url' => $item['author-link']];
894         $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
895         $sparkle = (strpos($profile_link, 'redir/') === 0);
896
897         $cid = 0;
898         $pcid = Contact::getIdForURL($item['author-link'], 0, false);
899         $network = '';
900         $rel = 0;
901         $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
902         $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
903         if (DBA::isResult($contact)) {
904                 $cid = $contact['id'];
905                 $network = $contact['network'];
906                 $rel = $contact['rel'];
907         }
908
909         if ($sparkle) {
910                 $status_link = $profile_link . '/status';
911                 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
912                 $profile_link = $profile_link . '/profile';
913         }
914
915         if (!empty($pcid)) {
916                 $contact_url = 'contact/' . $pcid;
917                 $posts_link  = $contact_url . '/posts';
918                 $block_link  = $contact_url . '/block';
919                 $ignore_link = $contact_url . '/ignore';
920         }
921
922         if ($cid && !$item['self']) {
923                 $contact_url = 'contact/' . $cid;
924                 $poke_link   = $contact_url . '/poke';
925                 $posts_link  = $contact_url . '/posts';
926
927                 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
928                         $pm_url = 'message/new/' . $cid;
929                 }
930         }
931
932         if (local_user()) {
933                 $menu = [
934                         DI::l10n()->t('Follow Thread') => $sub_link,
935                         DI::l10n()->t('View Status') => $status_link,
936                         DI::l10n()->t('View Profile') => $profile_link,
937                         DI::l10n()->t('View Photos') => $photos_link,
938                         DI::l10n()->t('Network Posts') => $posts_link,
939                         DI::l10n()->t('View Contact') => $contact_url,
940                         DI::l10n()->t('Send PM') => $pm_url,
941                         DI::l10n()->t('Block') => $block_link,
942                         DI::l10n()->t('Ignore') => $ignore_link
943                 ];
944
945                 if ($network == Protocol::DFRN) {
946                         $menu[DI::l10n()->t("Poke")] = $poke_link;
947                 }
948
949                 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
950                         in_array($item['network'], Protocol::FEDERATED)) {
951                         $menu[DI::l10n()->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
952                 }
953         } else {
954                 $menu = [DI::l10n()->t('View Profile') => $item['author-link']];
955         }
956
957         $args = ['item' => $item, 'menu' => $menu];
958
959         Hook::callAll('item_photo_menu', $args);
960
961         $menu = $args['menu'];
962
963         $o = '';
964         foreach ($menu as $k => $v) {
965                 if (strpos($v, 'javascript:') === 0) {
966                         $v = substr($v, 11);
967                         $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
968                 } elseif ($v!='') {
969                         $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
970                 }
971         }
972         return $o;
973 }
974
975 /**
976  * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
977  *
978  * Increments the count of each matching activity and adds a link to the author as needed.
979  *
980  * @param array  $item
981  * @param array &$conv_responses (already created with builtin activity structure)
982  * @return void
983  * @throws ImagickException
984  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
985  */
986 function builtin_activity_puller($item, &$conv_responses) {
987         foreach ($conv_responses as $mode => $v) {
988                 $sparkle = '';
989
990                 switch ($mode) {
991                         case 'like':
992                                 $verb = Activity::LIKE;
993                                 break;
994                         case 'dislike':
995                                 $verb = Activity::DISLIKE;
996                                 break;
997                         case 'attendyes':
998                                 $verb = Activity::ATTEND;
999                                 break;
1000                         case 'attendno':
1001                                 $verb = Activity::ATTENDNO;
1002                                 break;
1003                         case 'attendmaybe':
1004                                 $verb = Activity::ATTENDMAYBE;
1005                                 break;
1006                         case 'announce':
1007                                 $verb = Activity::ANNOUNCE;
1008                                 break;
1009                         default:
1010                                 return;
1011                 }
1012
1013                 if (!empty($item['verb']) && DI::activity()->match($item['verb'], $verb) && ($item['gravity'] != GRAVITY_PARENT)) {
1014                         $author = ['uid' => 0, 'id' => $item['author-id'],
1015                                 'network' => $item['author-network'], 'url' => $item['author-link']];
1016                         $url = Contact::magicLinkByContact($author);
1017                         if (strpos($url, 'redir/') === 0) {
1018                                 $sparkle = ' class="sparkle" ';
1019                         }
1020
1021                         $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
1022
1023                         if (empty($item['thr-parent'])) {
1024                                 $item['thr-parent'] = $item['parent-uri'];
1025                         }
1026
1027                         if (!(isset($conv_responses[$mode][$item['thr-parent'] . '-l'])
1028                                 && is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))) {
1029                                 $conv_responses[$mode][$item['thr-parent'] . '-l'] = [];
1030                         }
1031
1032                         // only list each unique author once
1033                         if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
1034                                 continue;
1035                         }
1036
1037                         if (!isset($conv_responses[$mode][$item['thr-parent']])) {
1038                                 $conv_responses[$mode][$item['thr-parent']] = 1;
1039                         } else {
1040                                 $conv_responses[$mode][$item['thr-parent']] ++;
1041                         }
1042
1043                         if (public_contact() == $item['author-id']) {
1044                                 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
1045                         }
1046
1047                         $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
1048
1049                         // there can only be one activity verb per item so if we found anything, we can stop looking
1050                         return;
1051                 }
1052         }
1053 }
1054
1055 /**
1056  * Format the vote text for a profile item
1057  *
1058  * @param int    $cnt  = number of people who vote the item
1059  * @param array  $arr  = array of pre-linked names of likers/dislikers
1060  * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1061  * @param int    $id   = item id
1062  * @return string formatted text
1063  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1064  */
1065 function format_like($cnt, array $arr, $type, $id) {
1066         $o = '';
1067         $expanded = '';
1068         $phrase = '';
1069
1070         if ($cnt == 1) {
1071                 $likers = $arr[0];
1072
1073                 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1074                 // list which show all likers
1075                 switch ($type) {
1076                         case 'like' :
1077                                 $phrase = DI::l10n()->t('%s likes this.', $likers);
1078                                 break;
1079                         case 'dislike' :
1080                                 $phrase = DI::l10n()->t('%s doesn\'t like this.', $likers);
1081                                 break;
1082                         case 'attendyes' :
1083                                 $phrase = DI::l10n()->t('%s attends.', $likers);
1084                                 break;
1085                         case 'attendno' :
1086                                 $phrase = DI::l10n()->t('%s doesn\'t attend.', $likers);
1087                                 break;
1088                         case 'attendmaybe' :
1089                                 $phrase = DI::l10n()->t('%s attends maybe.', $likers);
1090                                 break;
1091                         case 'announce' :
1092                                 $phrase = DI::l10n()->t('%s reshared this.', $likers);
1093                                 break;
1094                 }
1095         }
1096
1097         if ($cnt > 1) {
1098                 $total = count($arr);
1099                 if ($total < MAX_LIKERS) {
1100                         $last = DI::l10n()->t('and') . ' ' . $arr[count($arr)-1];
1101                         $arr2 = array_slice($arr, 0, -1);
1102                         $likers = implode(', ', $arr2) . ' ' . $last;
1103                 } else  {
1104                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1105                         $likers = implode(', ', $arr);
1106                         $likers .= DI::l10n()->t('and %d other people', $total - MAX_LIKERS);
1107                 }
1108
1109                 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1110
1111                 $explikers = '';
1112                 switch ($type) {
1113                         case 'like':
1114                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> like this', $spanatts, $cnt);
1115                                 $explikers = DI::l10n()->t('%s like this.', $likers);
1116                                 break;
1117                         case 'dislike':
1118                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> don\'t like this', $spanatts, $cnt);
1119                                 $explikers = DI::l10n()->t('%s don\'t like this.', $likers);
1120                                 break;
1121                         case 'attendyes':
1122                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> attend', $spanatts, $cnt);
1123                                 $explikers = DI::l10n()->t('%s attend.', $likers);
1124                                 break;
1125                         case 'attendno':
1126                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> don\'t attend', $spanatts, $cnt);
1127                                 $explikers = DI::l10n()->t('%s don\'t attend.', $likers);
1128                                 break;
1129                         case 'attendmaybe':
1130                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> attend maybe', $spanatts, $cnt);
1131                                 $explikers = DI::l10n()->t('%s attend maybe.', $likers);
1132                                 break;
1133                         case 'announce':
1134                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> reshared this', $spanatts, $cnt);
1135                                 $explikers = DI::l10n()->t('%s reshared this.', $likers);
1136                                 break;
1137                 }
1138
1139                 $expanded .= "\t" . '<p class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1140         }
1141
1142         $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1143                 '$phrase' => $phrase,
1144                 '$type' => $type,
1145                 '$id' => $id
1146         ]);
1147         $o .= $expanded;
1148
1149         return $o;
1150 }
1151
1152 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1153 {
1154         $o = '';
1155
1156         $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1157
1158         $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1159         DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
1160                 '$newpost'   => 'true',
1161                 '$baseurl'   => DI::baseUrl()->get(true),
1162                 '$geotag'    => $geotag,
1163                 '$nickname'  => $x['nickname'],
1164                 '$ispublic'  => DI::l10n()->t('Visible to <strong>everybody</strong>'),
1165                 '$linkurl'   => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1166                 '$term'      => DI::l10n()->t('Tag term:'),
1167                 '$fileas'    => DI::l10n()->t('Save to Folder:'),
1168                 '$whereareu' => DI::l10n()->t('Where are you right now?'),
1169                 '$delitems'  => DI::l10n()->t("Delete item\x28s\x29?")
1170         ]);
1171
1172         $jotplugins = '';
1173         Hook::callAll('jot_tool', $jotplugins);
1174
1175         // $tpl = Renderer::replaceMacros($tpl,array('$jotplugins' => $jotplugins));
1176         $tpl = Renderer::getMarkupTemplate("jot.tpl");
1177
1178         $o .= Renderer::replaceMacros($tpl,[
1179                 '$new_post' => DI::l10n()->t('New Post'),
1180                 '$return_path'  => DI::args()->getQueryString(),
1181                 '$action'       => 'item',
1182                 '$share'        => ($x['button'] ?? '') ?: DI::l10n()->t('Share'),
1183                 '$loading'      => DI::l10n()->t('Loading...'),
1184                 '$upload'       => DI::l10n()->t('Upload photo'),
1185                 '$shortupload'  => DI::l10n()->t('upload photo'),
1186                 '$attach'       => DI::l10n()->t('Attach file'),
1187                 '$shortattach'  => DI::l10n()->t('attach file'),
1188                 '$edbold'       => DI::l10n()->t('Bold'),
1189                 '$editalic'     => DI::l10n()->t('Italic'),
1190                 '$eduline'      => DI::l10n()->t('Underline'),
1191                 '$edquote'      => DI::l10n()->t('Quote'),
1192                 '$edcode'       => DI::l10n()->t('Code'),
1193                 '$edimg'        => DI::l10n()->t('Image'),
1194                 '$edurl'        => DI::l10n()->t('Link'),
1195                 '$edattach'     => DI::l10n()->t('Link or Media'),
1196                 '$setloc'       => DI::l10n()->t('Set your location'),
1197                 '$shortsetloc'  => DI::l10n()->t('set location'),
1198                 '$noloc'        => DI::l10n()->t('Clear browser location'),
1199                 '$shortnoloc'   => DI::l10n()->t('clear location'),
1200                 '$title'        => $x['title'] ?? '',
1201                 '$placeholdertitle' => DI::l10n()->t('Set title'),
1202                 '$category'     => $x['category'] ?? '',
1203                 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1204                 '$wait'         => DI::l10n()->t('Please wait'),
1205                 '$permset'      => DI::l10n()->t('Permission settings'),
1206                 '$shortpermset' => DI::l10n()->t('Permissions'),
1207                 '$wall'         => $notes_cid ? 0 : 1,
1208                 '$posttype'     => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1209                 '$content'      => $x['content'] ?? '',
1210                 '$post_id'      => $x['post_id'] ?? '',
1211                 '$baseurl'      => DI::baseUrl()->get(true),
1212                 '$defloc'       => $x['default_location'],
1213                 '$visitor'      => $x['visitor'],
1214                 '$pvisit'       => $notes_cid ? 'none' : $x['visitor'],
1215                 '$public'       => DI::l10n()->t('Public post'),
1216                 '$lockstate'    => $x['lockstate'],
1217                 '$bang'         => $x['bang'],
1218                 '$profile_uid'  => $x['profile_uid'],
1219                 '$preview'      => DI::l10n()->t('Preview'),
1220                 '$jotplugins'   => $jotplugins,
1221                 '$notes_cid'    => $notes_cid,
1222                 '$sourceapp'    => DI::l10n()->t($a->sourcename),
1223                 '$cancel'       => DI::l10n()->t('Cancel'),
1224                 '$rand_num'     => Crypto::randomDigits(12),
1225
1226                 // ACL permissions box
1227                 '$acl'           => $x['acl'],
1228
1229                 //jot nav tab (used in some themes)
1230                 '$message' => DI::l10n()->t('Message'),
1231                 '$browser' => DI::l10n()->t('Browser'),
1232
1233                 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1234         ]);
1235
1236
1237         if ($popup == true) {
1238                 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1239         }
1240
1241         return $o;
1242 }
1243
1244 /**
1245  * Plucks the children of the given parent from a given item list.
1246  *
1247  * @param array $item_list
1248  * @param array $parent
1249  * @param bool  $recursive
1250  * @return array
1251  */
1252 function get_item_children(array &$item_list, array $parent, $recursive = true)
1253 {
1254         $children = [];
1255         foreach ($item_list as $i => $item) {
1256                 if ($item['gravity'] != GRAVITY_PARENT) {
1257                         if ($recursive) {
1258                                 // Fallback to parent-uri if thr-parent is not set
1259                                 $thr_parent = $item['thr-parent'];
1260                                 if ($thr_parent == '') {
1261                                         $thr_parent = $item['parent-uri'];
1262                                 }
1263
1264                                 if ($thr_parent == $parent['uri']) {
1265                                         $item['children'] = get_item_children($item_list, $item);
1266                                         $children[] = $item;
1267                                         unset($item_list[$i]);
1268                                 }
1269                         } elseif ($item['parent'] == $parent['id']) {
1270                                 $children[] = $item;
1271                                 unset($item_list[$i]);
1272                         }
1273                 }
1274         }
1275         return $children;
1276 }
1277
1278 /**
1279  * Recursively sorts a tree-like item array
1280  *
1281  * @param array $items
1282  * @return array
1283  */
1284 function sort_item_children(array $items)
1285 {
1286         $result = $items;
1287         usort($result, 'sort_thr_received_rev');
1288         foreach ($result as $k => $i) {
1289                 if (isset($result[$k]['children'])) {
1290                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1291                 }
1292         }
1293         return $result;
1294 }
1295
1296 /**
1297  * Recursively add all children items at the top level of a list
1298  *
1299  * @param array $children List of items to append
1300  * @param array $item_list
1301  */
1302 function add_children_to_list(array $children, array &$item_list)
1303 {
1304         foreach ($children as $child) {
1305                 $item_list[] = $child;
1306                 if (isset($child['children'])) {
1307                         add_children_to_list($child['children'], $item_list);
1308                 }
1309         }
1310 }
1311
1312 /**
1313  * Selectively flattens a tree-like item structure to prevent threading stairs
1314  *
1315  * This recursive function takes the item tree structure created by conv_sort() and
1316  * flatten the extraneous depth levels when people reply sequentially, removing the
1317  * stairs effect in threaded conversations limiting the available content width.
1318  *
1319  * The basic principle is the following: if a post item has only one reply and is
1320  * the last reply of its parent, then the reply is moved to the parent.
1321  *
1322  * This process is rendered somewhat more complicated because items can be either
1323  * replies or likes, and these don't factor at all in the reply count/last reply.
1324  *
1325  * @param array $parent A tree-like array of items
1326  * @return array
1327  */
1328 function smart_flatten_conversation(array $parent)
1329 {
1330         if (!isset($parent['children']) || count($parent['children']) == 0) {
1331                 return $parent;
1332         }
1333
1334         // We use a for loop to ensure we process the newly-moved items
1335         for ($i = 0; $i < count($parent['children']); $i++) {
1336                 $child = $parent['children'][$i];
1337
1338                 if (isset($child['children']) && count($child['children'])) {
1339                         // This helps counting only the regular posts
1340                         $count_post_closure = function($var) {
1341                                 return $var['verb'] === Activity::POST;
1342                         };
1343
1344                         $child_post_count = count(array_filter($child['children'], $count_post_closure));
1345
1346                         $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1347
1348                         // If there's only one child's children post and this is the last child post
1349                         if ($child_post_count == 1 && $remaining_post_count == 1) {
1350
1351                                 // Searches the post item in the children
1352                                 $j = 0;
1353                                 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1354                                         $j ++;
1355                                 }
1356
1357                                 $moved_item = $child['children'][$j];
1358                                 unset($parent['children'][$i]['children'][$j]);
1359                                 $parent['children'][] = $moved_item;
1360                         } else {
1361                                 $parent['children'][$i] = smart_flatten_conversation($child);
1362                         }
1363                 }
1364         }
1365
1366         return $parent;
1367 }
1368
1369
1370 /**
1371  * Expands a flat list of items into corresponding tree-like conversation structures.
1372  *
1373  * sort the top-level posts either on "received" or "commented", and finally
1374  * append all the items at the top level (???)
1375  *
1376  * @param array  $item_list A list of items belonging to one or more conversations
1377  * @param string $order     Either on "received" or "commented"
1378  * @return array
1379  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1380  */
1381 function conv_sort(array $item_list, $order)
1382 {
1383         $parents = [];
1384
1385         if (!(is_array($item_list) && count($item_list))) {
1386                 return $parents;
1387         }
1388
1389         $blocklist = conv_get_blocklist();
1390
1391         $item_array = [];
1392
1393         // Dedupes the item list on the uri to prevent infinite loops
1394         foreach ($item_list as $item) {
1395                 if (in_array($item['author-id'], $blocklist)) {
1396                         continue;
1397                 }
1398
1399                 $item_array[$item['uri']] = $item;
1400         }
1401
1402         // Extract the top level items
1403         foreach ($item_array as $item) {
1404                 if ($item['gravity'] == GRAVITY_PARENT) {
1405                         $parents[] = $item;
1406                 }
1407         }
1408
1409         if (stristr($order, 'pinned_received')) {
1410                 usort($parents, 'sort_thr_pinned_received');
1411         } elseif (stristr($order, 'received')) {
1412                 usort($parents, 'sort_thr_received');
1413         } elseif (stristr($order, 'commented')) {
1414                 usort($parents, 'sort_thr_commented');
1415         }
1416
1417         /*
1418          * Plucks children from the item_array, second pass collects eventual orphan
1419          * items and add them as children of their top-level post.
1420          */
1421         foreach ($parents as $i => $parent) {
1422                 $parents[$i]['children'] =
1423                         array_merge(get_item_children($item_array, $parent, true),
1424                                 get_item_children($item_array, $parent, false));
1425         }
1426
1427         foreach ($parents as $i => $parent) {
1428                 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1429         }
1430
1431         if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
1432                 foreach ($parents as $i => $parent) {
1433                         $parents[$i] = smart_flatten_conversation($parent);
1434                 }
1435         }
1436
1437         /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1438         /// However, this apparently ensures responses (likes, attendance) display (?!)
1439         foreach ($parents as $parent) {
1440                 if (count($parent['children'])) {
1441                         add_children_to_list($parent['children'], $parents);
1442                 }
1443         }
1444
1445         return $parents;
1446 }
1447
1448 /**
1449  * usort() callback to sort item arrays by pinned and the received key
1450  *
1451  * @param array $a
1452  * @param array $b
1453  * @return int
1454  */
1455 function sort_thr_pinned_received(array $a, array $b)
1456 {
1457         if ($b['pinned'] && !$a['pinned']) {
1458                 return 1;
1459         } elseif (!$b['pinned'] && $a['pinned']) {
1460                 return -1;
1461         }
1462
1463         return strcmp($b['received'], $a['received']);
1464 }
1465
1466 /**
1467  * usort() callback to sort item arrays by the received key
1468  *
1469  * @param array $a
1470  * @param array $b
1471  * @return int
1472  */
1473 function sort_thr_received(array $a, array $b)
1474 {
1475         return strcmp($b['received'], $a['received']);
1476 }
1477
1478 /**
1479  * usort() callback to reverse sort item arrays by the received key
1480  *
1481  * @param array $a
1482  * @param array $b
1483  * @return int
1484  */
1485 function sort_thr_received_rev(array $a, array $b)
1486 {
1487         return strcmp($a['received'], $b['received']);
1488 }
1489
1490 /**
1491  * usort() callback to sort item arrays by the commented key
1492  *
1493  * @param array $a
1494  * @param array $b
1495  * @return int
1496  */
1497 function sort_thr_commented(array $a, array $b)
1498 {
1499         return strcmp($b['commented'], $a['commented']);
1500 }