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