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