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