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