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