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