]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
Merge pull request #6719 from annando/worker-scheduler
[friendica.git] / include / conversation.php
1 <?php
2 /**
3  * @file include/conversation.php
4  */
5
6 use Friendica\App;
7 use Friendica\Content\ContactSelector;
8 use Friendica\Content\Feature;
9 use Friendica\Content\Pager;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\Config;
12 use Friendica\Core\Hook;
13 use Friendica\Core\L10n;
14 use Friendica\Core\Logger;
15 use Friendica\Core\PConfig;
16 use Friendica\Core\Protocol;
17 use Friendica\Core\Renderer;
18 use Friendica\Core\System;
19 use Friendica\Database\DBA;
20 use Friendica\Model\Contact;
21 use Friendica\Model\Item;
22 use Friendica\Model\Profile;
23 use Friendica\Model\Term;
24 use Friendica\Object\Post;
25 use Friendica\Object\Thread;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Proxy as ProxyUtils;
28 use Friendica\Util\Temporal;
29 use Friendica\Util\Strings;
30 use Friendica\Util\XML;
31 use Friendica\Util\Crypto;
32
33 function item_extract_images($body) {
34
35         $saved_image = [];
36         $orig_body = $body;
37         $new_body = '';
38
39         $cnt = 0;
40         $img_start = strpos($orig_body, '[img');
41         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
42         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
43         while (($img_st_close !== false) && ($img_end !== false)) {
44
45                 $img_st_close++; // make it point to AFTER the closing bracket
46                 $img_end += $img_start;
47
48                 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
49                         // This is an embedded image
50
51                         $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
52                         $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
53
54                         $cnt++;
55                 } else {
56                         $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
57                 }
58
59                 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
60
61                 if ($orig_body === false) {
62                         // in case the body ends on a closing image tag
63                         $orig_body = '';
64                 }
65
66                 $img_start = strpos($orig_body, '[img');
67                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
68                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
69         }
70
71         $new_body = $new_body . $orig_body;
72
73         return ['body' => $new_body, 'images' => $saved_image];
74 }
75
76 function item_redir_and_replace_images($body, $images, $cid) {
77
78         $origbody = $body;
79         $newbody = '';
80
81         $cnt = 1;
82         $pos = BBCode::getTagPosition($origbody, 'url', 0);
83         while ($pos !== false && $cnt < 1000) {
84
85                 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
86                 $replace = '[url=' . System::baseUrl() . '/redir/' . $cid
87                                    . '?f=1&url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
88
89                 $newbody .= substr($origbody, 0, $pos['start']['open']);
90                 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
91                 $origbody = substr($origbody, $pos['end']['close']);
92                 if ($origbody === false) {
93                         $origbody = '';
94                 }
95
96                 $subject = preg_replace($search, $replace, $subject);
97                 $newbody .= $subject;
98
99                 $cnt++;
100                 // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
101                 $pos = BBCode::getTagPosition($origbody, 'url', 0);
102         }
103         $newbody .= $origbody;
104
105         $cnt = 0;
106         foreach ($images as $image) {
107                 /*
108                  * We're depending on the property of 'foreach' (specified on the PHP website) that
109                  * it loops over the array starting from the first element and going sequentially
110                  * to the last element.
111                  */
112                 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
113                 $cnt++;
114         }
115         return $newbody;
116 }
117
118 /**
119  * Render actions localized
120  *
121  * @param $item
122  * @throws ImagickException
123  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
124  */
125 function localize_item(&$item)
126 {
127         $extracted = item_extract_images($item['body']);
128         if ($extracted['images']) {
129                 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
130         }
131
132         /*
133         heluecht 2018-06-19: from my point of view this whole code part is useless.
134         It just renders the body message of technical posts (Like, dislike, ...).
135         But: The body isn't visible at all. So we do this stuff just because we can.
136         Even if these messages were visible, this would only mean that something went wrong.
137         During the further steps of the database restructuring I would like to address this issue.
138         */
139
140         $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
141         if (activity_match($item['verb'], ACTIVITY_LIKE)
142                 || activity_match($item['verb'], ACTIVITY_DISLIKE)
143                 || activity_match($item['verb'], ACTIVITY_ATTEND)
144                 || activity_match($item['verb'], ACTIVITY_ATTENDNO)
145                 || activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
146
147                 $fields = ['author-link', 'author-name', 'verb', 'object-type', 'resource-id', 'body', 'plink'];
148                 $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
149                 if (!DBA::isResult($obj)) {
150                         return;
151                 }
152
153                 $author  = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
154                 $objauthor =  '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]';
155
156                 switch ($obj['verb']) {
157                         case ACTIVITY_POST:
158                                 switch ($obj['object-type']) {
159                                         case ACTIVITY_OBJ_EVENT:
160                                                 $post_type = L10n::t('event');
161                                                 break;
162                                         default:
163                                                 $post_type = L10n::t('status');
164                                 }
165                                 break;
166                         default:
167                                 if ($obj['resource-id']) {
168                                         $post_type = L10n::t('photo');
169                                         $m = [];
170                                         preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
171                                         $rr['plink'] = $m[1];
172                                 } else {
173                                         $post_type = L10n::t('status');
174                                 }
175                 }
176
177                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
178
179                 $bodyverb = '';
180                 if (activity_match($item['verb'], ACTIVITY_LIKE)) {
181                         $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
182                 } elseif (activity_match($item['verb'], ACTIVITY_DISLIKE)) {
183                         $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
184                 } elseif (activity_match($item['verb'], ACTIVITY_ATTEND)) {
185                         $bodyverb = L10n::t('%1$s attends %2$s\'s %3$s');
186                 } elseif (activity_match($item['verb'], ACTIVITY_ATTENDNO)) {
187                         $bodyverb = L10n::t('%1$s doesn\'t attend %2$s\'s %3$s');
188                 } elseif (activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
189                         $bodyverb = L10n::t('%1$s attends maybe %2$s\'s %3$s');
190                 }
191
192                 $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
193         }
194
195         if (activity_match($item['verb'], ACTIVITY_FRIEND)) {
196
197                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
198
199                 $Aname = $item['author-name'];
200                 $Alink = $item['author-link'];
201
202                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
203
204                 $obj = XML::parseString($xmlhead.$item['object']);
205                 $links = XML::parseString($xmlhead."<links>".XML::unescape($obj->link)."</links>");
206
207                 $Bname = $obj->title;
208                 $Blink = "";
209                 $Bphoto = "";
210                 foreach ($links->link as $l) {
211                         $atts = $l->attributes();
212                         switch ($atts['rel']) {
213                                 case "alternate": $Blink = $atts['href']; break;
214                                 case "photo": $Bphoto = $atts['href']; break;
215                         }
216                 }
217
218                 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
219                 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
220                 if ($Bphoto != "") {
221                         $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img]' . $Bphoto . '[/img][/url]';
222                 }
223
224                 $item['body'] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$Bphoto;
225
226         }
227         if (stristr($item['verb'], ACTIVITY_POKE)) {
228                 $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
229                 if (!$verb) {
230                         return;
231                 }
232                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) {
233                         return;
234                 }
235
236                 $Aname = $item['author-name'];
237                 $Alink = $item['author-link'];
238
239                 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
240
241                 $obj = XML::parseString($xmlhead.$item['object']);
242
243                 $Bname = $obj->title;
244                 $Blink = $obj->id;
245                 $Bphoto = "";
246
247                 foreach ($obj->link as $l) {
248                         $atts = $l->attributes();
249                         switch ($atts['rel']) {
250                                 case "alternate": $Blink = $atts['href'];
251                                 case "photo": $Bphoto = $atts['href'];
252                         }
253                 }
254
255                 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
256                 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
257                 if ($Bphoto != "") {
258                         $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
259                 }
260
261                 /*
262                  * we can't have a translation string with three positions but no distinguishable text
263                  * So here is the translate string.
264                  */
265                 $txt = L10n::t('%1$s poked %2$s');
266
267                 // now translate the verb
268                 $poked_t = trim(sprintf($txt, "", ""));
269                 $txt = str_replace($poked_t, L10n::t($verb), $txt);
270
271                 // then do the sprintf on the translation string
272
273                 $item['body'] = sprintf($txt, $A, $B). "\n\n\n" . $Bphoto;
274
275         }
276
277         if (activity_match($item['verb'], ACTIVITY_TAG)) {
278                 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
279                         'verb', 'object-type', 'resource-id', 'body', 'plink'];
280                 $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
281                 if (!DBA::isResult($obj)) {
282                         return;
283                 }
284
285                 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
286                         'network' => $item['author-network'], 'url' => $item['author-link']];
287                 $author  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
288
289                 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
290                         'network' => $obj['author-network'], 'url' => $obj['author-link']];
291                 $objauthor  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
292
293                 switch ($obj['verb']) {
294                         case ACTIVITY_POST:
295                                 switch ($obj['object-type']) {
296                                         case ACTIVITY_OBJ_EVENT:
297                                                 $post_type = L10n::t('event');
298                                                 break;
299                                         default:
300                                                 $post_type = L10n::t('status');
301                                 }
302                                 break;
303                         default:
304                                 if ($obj['resource-id']) {
305                                         $post_type = L10n::t('photo');
306                                         $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
307                                         $rr['plink'] = $m[1];
308                                 } else {
309                                         $post_type = L10n::t('status');
310                                 }
311                                 // Let's break everthing ... ;-)
312                                 break;
313                 }
314                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
315
316                 $parsedobj = XML::parseString($xmlhead.$item['object']);
317
318                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
319                 $item['body'] = L10n::t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
320         }
321
322         if (activity_match($item['verb'], ACTIVITY_FAVORITE)) {
323                 if ($item['object-type'] == "") {
324                         return;
325                 }
326
327                 $Aname = $item['author-name'];
328                 $Alink = $item['author-link'];
329
330                 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
331
332                 $obj = XML::parseString($xmlhead.$item['object']);
333                 if (strlen($obj->id)) {
334                         $fields = ['author-link', 'author-name', 'plink'];
335                         $target = Item::selectFirst($fields, ['uri' => $obj->id, 'uid' => $item['uid']]);
336                         if (DBA::isResult($target) && $target['plink']) {
337                                 $Bname = $target['author-name'];
338                                 $Blink = $target['author-link'];
339                                 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
340                                 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
341                                 $P = '[url=' . $target['plink'] . ']' . L10n::t('post/item') . '[/url]';
342                                 $item['body'] = L10n::t('%1$s marked %2$s\'s %3$s as favorite', $A, $B, $P)."\n";
343                         }
344                 }
345         }
346         $matches = null;
347         if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
348                 foreach ($matches as $mtch) {
349                         if (!strpos($mtch[1], 'zrl=')) {
350                                 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
351                         }
352                 }
353         }
354
355         // add zrl's to public images
356         $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
357         if (preg_match($photo_pattern, $item['body'])) {
358                 $photo_replace = '[url=' . Profile::zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5'  . '[/img][/url]';
359                 $item['body'] = BBCode::pregReplaceInTag($photo_pattern, $photo_replace, 'url', $item['body']);
360         }
361
362         // add sparkle links to appropriate permalinks
363         $author = ['uid' => 0, 'id' => $item['author-id'],
364                 'network' => $item['author-network'], 'url' => $item['author-link']];
365
366         // Only create a redirection to a magic link when logged in
367         if (!empty($item['plink']) && (local_user() || remote_user())) {
368                 $item['plink'] = Contact::magicLinkbyContact($author, $item['plink']);
369         }
370 }
371
372 /**
373  * Count the total of comments on this item and its desendants
374  * @TODO proper type-hint + doc-tag
375  * @param $item
376  * @return int
377  */
378 function count_descendants($item) {
379         $total = count($item['children']);
380
381         if ($total > 0) {
382                 foreach ($item['children'] as $child) {
383                         if (!visible_activity($child)) {
384                                 $total --;
385                         }
386                         $total += count_descendants($child);
387                 }
388         }
389
390         return $total;
391 }
392
393 function visible_activity($item) {
394
395         /*
396          * likes (etc.) can apply to other things besides posts. Check if they are post children,
397          * in which case we handle them specially
398          */
399         $hidden_activities = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE, ACTIVITY_FOLLOW];
400         foreach ($hidden_activities as $act) {
401                 if (activity_match($item['verb'], $act)) {
402                         return false;
403                 }
404         }
405
406         // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
407         if (activity_match($item['verb'], ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE && empty($item['self']) && $item['uid'] == local_user()) {
408                 return false;
409         }
410
411         return true;
412 }
413
414 function conv_get_blocklist()
415 {
416         if (!local_user()) {
417                 return [];
418         }
419
420         $str_blocked = PConfig::get(local_user(), 'system', 'blocked');
421         if (empty($str_blocked)) {
422                 return [];
423         }
424
425         $blocklist = [];
426
427         foreach (explode(',', $str_blocked) as $entry) {
428                 // The 4th parameter guarantees that there always will be a public contact entry
429                 $cid = Contact::getIdForURL(trim($entry), 0, true, ['url' => trim($entry)]);
430                 if (!empty($cid)) {
431                         $blocklist[] = $cid;
432                 }
433         }
434
435         return $blocklist;
436 }
437
438 /**
439  * "Render" a conversation or list of items for HTML display.
440  * There are two major forms of display:
441  *      - Sequential or unthreaded ("New Item View" or search results)
442  *      - conversation view
443  * The $mode parameter decides between the various renderings and also
444  * figures out how to determine page owner and other contextual items
445  * that are based on unique features of the calling module.
446  * @param App    $a
447  * @param array  $items
448  * @param Pager  $pager
449  * @param        $mode
450  * @param        $update
451  * @param bool   $preview
452  * @param string $order
453  * @param int    $uid
454  * @return string
455  * @throws ImagickException
456  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
457  */
458 function conversation(App $a, array $items, Pager $pager, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
459 {
460         $ssl_state = (local_user() ? true : false);
461
462         $profile_owner = 0;
463         $live_update_div = '';
464
465         $blocklist = conv_get_blocklist();
466
467         $previewing = (($preview) ? ' preview ' : '');
468
469         if ($mode === 'network') {
470                 $items = conversation_add_children($items, false, $order, $uid);
471                 $profile_owner = local_user();
472                 if (!$update) {
473                         /*
474                          * The special div is needed for liveUpdate to kick in for this page.
475                          * We only launch liveUpdate if you aren't filtering in some incompatible
476                          * way and also you aren't writing a comment (discovered in javascript).
477                          */
478                         $live_update_div = '<div id="live-network"></div>' . "\r\n"
479                                 . "<script> var profile_uid = " . $_SESSION['uid']
480                                 . "; var netargs = '" . substr($a->cmd, 8)
481                                 . '?f='
482                                 . (!empty($_GET['cid'])    ? '&cid='    . rawurlencode($_GET['cid'])    : '')
483                                 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
484                                 . (!empty($_GET['star'])   ? '&star='   . rawurlencode($_GET['star'])   : '')
485                                 . (!empty($_GET['order'])  ? '&order='  . rawurlencode($_GET['order'])  : '')
486                                 . (!empty($_GET['bmark'])  ? '&bmark='  . rawurlencode($_GET['bmark'])  : '')
487                                 . (!empty($_GET['liked'])  ? '&liked='  . rawurlencode($_GET['liked'])  : '')
488                                 . (!empty($_GET['conv'])   ? '&conv='   . rawurlencode($_GET['conv'])   : '')
489                                 . (!empty($_GET['nets'])   ? '&nets='   . rawurlencode($_GET['nets'])   : '')
490                                 . (!empty($_GET['cmin'])   ? '&cmin='   . rawurlencode($_GET['cmin'])   : '')
491                                 . (!empty($_GET['cmax'])   ? '&cmax='   . rawurlencode($_GET['cmax'])   : '')
492                                 . (!empty($_GET['file'])   ? '&file='   . rawurlencode($_GET['file'])   : '')
493
494                                 . "'; var profile_page = " . $pager->getPage() . "; </script>\r\n";
495                 }
496         } elseif ($mode === 'profile') {
497                 $items = conversation_add_children($items, false, $order, $uid);
498                 $profile_owner = $a->profile['profile_uid'];
499
500                 if (!$update) {
501                         $tab = 'posts';
502                         if (!empty($_GET['tab'])) {
503                                 $tab = Strings::escapeTags(trim($_GET['tab']));
504                         }
505                         if ($tab === 'posts') {
506                                 /*
507                                  * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
508                                  * because browser prefetching might change it on us. We have to deliver it with the page.
509                                  */
510
511                                 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
512                                         . "<script> var profile_uid = " . $a->profile['profile_uid']
513                                         . "; var netargs = '?f='; var profile_page = " . $pager->getPage() . "; </script>\r\n";
514                         }
515                 }
516         } elseif ($mode === 'notes') {
517                 $items = conversation_add_children($items, false, $order, local_user());
518                 $profile_owner = local_user();
519
520                 if (!$update) {
521                         $live_update_div = '<div id="live-notes"></div>' . "\r\n"
522                                 . "<script> var profile_uid = " . local_user()
523                                 . "; var netargs = '/?f='; var profile_page = " . $pager->getPage() . "; </script>\r\n";
524                 }
525         } elseif ($mode === 'display') {
526                 $items = conversation_add_children($items, false, $order, $uid);
527                 $profile_owner = $a->profile['uid'];
528
529                 if (!$update) {
530                         $live_update_div = '<div id="live-display"></div>' . "\r\n"
531                                 . "<script> var profile_uid = " . defaults($_SESSION, 'uid', 0) . ";"
532                                 . " var profile_page = 1; </script>";
533                 }
534         } elseif ($mode === 'community') {
535                 $items = conversation_add_children($items, true, $order, $uid);
536                 $profile_owner = 0;
537
538                 if (!$update) {
539                         $live_update_div = '<div id="live-community"></div>' . "\r\n"
540                                 . "<script> var profile_uid = -1; var netargs = '" . substr($a->cmd, 10)
541                                 ."/?f='; var profile_page = " . $pager->getPage() . "; </script>\r\n";
542                 }
543         } elseif ($mode === 'contacts') {
544                 $items = conversation_add_children($items, false, $order, $uid);
545                 $profile_owner = 0;
546
547                 if (!$update) {
548                         $live_update_div = '<div id="live-contacts"></div>' . "\r\n"
549                                 . "<script> var profile_uid = -1; var netargs = '" . substr($a->cmd, 9)
550                                 ."/?f='; var profile_page = " . $pager->getPage() . "; </script>\r\n";
551                 }
552         } elseif ($mode === 'search') {
553                 $live_update_div = '<div id="live-search"></div>' . "\r\n";
554         }
555
556         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
557
558         if (!$update) {
559                 $_SESSION['return_path'] = $a->query_string;
560         }
561
562         $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
563         Hook::callAll('conversation_start',$cb);
564
565         $items = $cb['items'];
566
567         $conv_responses = [
568                 'like' => ['title' => L10n::t('Likes','title')], 'dislike' => ['title' => L10n::t('Dislikes','title')],
569                 'attendyes' => ['title' => L10n::t('Attending','title')], 'attendno' => ['title' => L10n::t('Not attending','title')], 'attendmaybe' => ['title' => L10n::t('Might attend','title')]
570         ];
571
572         // array with html for each thread (parent+comments)
573         $threads = [];
574         $threadsid = -1;
575
576         $page_template = Renderer::getMarkupTemplate("conversation.tpl");
577
578         if (!empty($items)) {
579                 if (in_array($mode, ['community', 'contacts'])) {
580                         $writable = true;
581                 } else {
582                         $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
583                 }
584
585                 if (!local_user()) {
586                         $writable = false;
587                 }
588
589                 if (in_array($mode, ['network-new', 'search', 'contact-posts'])) {
590
591                         /*
592                          * "New Item View" on network page or search page results
593                          * - just loop through the items and format them minimally for display
594                          */
595
596                         $tpl = 'search_item.tpl';
597
598                         foreach ($items as $item) {
599
600                                 if (!visible_activity($item)) {
601                                         continue;
602                                 }
603
604                                 if (in_array($item['author-id'], $blocklist)) {
605                                         continue;
606                                 }
607
608                                 $threadsid++;
609
610                                 $owner_url   = '';
611                                 $owner_name  = '';
612                                 $sparkle     = '';
613
614                                 // prevent private email from leaking.
615                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
616                                         continue;
617                                 }
618
619                                 $profile_name = $item['author-name'];
620                                 if (!empty($item['author-link']) && empty($item['author-name'])) {
621                                         $profile_name = $item['author-link'];
622                                 }
623
624                                 $tags = Term::populateTagsFromItem($item);
625
626                                 $author = ['uid' => 0, 'id' => $item['author-id'],
627                                         'network' => $item['author-network'], 'url' => $item['author-link']];
628                                 $profile_link = Contact::magicLinkbyContact($author);
629
630                                 if (strpos($profile_link, 'redir/') === 0) {
631                                         $sparkle = ' sparkle';
632                                 }
633
634                                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
635                                 Hook::callAll('render_location',$locate);
636
637                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
638
639                                 localize_item($item);
640                                 if ($mode === 'network-new') {
641                                         $dropping = true;
642                                 } else {
643                                         $dropping = false;
644                                 }
645
646                                 $drop = [
647                                         'dropping' => $dropping,
648                                         'pagedrop' => $page_dropping,
649                                         'select' => L10n::t('Select'),
650                                         'delete' => L10n::t('Delete'),
651                                 ];
652
653                                 $star = false;
654                                 $isstarred = "unstarred";
655
656                                 $lock = false;
657                                 $likebuttons = false;
658
659                                 $body = Item::prepareBody($item, true, $preview);
660
661                                 list($categories, $folders) = get_cats_and_terms($item);
662
663                                 $profile_name_e = $profile_name;
664
665                                 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
666                                         $title_e = ucfirst($item['content-warning']);
667                                 } else {
668                                         $title_e = $item['title'];
669                                 }
670
671                                 $body_e = $body;
672                                 $tags_e = $tags['tags'];
673                                 $hashtags_e = $tags['hashtags'];
674                                 $mentions_e = $tags['mentions'];
675                                 $location_e = $location;
676                                 $owner_name_e = $owner_name;
677
678                                 $tmp_item = [
679                                         'template' => $tpl,
680                                         'id' => ($preview ? 'P0' : $item['id']),
681                                         'guid' => ($preview ? 'Q0' : $item['guid']),
682                                         'network' => $item['network'],
683                                         'network_name' => ContactSelector::networkToName($item['network'], $item['author-link']),
684                                         'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
685                                         'profile_url' => $profile_link,
686                                         'item_photo_menu' => item_photo_menu($item),
687                                         'name' => $profile_name_e,
688                                         'sparkle' => $sparkle,
689                                         'lock' => $lock,
690                                         'thumb' => System::removedBaseUrl(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
691                                         'title' => $title_e,
692                                         'body' => $body_e,
693                                         'tags' => $tags_e,
694                                         'hashtags' => $hashtags_e,
695                                         'mentions' => $mentions_e,
696                                         'txt_cats' => L10n::t('Categories:'),
697                                         'txt_folders' => L10n::t('Filed under:'),
698                                         'has_cats' => ((count($categories)) ? 'true' : ''),
699                                         'has_folders' => ((count($folders)) ? 'true' : ''),
700                                         'categories' => $categories,
701                                         'folders' => $folders,
702                                         'text' => strip_tags($body_e),
703                                         'localtime' => DateTimeFormat::local($item['created'], 'r'),
704                                         'ago' => (($item['app']) ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']),$item['app']) : Temporal::getRelativeDate($item['created'])),
705                                         'location' => $location_e,
706                                         'indent' => '',
707                                         'owner_name' => $owner_name_e,
708                                         'owner_url' => $owner_url,
709                                         'owner_photo' => System::removedBaseUrl(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
710                                         'plink' => Item::getPlink($item),
711                                         'edpost' => false,
712                                         'isstarred' => $isstarred,
713                                         'star' => $star,
714                                         'drop' => $drop,
715                                         'vote' => $likebuttons,
716                                         'like' => '',
717                                         'dislike' => '',
718                                         'comment' => '',
719                                         'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> L10n::t('View in context')]),
720                                         'previewing' => $previewing,
721                                         'wait' => L10n::t('Please wait'),
722                                         'thread_level' => 1,
723                                 ];
724
725                                 $arr = ['item' => $item, 'output' => $tmp_item];
726                                 Hook::callAll('display_item', $arr);
727
728                                 $threads[$threadsid]['id'] = $item['id'];
729                                 $threads[$threadsid]['network'] = $item['network'];
730                                 $threads[$threadsid]['items'] = [$arr['output']];
731
732                         }
733                 } else {
734                         // Normal View
735                         $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
736
737                         $conv = new Thread($mode, $preview, $writable);
738
739                         /*
740                          * get all the topmost parents
741                          * this shouldn't be needed, as we should have only them in our array
742                          * But for now, this array respects the old style, just in case
743                          */
744                         foreach ($items as $item) {
745                                 if (in_array($item['author-id'], $blocklist)) {
746                                         continue;
747                                 }
748
749                                 // Can we put this after the visibility check?
750                                 builtin_activity_puller($item, $conv_responses);
751
752                                 // Only add what is visible
753                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
754                                         continue;
755                                 }
756
757                                 if (!visible_activity($item)) {
758                                         continue;
759                                 }
760
761                                 /// @todo Check if this call is needed or not
762                                 $arr = ['item' => $item];
763                                 Hook::callAll('display_item', $arr);
764
765                                 $item['pagedrop'] = $page_dropping;
766
767                                 if ($item['id'] == $item['parent']) {
768                                         $item_object = new Post($item);
769                                         $conv->addParent($item_object);
770                                 }
771                         }
772
773                         $threads = $conv->getTemplateData($conv_responses);
774                         if (!$threads) {
775                                 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
776                                 $threads = [];
777                         }
778                 }
779         }
780
781         $o = Renderer::replaceMacros($page_template, [
782                 '$baseurl' => System::baseUrl($ssl_state),
783                 '$return_path' => $a->query_string,
784                 '$live_update' => $live_update_div,
785                 '$remove' => L10n::t('remove'),
786                 '$mode' => $mode,
787                 '$user' => $a->user,
788                 '$threads' => $threads,
789                 '$dropping' => ($page_dropping ? L10n::t('Delete Selected Items') : False),
790         ]);
791
792         return $o;
793 }
794
795 /**
796  * @brief Add comments to top level entries that had been fetched before
797  *
798  * The system will fetch the comments for the local user whenever possible.
799  * This behaviour is currently needed to allow commenting on Friendica posts.
800  *
801  * @param array $parents Parent items
802  *
803  * @param       $block_authors
804  * @param       $order
805  * @param       $uid
806  * @return array items with parents and comments
807  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
808  */
809 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
810         $max_comments = Config::get('system', 'max_comments', 100);
811
812         $params = ['order' => ['uid', 'commented' => true]];
813
814         if ($max_comments > 0) {
815                 $params['limit'] = $max_comments;
816         }
817
818         $items = [];
819
820         foreach ($parents AS $parent) {
821                 $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) ",
822                         $parent['uri'], $uid];
823                 if ($block_authors) {
824                         $condition[0] .= "AND NOT `author`.`hidden`";
825                 }
826                 $thread_items = Item::selectForUser(local_user(), [], $condition, $params);
827
828                 $comments = Item::inArray($thread_items);
829
830                 if (count($comments) != 0) {
831                         $items = array_merge($items, $comments);
832                 }
833         }
834
835         foreach ($items as $index => $item) {
836                 if ($item['uid'] == 0) {
837                         $items[$index]['writable'] = in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
838                 }
839         }
840
841         $items = conv_sort($items, $order);
842
843         return $items;
844 }
845
846 function item_photo_menu($item) {
847         $sub_link = '';
848         $poke_link = '';
849         $contact_url = '';
850         $pm_url = '';
851         $status_link = '';
852         $photos_link = '';
853         $posts_link = '';
854
855         if (local_user() && local_user() == $item['uid'] && $item['parent'] == $item['id'] && !$item['self']) {
856                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
857         }
858
859         $author = ['uid' => 0, 'id' => $item['author-id'],
860                 'network' => $item['author-network'], 'url' => $item['author-link']];
861         $profile_link = Contact::magicLinkbyContact($author);
862         $sparkle = (strpos($profile_link, 'redir/') === 0);
863
864         $cid = 0;
865         $network = '';
866         $rel = 0;
867         $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
868         $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
869         if (DBA::isResult($contact)) {
870                 $cid = $contact['id'];
871                 $network = $contact['network'];
872                 $rel = $contact['rel'];
873         }
874
875         if ($sparkle) {
876                 $status_link = $profile_link . '?url=status';
877                 $photos_link = $profile_link . '?url=photos';
878                 $profile_link = $profile_link . '?url=profile';
879         }
880
881         if ($cid && !$item['self']) {
882                 $poke_link = 'poke/?f=&c=' . $cid;
883                 $contact_url = 'contact/' . $cid;
884                 $posts_link = 'contact/' . $cid . '/posts';
885
886                 if (in_array($network, [Protocol::DFRN, Protocol::DIASPORA])) {
887                         $pm_url = 'message/new/' . $cid;
888                 }
889         }
890
891         if (local_user()) {
892                 $menu = [
893                         L10n::t('Follow Thread') => $sub_link,
894                         L10n::t('View Status') => $status_link,
895                         L10n::t('View Profile') => $profile_link,
896                         L10n::t('View Photos') => $photos_link,
897                         L10n::t('Network Posts') => $posts_link,
898                         L10n::t('View Contact') => $contact_url,
899                         L10n::t('Send PM') => $pm_url
900                 ];
901
902                 if ($network == Protocol::DFRN) {
903                         $menu[L10n::t("Poke")] = $poke_link;
904                 }
905
906                 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
907                         in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA])) {
908                         $menu[L10n::t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
909                 }
910         } else {
911                 $menu = [L10n::t('View Profile') => $item['author-link']];
912         }
913
914         $args = ['item' => $item, 'menu' => $menu];
915
916         Hook::callAll('item_photo_menu', $args);
917
918         $menu = $args['menu'];
919
920         $o = '';
921         foreach ($menu as $k => $v) {
922                 if (strpos($v, 'javascript:') === 0) {
923                         $v = substr($v, 11);
924                         $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
925                 } elseif ($v!='') {
926                         $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
927                 }
928         }
929         return $o;
930 }
931
932 /**
933  * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
934  * Increments the count of each matching activity and adds a link to the author as needed.
935  *
936  * @param array  $item
937  * @param array &$conv_responses (already created with builtin activity structure)
938  * @return void
939  * @throws ImagickException
940  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
941  */
942 function builtin_activity_puller($item, &$conv_responses) {
943         foreach ($conv_responses as $mode => $v) {
944                 $sparkle = '';
945
946                 switch ($mode) {
947                         case 'like':
948                                 $verb = ACTIVITY_LIKE;
949                                 break;
950                         case 'dislike':
951                                 $verb = ACTIVITY_DISLIKE;
952                                 break;
953                         case 'attendyes':
954                                 $verb = ACTIVITY_ATTEND;
955                                 break;
956                         case 'attendno':
957                                 $verb = ACTIVITY_ATTENDNO;
958                                 break;
959                         case 'attendmaybe':
960                                 $verb = ACTIVITY_ATTENDMAYBE;
961                                 break;
962                         default:
963                                 return;
964                 }
965
966                 if (activity_match($item['verb'], $verb) && ($item['id'] != $item['parent'])) {
967                         $author = ['uid' => 0, 'id' => $item['author-id'],
968                                 'network' => $item['author-network'], 'url' => $item['author-link']];
969                         $url = Contact::magicLinkbyContact($author);
970                         if (strpos($url, 'redir/') === 0) {
971                                 $sparkle = ' class="sparkle" ';
972                         }
973
974                         $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
975
976                         if (empty($item['thr-parent'])) {
977                                 $item['thr-parent'] = $item['parent-uri'];
978                         }
979
980                         if (!(isset($conv_responses[$mode][$item['thr-parent'] . '-l'])
981                                 && is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))) {
982                                 $conv_responses[$mode][$item['thr-parent'] . '-l'] = [];
983                         }
984
985                         // only list each unique author once
986                         if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
987                                 continue;
988                         }
989
990                         if (!isset($conv_responses[$mode][$item['thr-parent']])) {
991                                 $conv_responses[$mode][$item['thr-parent']] = 1;
992                         } else {
993                                 $conv_responses[$mode][$item['thr-parent']] ++;
994                         }
995
996                         if (public_contact() == $item['author-id']) {
997                                 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
998                         }
999
1000                         $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
1001
1002                         // there can only be one activity verb per item so if we found anything, we can stop looking
1003                         return;
1004                 }
1005         }
1006 }
1007
1008 /**
1009  * Format the vote text for a profile item
1010  *
1011  * @param int    $cnt  = number of people who vote the item
1012  * @param array  $arr  = array of pre-linked names of likers/dislikers
1013  * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1014  * @param int    $id   = item id
1015  * @return string formatted text
1016  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1017  */
1018 function format_like($cnt, array $arr, $type, $id) {
1019         $o = '';
1020         $expanded = '';
1021         $phrase = '';
1022
1023         if ($cnt == 1) {
1024                 $likers = $arr[0];
1025
1026                 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1027                 // list which show all likers
1028                 switch ($type) {
1029                         case 'like' :
1030                                 $phrase = L10n::t('%s likes this.', $likers);
1031                                 break;
1032                         case 'dislike' :
1033                                 $phrase = L10n::t('%s doesn\'t like this.', $likers);
1034                                 break;
1035                         case 'attendyes' :
1036                                 $phrase = L10n::t('%s attends.', $likers);
1037                                 break;
1038                         case 'attendno' :
1039                                 $phrase = L10n::t('%s doesn\'t attend.', $likers);
1040                                 break;
1041                         case 'attendmaybe' :
1042                                 $phrase = L10n::t('%s attends maybe.', $likers);
1043                                 break;
1044                 }
1045         }
1046
1047         if ($cnt > 1) {
1048                 $total = count($arr);
1049                 if ($total < MAX_LIKERS) {
1050                         $last = L10n::t('and') . ' ' . $arr[count($arr)-1];
1051                         $arr2 = array_slice($arr, 0, -1);
1052                         $likers = implode(', ', $arr2) . ' ' . $last;
1053                 } else  {
1054                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1055                         $likers = implode(', ', $arr);
1056                         $likers .= L10n::t('and %d other people', $total - MAX_LIKERS);
1057                 }
1058
1059                 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1060
1061                 $explikers = '';
1062                 switch ($type) {
1063                         case 'like':
1064                                 $phrase = L10n::t('<span  %1$s>%2$d people</span> like this', $spanatts, $cnt);
1065                                 $explikers = L10n::t('%s like this.', $likers);
1066                                 break;
1067                         case 'dislike':
1068                                 $phrase = L10n::t('<span  %1$s>%2$d people</span> don\'t like this', $spanatts, $cnt);
1069                                 $explikers = L10n::t('%s don\'t like this.', $likers);
1070                                 break;
1071                         case 'attendyes':
1072                                 $phrase = L10n::t('<span  %1$s>%2$d people</span> attend', $spanatts, $cnt);
1073                                 $explikers = L10n::t('%s attend.', $likers);
1074                                 break;
1075                         case 'attendno':
1076                                 $phrase = L10n::t('<span  %1$s>%2$d people</span> don\'t attend', $spanatts, $cnt);
1077                                 $explikers = L10n::t('%s don\'t attend.', $likers);
1078                                 break;
1079                         case 'attendmaybe':
1080                                 $phrase = L10n::t('<span  %1$s>%2$d people</span> attend maybe', $spanatts, $cnt);
1081                                 $explikers = L10n::t('%s attend maybe.', $likers);
1082                                 break;
1083                 }
1084
1085                 $expanded .= "\t" . '<p class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1086         }
1087
1088         $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1089                 '$phrase' => $phrase,
1090                 '$type' => $type,
1091                 '$id' => $id
1092         ]);
1093         $o .= $expanded;
1094
1095         return $o;
1096 }
1097
1098 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1099 {
1100         $o = '';
1101
1102         $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1103
1104         $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1105         $a->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
1106                 '$newpost'   => 'true',
1107                 '$baseurl'   => System::baseUrl(true),
1108                 '$geotag'    => $geotag,
1109                 '$nickname'  => $x['nickname'],
1110                 '$ispublic'  => L10n::t('Visible to <strong>everybody</strong>'),
1111                 '$linkurl'   => L10n::t('Please enter a image/video/audio/webpage URL:'),
1112                 '$term'      => L10n::t('Tag term:'),
1113                 '$fileas'    => L10n::t('Save to Folder:'),
1114                 '$whereareu' => L10n::t('Where are you right now?'),
1115                 '$delitems'  => L10n::t("Delete item\x28s\x29?")
1116         ]);
1117
1118         $jotplugins = '';
1119         Hook::callAll('jot_tool', $jotplugins);
1120
1121         // Private/public post links for the non-JS ACL form
1122         $private_post = 1;
1123         if (!empty($_REQUEST['public'])) {
1124                 $private_post = 0;
1125         }
1126
1127         $query_str = $a->query_string;
1128         if (strpos($query_str, 'public=1') !== false) {
1129                 $query_str = str_replace(['?public=1', '&public=1'], ['', ''], $query_str);
1130         }
1131
1132         /*
1133          * I think $a->query_string may never have ? in it, but I could be wrong
1134          * It looks like it's from the index.php?q=[etc] rewrite that the web
1135          * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1136          */
1137         if (strpos($query_str, '?') === false) {
1138                 $public_post_link = '?public=1';
1139         } else {
1140                 $public_post_link = '&public=1';
1141         }
1142
1143         // $tpl = Renderer::replaceMacros($tpl,array('$jotplugins' => $jotplugins));
1144         $tpl = Renderer::getMarkupTemplate("jot.tpl");
1145
1146         $o .= Renderer::replaceMacros($tpl,[
1147                 '$new_post' => L10n::t('New Post'),
1148                 '$return_path'  => $query_str,
1149                 '$action'       => 'item',
1150                 '$share'        => defaults($x, 'button', L10n::t('Share')),
1151                 '$upload'       => L10n::t('Upload photo'),
1152                 '$shortupload'  => L10n::t('upload photo'),
1153                 '$attach'       => L10n::t('Attach file'),
1154                 '$shortattach'  => L10n::t('attach file'),
1155                 '$edbold'       => L10n::t('Bold'),
1156                 '$editalic'     => L10n::t('Italic'),
1157                 '$eduline'      => L10n::t('Underline'),
1158                 '$edquote'      => L10n::t('Quote'),
1159                 '$edcode'       => L10n::t('Code'),
1160                 '$edimg'        => L10n::t('Image'),
1161                 '$edurl'        => L10n::t('Link'),
1162                 '$edattach'     => L10n::t('Link or Media'),
1163                 '$setloc'       => L10n::t('Set your location'),
1164                 '$shortsetloc'  => L10n::t('set location'),
1165                 '$noloc'        => L10n::t('Clear browser location'),
1166                 '$shortnoloc'   => L10n::t('clear location'),
1167                 '$title'        => defaults($x, 'title', ''),
1168                 '$placeholdertitle' => L10n::t('Set title'),
1169                 '$category'     => defaults($x, 'category', ''),
1170                 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? L10n::t("Categories \x28comma-separated list\x29") : '',
1171                 '$wait'         => L10n::t('Please wait'),
1172                 '$permset'      => L10n::t('Permission settings'),
1173                 '$shortpermset' => L10n::t('permissions'),
1174                 '$wall'         => $notes_cid ? 0 : 1,
1175                 '$posttype'     => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1176                 '$content'      => defaults($x, 'content', ''),
1177                 '$post_id'      => defaults($x, 'post_id', ''),
1178                 '$baseurl'      => System::baseUrl(true),
1179                 '$defloc'       => $x['default_location'],
1180                 '$visitor'      => $x['visitor'],
1181                 '$pvisit'       => $notes_cid ? 'none' : $x['visitor'],
1182                 '$public'       => L10n::t('Public post'),
1183                 '$lockstate'    => $x['lockstate'],
1184                 '$bang'         => $x['bang'],
1185                 '$profile_uid'  => $x['profile_uid'],
1186                 '$preview'      => L10n::t('Preview'),
1187                 '$jotplugins'   => $jotplugins,
1188                 '$notes_cid'    => $notes_cid,
1189                 '$sourceapp'    => L10n::t($a->sourcename),
1190                 '$cancel'       => L10n::t('Cancel'),
1191                 '$rand_num'     => Crypto::randomDigits(12),
1192
1193                 // ACL permissions box
1194                 '$acl'           => $x['acl'],
1195                 '$group_perms'   => L10n::t('Post to Groups'),
1196                 '$contact_perms' => L10n::t('Post to Contacts'),
1197                 '$private'       => L10n::t('Private post'),
1198                 '$is_private'    => $private_post,
1199                 '$public_link'   => $public_post_link,
1200
1201                 //jot nav tab (used in some themes)
1202                 '$message' => L10n::t('Message'),
1203                 '$browser' => L10n::t('Browser'),
1204         ]);
1205
1206
1207         if ($popup == true) {
1208                 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1209         }
1210
1211         return $o;
1212 }
1213
1214 /**
1215  * Plucks the children of the given parent from a given item list.
1216  *
1217  * @brief Plucks all the children in the given item list of the given parent
1218  *
1219  * @param array $item_list
1220  * @param array $parent
1221  * @param bool  $recursive
1222  * @return array
1223  */
1224 function get_item_children(array &$item_list, array $parent, $recursive = true)
1225 {
1226         $children = [];
1227         foreach ($item_list as $i => $item) {
1228                 if ($item['id'] != $item['parent']) {
1229                         if ($recursive) {
1230                                 // Fallback to parent-uri if thr-parent is not set
1231                                 $thr_parent = $item['thr-parent'];
1232                                 if ($thr_parent == '') {
1233                                         $thr_parent = $item['parent-uri'];
1234                                 }
1235
1236                                 if ($thr_parent == $parent['uri']) {
1237                                         $item['children'] = get_item_children($item_list, $item);
1238                                         $children[] = $item;
1239                                         unset($item_list[$i]);
1240                                 }
1241                         } elseif ($item['parent'] == $parent['id']) {
1242                                 $children[] = $item;
1243                                 unset($item_list[$i]);
1244                         }
1245                 }
1246         }
1247         return $children;
1248 }
1249
1250 /**
1251  * @brief Recursively sorts a tree-like item array
1252  *
1253  * @param array $items
1254  * @return array
1255  */
1256 function sort_item_children(array $items)
1257 {
1258         $result = $items;
1259         usort($result, 'sort_thr_created_rev');
1260         foreach ($result as $k => $i) {
1261                 if (isset($result[$k]['children'])) {
1262                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1263                 }
1264         }
1265         return $result;
1266 }
1267
1268 /**
1269  * @brief Recursively add all children items at the top level of a list
1270  *
1271  * @param array $children List of items to append
1272  * @param array $item_list
1273  */
1274 function add_children_to_list(array $children, array &$item_list)
1275 {
1276         foreach ($children as $child) {
1277                 $item_list[] = $child;
1278                 if (isset($child['children'])) {
1279                         add_children_to_list($child['children'], $item_list);
1280                 }
1281         }
1282 }
1283
1284 /**
1285  * This recursive function takes the item tree structure created by conv_sort() and
1286  * flatten the extraneous depth levels when people reply sequentially, removing the
1287  * stairs effect in threaded conversations limiting the available content width.
1288  *
1289  * The basic principle is the following: if a post item has only one reply and is
1290  * the last reply of its parent, then the reply is moved to the parent.
1291  *
1292  * This process is rendered somewhat more complicated because items can be either
1293  * replies or likes, and these don't factor at all in the reply count/last reply.
1294  *
1295  * @brief Selectively flattens a tree-like item structure to prevent threading stairs
1296  *
1297  * @param array $parent A tree-like array of items
1298  * @return array
1299  */
1300 function smart_flatten_conversation(array $parent)
1301 {
1302         if (!isset($parent['children']) || count($parent['children']) == 0) {
1303                 return $parent;
1304         }
1305
1306         // We use a for loop to ensure we process the newly-moved items
1307         for ($i = 0; $i < count($parent['children']); $i++) {
1308                 $child = $parent['children'][$i];
1309
1310                 if (isset($child['children']) && count($child['children'])) {
1311                         // This helps counting only the regular posts
1312                         $count_post_closure = function($var) {
1313                                 return $var['verb'] === ACTIVITY_POST;
1314                         };
1315
1316                         $child_post_count = count(array_filter($child['children'], $count_post_closure));
1317
1318                         $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1319
1320                         // If there's only one child's children post and this is the last child post
1321                         if ($child_post_count == 1 && $remaining_post_count == 1) {
1322
1323                                 // Searches the post item in the children
1324                                 $j = 0;
1325                                 while($child['children'][$j]['verb'] !== ACTIVITY_POST && $j < count($child['children'])) {
1326                                         $j ++;
1327                                 }
1328
1329                                 $moved_item = $child['children'][$j];
1330                                 unset($parent['children'][$i]['children'][$j]);
1331                                 $parent['children'][] = $moved_item;
1332                         } else {
1333                                 $parent['children'][$i] = smart_flatten_conversation($child);
1334                         }
1335                 }
1336         }
1337
1338         return $parent;
1339 }
1340
1341
1342 /**
1343  * Expands a flat list of items into corresponding tree-like conversation structures,
1344  * sort the top-level posts either on "created" or "commented", and finally
1345  * append all the items at the top level (???)
1346  *
1347  * @brief Expands a flat item list into a conversation array for display
1348  *
1349  * @param array  $item_list A list of items belonging to one or more conversations
1350  * @param string $order     Either on "created" or "commented"
1351  * @return array
1352  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1353  */
1354 function conv_sort(array $item_list, $order)
1355 {
1356         $parents = [];
1357
1358         if (!(is_array($item_list) && count($item_list))) {
1359                 return $parents;
1360         }
1361
1362         $blocklist = conv_get_blocklist();
1363
1364         $item_array = [];
1365
1366         // Dedupes the item list on the uri to prevent infinite loops
1367         foreach ($item_list as $item) {
1368                 if (in_array($item['author-id'], $blocklist)) {
1369                         continue;
1370                 }
1371
1372                 $item_array[$item['uri']] = $item;
1373         }
1374
1375         // Extract the top level items
1376         foreach ($item_array as $item) {
1377                 if ($item['id'] == $item['parent']) {
1378                         $parents[] = $item;
1379                 }
1380         }
1381
1382         if (stristr($order, 'created')) {
1383                 usort($parents, 'sort_thr_created');
1384         } elseif (stristr($order, 'commented')) {
1385                 usort($parents, 'sort_thr_commented');
1386         }
1387
1388         /*
1389          * Plucks children from the item_array, second pass collects eventual orphan
1390          * items and add them as children of their top-level post.
1391          */
1392         foreach ($parents as $i => $parent) {
1393                 $parents[$i]['children'] =
1394                         array_merge(get_item_children($item_array, $parent, true),
1395                                 get_item_children($item_array, $parent, false));
1396         }
1397
1398         foreach ($parents as $i => $parent) {
1399                 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1400         }
1401
1402         if (PConfig::get(local_user(), 'system', 'smart_threading', 0)) {
1403                 foreach ($parents as $i => $parent) {
1404                         $parents[$i] = smart_flatten_conversation($parent);
1405                 }
1406         }
1407
1408         /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1409         /// However, this apparently ensures responses (likes, attendance) display (?!)
1410         foreach ($parents as $parent) {
1411                 if (count($parent['children'])) {
1412                         add_children_to_list($parent['children'], $parents);
1413                 }
1414         }
1415
1416         return $parents;
1417 }
1418
1419 /**
1420  * @brief usort() callback to sort item arrays by the created key
1421  *
1422  * @param array $a
1423  * @param array $b
1424  * @return int
1425  */
1426 function sort_thr_created(array $a, array $b)
1427 {
1428         return strcmp($b['created'], $a['created']);
1429 }
1430
1431 /**
1432  * @brief usort() callback to reverse sort item arrays by the created key
1433  *
1434  * @param array $a
1435  * @param array $b
1436  * @return int
1437  */
1438 function sort_thr_created_rev(array $a, array $b)
1439 {
1440         return strcmp($a['created'], $b['created']);
1441 }
1442
1443 /**
1444  * @brief usort() callback to sort item arrays by the commented key
1445  *
1446  * @param array $a
1447  * @param array $b
1448  * @return int
1449  */
1450 function sort_thr_commented(array $a, array $b)
1451 {
1452         return strcmp($b['commented'], $a['commented']);
1453 }
1454
1455 function render_location_dummy(array $item) {
1456         if (!empty($item['location']) && !empty($item['location'])) {
1457                 return $item['location'];
1458         }
1459
1460         if (!empty($item['coord']) && !empty($item['coord'])) {
1461                 return $item['coord'];
1462         }
1463 }
1464
1465 function get_responses(array $conv_responses, array $response_verbs, array $item, Post $ob = null) {
1466         $ret = [];
1467         foreach ($response_verbs as $v) {
1468                 $ret[$v] = [];
1469                 $ret[$v]['count'] = defaults($conv_responses[$v], $item['uri'], 0);
1470                 $ret[$v]['list']  = defaults($conv_responses[$v], $item['uri'] . '-l', []);
1471                 $ret[$v]['self']  = defaults($conv_responses[$v], $item['uri'] . '-self', '0');
1472                 if (count($ret[$v]['list']) > MAX_LIKERS) {
1473                         $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
1474                         array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
1475                                 . (($ob) ? $ob->getId() : $item['id']) . '"><b>' . L10n::t('View all') . '</b></a>');
1476                 } else {
1477                         $ret[$v]['list_part'] = '';
1478                 }
1479                 $ret[$v]['button'] = get_response_button_text($v, $ret[$v]['count']);
1480                 $ret[$v]['title'] = $conv_responses[$v]['title'];
1481         }
1482
1483         $count = 0;
1484         foreach ($ret as $key) {
1485                 if ($key['count'] == true) {
1486                         $count++;
1487                 }
1488         }
1489         $ret['count'] = $count;
1490
1491         return $ret;
1492 }
1493
1494 function get_response_button_text($v, $count)
1495 {
1496         $return = '';
1497         switch ($v) {
1498                 case 'like':
1499                         $return = L10n::tt('Like', 'Likes', $count);
1500                         break;
1501                 case 'dislike':
1502                         $return = L10n::tt('Dislike', 'Dislikes', $count);
1503                         break;
1504                 case 'attendyes':
1505                         $return = L10n::tt('Attending', 'Attending', $count);
1506                         break;
1507                 case 'attendno':
1508                         $return = L10n::tt('Not Attending', 'Not Attending', $count);
1509                         break;
1510                 case 'attendmaybe':
1511                         $return = L10n::tt('Undecided', 'Undecided', $count);
1512                         break;
1513         }
1514
1515         return $return;
1516 }