]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
Merge pull request #9323 from annando/notice
[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='
447                                 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
448                                 . "'; </script>\r\n";
449                 }
450         } elseif ($mode === 'contacts') {
451                 $items = conversation_add_children($items, false, $order, $uid);
452                 $profile_owner = 0;
453
454                 if (!$update) {
455                         $live_update_div = '<div id="live-contacts"></div>' . "\r\n"
456                                 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 9)
457                                 ."/?f='; </script>\r\n";
458                 }
459         } elseif ($mode === 'search') {
460                 $live_update_div = '<div id="live-search"></div>' . "\r\n";
461         }
462
463         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
464
465         if (!$update) {
466                 $_SESSION['return_path'] = DI::args()->getQueryString();
467         }
468
469         $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
470         Hook::callAll('conversation_start',$cb);
471
472         $items = $cb['items'];
473
474         $conv_responses = [
475                 'like'        => [],
476                 'dislike'     => [],
477                 'attendyes'   => [],
478                 'attendno'    => [],
479                 'attendmaybe' => [],
480                 'announce'    => [],    
481         ];
482
483         if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
484                 unset($conv_responses['dislike']);
485         }
486
487         // array with html for each thread (parent+comments)
488         $threads = [];
489         $threadsid = -1;
490
491         $page_template = Renderer::getMarkupTemplate("conversation.tpl");
492
493         if (!empty($items)) {
494                 if (in_array($mode, ['community', 'contacts'])) {
495                         $writable = true;
496                 } else {
497                         $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
498                 }
499
500                 if (!local_user()) {
501                         $writable = false;
502                 }
503
504                 if (in_array($mode, ['network-new', 'search', 'contact-posts'])) {
505
506                         /*
507                          * "New Item View" on network page or search page results
508                          * - just loop through the items and format them minimally for display
509                          */
510
511                         $tpl = 'search_item.tpl';
512
513                         foreach ($items as $item) {
514
515                                 if (!visible_activity($item)) {
516                                         continue;
517                                 }
518
519                                 if (in_array($item['author-id'], $blocklist)) {
520                                         continue;
521                                 }
522
523                                 $threadsid++;
524
525                                 // prevent private email from leaking.
526                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
527                                         continue;
528                                 }
529
530                                 $profile_name = $item['author-name'];
531                                 if (!empty($item['author-link']) && empty($item['author-name'])) {
532                                         $profile_name = $item['author-link'];
533                                 }
534
535                                 $tags = Tag::populateFromItem($item);
536
537                                 $author = ['uid' => 0, 'id' => $item['author-id'],
538                                         'network' => $item['author-network'], 'url' => $item['author-link']];
539                                 $profile_link = Contact::magicLinkByContact($author);
540
541                                 $sparkle = '';
542                                 if (strpos($profile_link, 'redir/') === 0) {
543                                         $sparkle = ' sparkle';
544                                 }
545
546                                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
547                                 Hook::callAll('render_location',$locate);
548                                 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
549
550                                 localize_item($item);
551                                 if ($mode === 'network-new') {
552                                         $dropping = true;
553                                 } else {
554                                         $dropping = false;
555                                 }
556
557                                 $drop = [
558                                         'dropping' => $dropping,
559                                         'pagedrop' => $page_dropping,
560                                         'select' => DI::l10n()->t('Select'),
561                                         'delete' => DI::l10n()->t('Delete'),
562                                 ];
563
564                                 $likebuttons = [
565                                         'like'    => null,
566                                         'dislike' => null,
567                                         'share'   => null,
568                                 ];
569
570                                 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
571                                         unset($likebuttons['dislike']);
572                                 }
573
574                                 $body_html = Item::prepareBody($item, true, $preview);
575
576                                 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
577
578                                 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
579                                         $title = ucfirst($item['content-warning']);
580                                 } else {
581                                         $title = $item['title'];
582                                 }
583
584                                 $tmp_item = [
585                                         'template' => $tpl,
586                                         'id' => ($preview ? 'P0' : $item['id']),
587                                         'guid' => ($preview ? 'Q0' : $item['guid']),
588                                         'network' => $item['network'],
589                                         'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
590                                         'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link']),
591                                         'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
592                                         'profile_url' => $profile_link,
593                                         'item_photo_menu_html' => item_photo_menu($item),
594                                         'name' => $profile_name,
595                                         'sparkle' => $sparkle,
596                                         'lock' => false,
597                                         'thumb' => DI::baseUrl()->remove($item['author-avatar']),
598                                         'title' => $title,
599                                         'body_html' => $body_html,
600                                         'tags' => $tags['tags'],
601                                         'hashtags' => $tags['hashtags'],
602                                         'mentions' => $tags['mentions'],
603                                         'implicit_mentions' => $tags['implicit_mentions'],
604                                         'txt_cats' => DI::l10n()->t('Categories:'),
605                                         'txt_folders' => DI::l10n()->t('Filed under:'),
606                                         'has_cats' => ((count($categories)) ? 'true' : ''),
607                                         'has_folders' => ((count($folders)) ? 'true' : ''),
608                                         'categories' => $categories,
609                                         'folders' => $folders,
610                                         'text' => strip_tags($body_html),
611                                         'localtime' => DateTimeFormat::local($item['created'], 'r'),
612                                         'ago' => (($item['app']) ? DI::l10n()->t('%s from %s', Temporal::getRelativeDate($item['created']),$item['app']) : Temporal::getRelativeDate($item['created'])),
613                                         'location_html' => $location_html,
614                                         'indent' => '',
615                                         'owner_name' => '',
616                                         'owner_url' => '',
617                                         'owner_photo' => DI::baseUrl()->remove($item['owner-avatar']),
618                                         'plink' => Item::getPlink($item),
619                                         'edpost' => false,
620                                         'isstarred' => 'unstarred',
621                                         'star' => false,
622                                         'drop' => $drop,
623                                         'vote' => $likebuttons,
624                                         'like_html' => '',
625                                         'dislike_html' => '',
626                                         'comment_html' => '',
627                                         'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> DI::l10n()->t('View in context')]),
628                                         'previewing' => $previewing,
629                                         'wait' => DI::l10n()->t('Please wait'),
630                                         'thread_level' => 1,
631                                 ];
632
633                                 $arr = ['item' => $item, 'output' => $tmp_item];
634                                 Hook::callAll('display_item', $arr);
635
636                                 $threads[$threadsid]['id'] = $item['id'];
637                                 $threads[$threadsid]['network'] = $item['network'];
638                                 $threads[$threadsid]['items'] = [$arr['output']];
639
640                         }
641                 } else {
642                         // Normal View
643                         $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
644
645                         $conv = new Thread($mode, $preview, $writable);
646
647                         /*
648                          * get all the topmost parents
649                          * this shouldn't be needed, as we should have only them in our array
650                          * But for now, this array respects the old style, just in case
651                          */
652                         foreach ($items as $item) {
653                                 if (in_array($item['author-id'], $blocklist)) {
654                                         continue;
655                                 }
656
657                                 // Can we put this after the visibility check?
658                                 builtin_activity_puller($item, $conv_responses);
659
660                                 // Only add what is visible
661                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
662                                         continue;
663                                 }
664
665                                 if (!visible_activity($item)) {
666                                         continue;
667                                 }
668
669                                 /// @todo Check if this call is needed or not
670                                 $arr = ['item' => $item];
671                                 Hook::callAll('display_item', $arr);
672
673                                 $item['pagedrop'] = $page_dropping;
674
675                                 if ($item['gravity'] == GRAVITY_PARENT) {
676                                         $item_object = new Post($item);
677                                         $conv->addParent($item_object);
678                                 }
679                         }
680
681                         $threads = $conv->getTemplateData($conv_responses);
682                         if (!$threads) {
683                                 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
684                                 $threads = [];
685                         }
686                 }
687         }
688
689         $o = Renderer::replaceMacros($page_template, [
690                 '$baseurl' => DI::baseUrl()->get($ssl_state),
691                 '$return_path' => DI::args()->getQueryString(),
692                 '$live_update' => $live_update_div,
693                 '$remove' => DI::l10n()->t('remove'),
694                 '$mode' => $mode,
695                 '$user' => $a->user,
696                 '$threads' => $threads,
697                 '$dropping' => ($page_dropping ? DI::l10n()->t('Delete Selected Items') : False),
698         ]);
699
700         return $o;
701 }
702
703 /**
704  * Fetch all comments from a query. Additionally set the newest resharer as thread owner.
705  *
706  * @param mixed   $thread_items Database statement with thread posts
707  * @param boolean $pinned       Is the item pinned?
708  *
709  * @return array items with parents and comments
710  */
711 function conversation_fetch_comments($thread_items, $pinned) {
712         $comments = [];
713
714         while ($row = Item::fetch($thread_items)) {
715                 $name = $row['causer-contact-type'] == Contact::TYPE_RELAY ? $row['causer-link'] : $row['causer-name'];
716
717                 switch ($row['post-type']) {
718                         case Item::PT_TO:
719                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'to')];
720                                 break;
721                         case Item::PT_CC:
722                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'cc')];
723                                 break;
724                         case Item::PT_BTO:
725                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bto')];
726                                 break;
727                         case Item::PT_BCC:
728                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bcc')];
729                                 break;
730                         case Item::PT_FOLLOWER:
731                                 $row['direction'] = ['direction' => 6, 'title' => DI::l10n()->t('You are following %s.', $row['author-name'])];
732                                 break;
733                         case Item::PT_TAG:
734                                 $row['direction'] = ['direction' => 4, 'title' => DI::l10n()->t('Tagged')];
735                                 break;
736                         case Item::PT_ANNOUNCEMENT:
737                                 if (!empty($row['causer-id']) && DI::pConfig()->get(local_user(), 'system', 'display_resharer')  ) {
738                                         $row['owner-link'] = $row['causer-link'];
739                                         $row['owner-avatar'] = $row['causer-avatar'];
740                                         $row['owner-name'] = $row['causer-name'];
741                                 }
742
743                                 if (($row['gravity'] == GRAVITY_PARENT) && !empty($row['causer-id'])) {
744                                         $row['reshared'] = DI::l10n()->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkbyId($row['causer-id'])) .'">' . htmlentities($name) . '</a>');
745                                 }
746                                 $row['direction'] = ['direction' => 3, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Reshared') : DI::l10n()->t('Reshared by %s', $name))];
747                                 break;
748                         case Item::PT_COMMENT:
749                                 $row['direction'] = ['direction' => 5, 'title' => DI::l10n()->t('%s is participating in this thread.', $row['author-name'])];
750                                 break;
751                         case Item::PT_STORED:
752                                 $row['direction'] = ['direction' => 8, 'title' => DI::l10n()->t('Stored')];
753                                 break;
754                         case Item::PT_GLOBAL:
755                                 $row['direction'] = ['direction' => 9, 'title' => DI::l10n()->t('Global')];
756                                 break;
757                         case Item::PT_RELAY:
758                                 $row['direction'] = ['direction' => 10, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Relayed') : DI::l10n()->t('Relayed by %s.', $name))];
759                                 break;
760                         case Item::PT_FETCHED:
761                                 $row['direction'] = ['direction' => 2, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Fetched') : DI::l10n()->t('Fetched because of %s', $name))];
762                                 break;
763                         }
764
765                 if ($row['gravity'] == GRAVITY_PARENT) {
766                         $row['pinned'] = $pinned;
767                 }
768
769                 $comments[] = $row;
770         }
771
772         DBA::close($thread_items);
773
774         return $comments;
775 }
776
777 /**
778  * Add comments to top level entries that had been fetched before
779  *
780  * The system will fetch the comments for the local user whenever possible.
781  * This behaviour is currently needed to allow commenting on Friendica posts.
782  *
783  * @param array $parents Parent items
784  *
785  * @param       $block_authors
786  * @param       $order
787  * @param       $uid
788  * @return array items with parents and comments
789  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
790  */
791 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
792         if (count($parents) > 1) {
793                 $max_comments = DI::config()->get('system', 'max_comments', 100);
794         } else {
795                 $max_comments = DI::config()->get('system', 'max_display_comments', 1000);
796         }
797
798         $params = ['order' => ['gravity', 'uid', 'commented' => true]];
799
800         if ($max_comments > 0) {
801                 $params['limit'] = $max_comments;
802         }
803
804         $items = [];
805
806         foreach ($parents AS $parent) {
807                 $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
808                         $parent['uri'], $uid, Verb::getID(Activity::FOLLOW)];
809                 $items = conversation_fetch_items($parent, $items, $condition, $block_authors, $params);
810         }
811
812         foreach ($items as $index => $item) {
813                 if ($item['uid'] == 0) {
814                         $items[$index]['writable'] = in_array($item['network'], Protocol::FEDERATED);
815                 }
816         }
817
818         $items = conv_sort($items, $order);
819
820         return $items;
821 }
822
823 /**
824  * Fetch conversation items
825  *
826  * @param array $parent
827  * @param array $items
828  * @param array $condition
829  * @param boolean $block_authors
830  * @param array $params
831  * @return array
832  */
833 function conversation_fetch_items(array $parent, array $items, array $condition, bool $block_authors, array $params) {
834         if ($block_authors) {
835                 $condition[0] .= " AND NOT `author`.`hidden`";
836         }
837
838         $thread_items = Item::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['contact-uid', 'gravity', 'post-type']), $condition, $params);
839
840         $comments = conversation_fetch_comments($thread_items, $parent['pinned'] ?? false);
841
842         if (count($comments) != 0) {
843                 $items = array_merge($items, $comments);
844         }
845         return $items;
846 }
847
848 function item_photo_menu($item) {
849         $sub_link = '';
850         $poke_link = '';
851         $contact_url = '';
852         $pm_url = '';
853         $status_link = '';
854         $photos_link = '';
855         $posts_link = '';
856         $block_link = '';
857         $ignore_link = '';
858
859         if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self']) {
860                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
861         }
862
863         $author = ['uid' => 0, 'id' => $item['author-id'],
864                 'network' => $item['author-network'], 'url' => $item['author-link']];
865         $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
866         $sparkle = (strpos($profile_link, 'redir/') === 0);
867
868         $cid = 0;
869         $pcid = Contact::getIdForURL($item['author-link'], 0, false);
870         $network = '';
871         $rel = 0;
872         $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
873         $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
874         if (DBA::isResult($contact)) {
875                 $cid = $contact['id'];
876                 $network = $contact['network'];
877                 $rel = $contact['rel'];
878         }
879
880         if ($sparkle) {
881                 $status_link = $profile_link . '/status';
882                 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
883                 $profile_link = $profile_link . '/profile';
884         }
885
886         if (!empty($pcid)) {
887                 $contact_url = 'contact/' . $pcid;
888                 $posts_link  = $contact_url . '/posts';
889                 $block_link  = $contact_url . '/block';
890                 $ignore_link = $contact_url . '/ignore';
891         }
892
893         if ($cid && !$item['self']) {
894                 $contact_url = 'contact/' . $cid;
895                 $poke_link   = $contact_url . '/poke';
896                 $posts_link  = $contact_url . '/posts';
897
898                 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
899                         $pm_url = 'message/new/' . $cid;
900                 }
901         }
902
903         if (local_user()) {
904                 $menu = [
905                         DI::l10n()->t('Follow Thread') => $sub_link,
906                         DI::l10n()->t('View Status') => $status_link,
907                         DI::l10n()->t('View Profile') => $profile_link,
908                         DI::l10n()->t('View Photos') => $photos_link,
909                         DI::l10n()->t('Network Posts') => $posts_link,
910                         DI::l10n()->t('View Contact') => $contact_url,
911                         DI::l10n()->t('Send PM') => $pm_url,
912                         DI::l10n()->t('Block') => $block_link,
913                         DI::l10n()->t('Ignore') => $ignore_link
914                 ];
915
916                 if ($network == Protocol::DFRN) {
917                         $menu[DI::l10n()->t("Poke")] = $poke_link;
918                 }
919
920                 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
921                         in_array($item['network'], Protocol::FEDERATED)) {
922                         $menu[DI::l10n()->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
923                 }
924         } else {
925                 $menu = [DI::l10n()->t('View Profile') => $item['author-link']];
926         }
927
928         $args = ['item' => $item, 'menu' => $menu];
929
930         Hook::callAll('item_photo_menu', $args);
931
932         $menu = $args['menu'];
933
934         $o = '';
935         foreach ($menu as $k => $v) {
936                 if (strpos($v, 'javascript:') === 0) {
937                         $v = substr($v, 11);
938                         $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
939                 } elseif ($v!='') {
940                         $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
941                 }
942         }
943         return $o;
944 }
945
946 /**
947  * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
948  *
949  * Increments the count of each matching activity and adds a link to the author as needed.
950  *
951  * @param array  $item
952  * @param array &$conv_responses (already created with builtin activity structure)
953  * @return void
954  * @throws ImagickException
955  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
956  */
957 function builtin_activity_puller($item, &$conv_responses) {
958         foreach ($conv_responses as $mode => $v) {
959                 $sparkle = '';
960
961                 switch ($mode) {
962                         case 'like':
963                                 $verb = Activity::LIKE;
964                                 break;
965                         case 'dislike':
966                                 $verb = Activity::DISLIKE;
967                                 break;
968                         case 'attendyes':
969                                 $verb = Activity::ATTEND;
970                                 break;
971                         case 'attendno':
972                                 $verb = Activity::ATTENDNO;
973                                 break;
974                         case 'attendmaybe':
975                                 $verb = Activity::ATTENDMAYBE;
976                                 break;
977                         case 'announce':
978                                 $verb = Activity::ANNOUNCE;
979                                 break;
980                         default:
981                                 return;
982                 }
983
984                 if (!empty($item['verb']) && DI::activity()->match($item['verb'], $verb) && ($item['gravity'] != GRAVITY_PARENT)) {
985                         $author = ['uid' => 0, 'id' => $item['author-id'],
986                                 'network' => $item['author-network'], 'url' => $item['author-link']];
987                         $url = Contact::magicLinkByContact($author);
988                         if (strpos($url, 'redir/') === 0) {
989                                 $sparkle = ' class="sparkle" ';
990                         }
991
992                         $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
993
994                         if (empty($item['thr-parent'])) {
995                                 $item['thr-parent'] = $item['parent-uri'];
996                         }
997
998                         if (!(isset($conv_responses[$mode][$item['thr-parent'] . '-l'])
999                                 && is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))) {
1000                                 $conv_responses[$mode][$item['thr-parent'] . '-l'] = [];
1001                         }
1002
1003                         // only list each unique author once
1004                         if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
1005                                 continue;
1006                         }
1007
1008                         // Skip when the causer of the parent is the same than the author of the announce
1009                         if (($verb == Activity::ANNOUNCE) && Item::exists(['uri' => $item['thr-parent'],
1010                                 'uid' => $item['uid'], 'causer-id' => $item['author-id'], 'gravity' => GRAVITY_PARENT])) {
1011                                 continue;
1012                         }
1013
1014                         if (!isset($conv_responses[$mode][$item['thr-parent']])) {
1015                                 $conv_responses[$mode][$item['thr-parent']] = 1;
1016                         } else {
1017                                 $conv_responses[$mode][$item['thr-parent']] ++;
1018                         }
1019
1020                         if (public_contact() == $item['author-id']) {
1021                                 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
1022                         }
1023
1024                         $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
1025
1026                         // there can only be one activity verb per item so if we found anything, we can stop looking
1027                         return;
1028                 }
1029         }
1030 }
1031
1032 /**
1033  * Format the vote text for a profile item
1034  *
1035  * @param int    $cnt  = number of people who vote the item
1036  * @param array  $arr  = array of pre-linked names of likers/dislikers
1037  * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1038  * @param int    $id   = item id
1039  * @return string formatted text
1040  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1041  */
1042 function format_like($cnt, array $arr, $type, $id) {
1043         $o = '';
1044         $expanded = '';
1045         $phrase = '';
1046
1047         if ($cnt == 1) {
1048                 $likers = $arr[0];
1049
1050                 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1051                 // list which show all likers
1052                 switch ($type) {
1053                         case 'like' :
1054                                 $phrase = DI::l10n()->t('%s likes this.', $likers);
1055                                 break;
1056                         case 'dislike' :
1057                                 $phrase = DI::l10n()->t('%s doesn\'t like this.', $likers);
1058                                 break;
1059                         case 'attendyes' :
1060                                 $phrase = DI::l10n()->t('%s attends.', $likers);
1061                                 break;
1062                         case 'attendno' :
1063                                 $phrase = DI::l10n()->t('%s doesn\'t attend.', $likers);
1064                                 break;
1065                         case 'attendmaybe' :
1066                                 $phrase = DI::l10n()->t('%s attends maybe.', $likers);
1067                                 break;
1068                         case 'announce' :
1069                                 $phrase = DI::l10n()->t('%s reshared this.', $likers);
1070                                 break;
1071                 }
1072         }
1073
1074         if ($cnt > 1) {
1075                 $total = count($arr);
1076                 if ($total < MAX_LIKERS) {
1077                         $last = DI::l10n()->t('and') . ' ' . $arr[count($arr)-1];
1078                         $arr2 = array_slice($arr, 0, -1);
1079                         $likers = implode(', ', $arr2) . ' ' . $last;
1080                 } else  {
1081                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1082                         $likers = implode(', ', $arr);
1083                         $likers .= DI::l10n()->t('and %d other people', $total - MAX_LIKERS);
1084                 }
1085
1086                 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1087
1088                 $explikers = '';
1089                 switch ($type) {
1090                         case 'like':
1091                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> like this', $spanatts, $cnt);
1092                                 $explikers = DI::l10n()->t('%s like this.', $likers);
1093                                 break;
1094                         case 'dislike':
1095                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> don\'t like this', $spanatts, $cnt);
1096                                 $explikers = DI::l10n()->t('%s don\'t like this.', $likers);
1097                                 break;
1098                         case 'attendyes':
1099                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> attend', $spanatts, $cnt);
1100                                 $explikers = DI::l10n()->t('%s attend.', $likers);
1101                                 break;
1102                         case 'attendno':
1103                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> don\'t attend', $spanatts, $cnt);
1104                                 $explikers = DI::l10n()->t('%s don\'t attend.', $likers);
1105                                 break;
1106                         case 'attendmaybe':
1107                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> attend maybe', $spanatts, $cnt);
1108                                 $explikers = DI::l10n()->t('%s attend maybe.', $likers);
1109                                 break;
1110                         case 'announce':
1111                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> reshared this', $spanatts, $cnt);
1112                                 $explikers = DI::l10n()->t('%s reshared this.', $likers);
1113                                 break;
1114                 }
1115
1116                 $expanded .= "\t" . '<p class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1117         }
1118
1119         $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1120                 '$phrase' => $phrase,
1121                 '$type' => $type,
1122                 '$id' => $id
1123         ]);
1124         $o .= $expanded;
1125
1126         return $o;
1127 }
1128
1129 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1130 {
1131         $o = '';
1132
1133         $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1134
1135         $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1136         DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
1137                 '$newpost'   => 'true',
1138                 '$baseurl'   => DI::baseUrl()->get(true),
1139                 '$geotag'    => $geotag,
1140                 '$nickname'  => $x['nickname'],
1141                 '$ispublic'  => DI::l10n()->t('Visible to <strong>everybody</strong>'),
1142                 '$linkurl'   => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1143                 '$term'      => DI::l10n()->t('Tag term:'),
1144                 '$fileas'    => DI::l10n()->t('Save to Folder:'),
1145                 '$whereareu' => DI::l10n()->t('Where are you right now?'),
1146                 '$delitems'  => DI::l10n()->t("Delete item\x28s\x29?")
1147         ]);
1148
1149         $jotplugins = '';
1150         Hook::callAll('jot_tool', $jotplugins);
1151
1152         // $tpl = Renderer::replaceMacros($tpl,array('$jotplugins' => $jotplugins));
1153         $tpl = Renderer::getMarkupTemplate("jot.tpl");
1154
1155         $o .= Renderer::replaceMacros($tpl,[
1156                 '$new_post' => DI::l10n()->t('New Post'),
1157                 '$return_path'  => DI::args()->getQueryString(),
1158                 '$action'       => 'item',
1159                 '$share'        => ($x['button'] ?? '') ?: DI::l10n()->t('Share'),
1160                 '$loading'      => DI::l10n()->t('Loading...'),
1161                 '$upload'       => DI::l10n()->t('Upload photo'),
1162                 '$shortupload'  => DI::l10n()->t('upload photo'),
1163                 '$attach'       => DI::l10n()->t('Attach file'),
1164                 '$shortattach'  => DI::l10n()->t('attach file'),
1165                 '$edbold'       => DI::l10n()->t('Bold'),
1166                 '$editalic'     => DI::l10n()->t('Italic'),
1167                 '$eduline'      => DI::l10n()->t('Underline'),
1168                 '$edquote'      => DI::l10n()->t('Quote'),
1169                 '$edcode'       => DI::l10n()->t('Code'),
1170                 '$edimg'        => DI::l10n()->t('Image'),
1171                 '$edurl'        => DI::l10n()->t('Link'),
1172                 '$edattach'     => DI::l10n()->t('Link or Media'),
1173                 '$setloc'       => DI::l10n()->t('Set your location'),
1174                 '$shortsetloc'  => DI::l10n()->t('set location'),
1175                 '$noloc'        => DI::l10n()->t('Clear browser location'),
1176                 '$shortnoloc'   => DI::l10n()->t('clear location'),
1177                 '$title'        => $x['title'] ?? '',
1178                 '$placeholdertitle' => DI::l10n()->t('Set title'),
1179                 '$category'     => $x['category'] ?? '',
1180                 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1181                 '$wait'         => DI::l10n()->t('Please wait'),
1182                 '$permset'      => DI::l10n()->t('Permission settings'),
1183                 '$shortpermset' => DI::l10n()->t('Permissions'),
1184                 '$wall'         => $notes_cid ? 0 : 1,
1185                 '$posttype'     => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1186                 '$content'      => $x['content'] ?? '',
1187                 '$post_id'      => $x['post_id'] ?? '',
1188                 '$baseurl'      => DI::baseUrl()->get(true),
1189                 '$defloc'       => $x['default_location'],
1190                 '$visitor'      => $x['visitor'],
1191                 '$pvisit'       => $notes_cid ? 'none' : $x['visitor'],
1192                 '$public'       => DI::l10n()->t('Public post'),
1193                 '$lockstate'    => $x['lockstate'],
1194                 '$bang'         => $x['bang'],
1195                 '$profile_uid'  => $x['profile_uid'],
1196                 '$preview'      => DI::l10n()->t('Preview'),
1197                 '$jotplugins'   => $jotplugins,
1198                 '$notes_cid'    => $notes_cid,
1199                 '$sourceapp'    => DI::l10n()->t($a->sourcename),
1200                 '$cancel'       => DI::l10n()->t('Cancel'),
1201                 '$rand_num'     => Crypto::randomDigits(12),
1202
1203                 // ACL permissions box
1204                 '$acl'           => $x['acl'],
1205
1206                 //jot nav tab (used in some themes)
1207                 '$message' => DI::l10n()->t('Message'),
1208                 '$browser' => DI::l10n()->t('Browser'),
1209
1210                 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1211         ]);
1212
1213
1214         if ($popup == true) {
1215                 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1216         }
1217
1218         return $o;
1219 }
1220
1221 /**
1222  * Plucks the children of the given parent from a given item list.
1223  *
1224  * @param array $item_list
1225  * @param array $parent
1226  * @param bool  $recursive
1227  * @return array
1228  */
1229 function get_item_children(array &$item_list, array $parent, $recursive = true)
1230 {
1231         $children = [];
1232         foreach ($item_list as $i => $item) {
1233                 if ($item['gravity'] != GRAVITY_PARENT) {
1234                         if ($recursive) {
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'];
1239                                 }
1240
1241                                 if ($thr_parent == $parent['uri']) {
1242                                         $item['children'] = get_item_children($item_list, $item);
1243                                         $children[] = $item;
1244                                         unset($item_list[$i]);
1245                                 }
1246                         } elseif ($item['parent'] == $parent['id']) {
1247                                 $children[] = $item;
1248                                 unset($item_list[$i]);
1249                         }
1250                 }
1251         }
1252         return $children;
1253 }
1254
1255 /**
1256  * Recursively sorts a tree-like item array
1257  *
1258  * @param array $items
1259  * @return array
1260  */
1261 function sort_item_children(array $items)
1262 {
1263         $result = $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']);
1268                 }
1269         }
1270         return $result;
1271 }
1272
1273 /**
1274  * Recursively add all children items at the top level of a list
1275  *
1276  * @param array $children List of items to append
1277  * @param array $item_list
1278  */
1279 function add_children_to_list(array $children, array &$item_list)
1280 {
1281         foreach ($children as $child) {
1282                 $item_list[] = $child;
1283                 if (isset($child['children'])) {
1284                         add_children_to_list($child['children'], $item_list);
1285                 }
1286         }
1287 }
1288
1289 /**
1290  * Selectively flattens a tree-like item structure to prevent threading stairs
1291  *
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.
1295  *
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.
1298  *
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.
1301  *
1302  * @param array $parent A tree-like array of items
1303  * @return array
1304  */
1305 function smart_flatten_conversation(array $parent)
1306 {
1307         if (!isset($parent['children']) || count($parent['children']) == 0) {
1308                 return $parent;
1309         }
1310
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];
1314
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;
1319                         };
1320
1321                         $child_post_count = count(array_filter($child['children'], $count_post_closure));
1322
1323                         $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1324
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) {
1327
1328                                 // Searches the post item in the children
1329                                 $j = 0;
1330                                 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1331                                         $j ++;
1332                                 }
1333
1334                                 $moved_item = $child['children'][$j];
1335                                 unset($parent['children'][$i]['children'][$j]);
1336                                 $parent['children'][] = $moved_item;
1337                         } else {
1338                                 $parent['children'][$i] = smart_flatten_conversation($child);
1339                         }
1340                 }
1341         }
1342
1343         return $parent;
1344 }
1345
1346
1347 /**
1348  * Expands a flat list of items into corresponding tree-like conversation structures.
1349  *
1350  * sort the top-level posts either on "received" or "commented", and finally
1351  * append all the items at the top level (???)
1352  *
1353  * @param array  $item_list A list of items belonging to one or more conversations
1354  * @param string $order     Either on "received" or "commented"
1355  * @return array
1356  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1357  */
1358 function conv_sort(array $item_list, $order)
1359 {
1360         $parents = [];
1361
1362         if (!(is_array($item_list) && count($item_list))) {
1363                 return $parents;
1364         }
1365
1366         $blocklist = conv_get_blocklist();
1367
1368         $item_array = [];
1369
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)) {
1373                         continue;
1374                 }
1375
1376                 $item_array[$item['uri']] = $item;
1377         }
1378
1379         // Extract the top level items
1380         foreach ($item_array as $item) {
1381                 if ($item['gravity'] == GRAVITY_PARENT) {
1382                         $parents[] = $item;
1383                 }
1384         }
1385
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');
1392         }
1393
1394         /*
1395          * Plucks children from the item_array, second pass collects eventual orphan
1396          * items and add them as children of their top-level post.
1397          */
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));
1402         }
1403
1404         foreach ($parents as $i => $parent) {
1405                 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1406         }
1407
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);
1411                 }
1412         }
1413
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);
1419                 }
1420         }
1421
1422         return $parents;
1423 }
1424
1425 /**
1426  * usort() callback to sort item arrays by pinned and the received key
1427  *
1428  * @param array $a
1429  * @param array $b
1430  * @return int
1431  */
1432 function sort_thr_pinned_received(array $a, array $b)
1433 {
1434         if ($b['pinned'] && !$a['pinned']) {
1435                 return 1;
1436         } elseif (!$b['pinned'] && $a['pinned']) {
1437                 return -1;
1438         }
1439
1440         return strcmp($b['received'], $a['received']);
1441 }
1442
1443 /**
1444  * usort() callback to sort item arrays by the received key
1445  *
1446  * @param array $a
1447  * @param array $b
1448  * @return int
1449  */
1450 function sort_thr_received(array $a, array $b)
1451 {
1452         return strcmp($b['received'], $a['received']);
1453 }
1454
1455 /**
1456  * usort() callback to reverse sort item arrays by the received key
1457  *
1458  * @param array $a
1459  * @param array $b
1460  * @return int
1461  */
1462 function sort_thr_received_rev(array $a, array $b)
1463 {
1464         return strcmp($a['received'], $b['received']);
1465 }
1466
1467 /**
1468  * usort() callback to sort item arrays by the commented key
1469  *
1470  * @param array $a
1471  * @param array $b
1472  * @return int
1473  */
1474 function sort_thr_commented(array $a, array $b)
1475 {
1476         return strcmp($b['commented'], $a['commented']);
1477 }