]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
port of the event attendance feature of red matrix with example implementation for...
[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_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                 'attendyes' => array('title' => t('Attending','title')), 'attendno' => array('title' => t('Not attending','title')), 'attendmaybe' => array('title' => t('Might attend','title'))
497         );
498
499         // array with html for each thread (parent+comments)
500         $threads = array();
501         $threadsid = -1;
502
503         $page_template = get_markup_template("conversation.tpl");
504
505         if($items && count($items)) {
506
507                 if($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
508
509                         // "New Item View" on network page or search page results
510                         // - just loop through the items and format them minimally for display
511
512 //                      $tpl = get_markup_template('search_item.tpl');
513                         $tpl = 'search_item.tpl';
514
515                         foreach($items as $item) {
516
517                                 if($arr_blocked) {
518                                         $blocked = false;
519                                         foreach($arr_blocked as $b) {
520                                                 if($b && link_compare($item['author-link'],$b)) {
521                                                         $blocked = true;
522                                                         break;
523                                                 }
524                                         }
525                                         if($blocked)
526                                                 continue;
527                                 }
528
529
530                                 $threadsid++;
531
532                                 $comment     = '';
533                                 $owner_url   = '';
534                                 $owner_photo = '';
535                                 $owner_name  = '';
536                                 $sparkle     = '';
537
538                                 if($mode === 'search' || $mode === 'community') {
539                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE)))
540                                                 && ($item['id'] != $item['parent']))
541                                                 continue;
542                                         $nickname = $item['nickname'];
543                                 }
544                                 else
545                                         $nickname = $a->user['nickname'];
546
547                                 // prevent private email from leaking.
548                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
549                                                 continue;
550
551                                 $profile_name   = ((strlen($item['author-name']))   ? $item['author-name']   : $item['name']);
552                                 if($item['author-link'] && (! $item['author-name']))
553                                         $profile_name = $item['author-link'];
554
555
556
557                                 $tags=array();
558                                 $hashtags = array();
559                                 $mentions = array();
560
561                                 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
562                                                 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
563
564                                 foreach($taglist as $tag) {
565
566                                         if ($tag["url"] == "")
567                                                 $tag["url"] = $searchpath.strtolower($tag["term"]);
568
569                                         if ($tag["type"] == TERM_HASHTAG) {
570                                                 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
571                                                 $prefix = "#";
572                                         } elseif ($tag["type"] == TERM_MENTION) {
573                                                 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
574                                                 $prefix = "@";
575                                         }
576                                         $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
577                                 }
578
579                                 /*foreach(explode(',',$item['tag']) as $tag){
580                                         $tag = trim($tag);
581                                         if ($tag!="") {
582                                                 $t = bbcode($tag);
583                                                 $tags[] = $t;
584                                                 if($t[0] == '#')
585                                                         $hashtags[] = $t;
586                                                 elseif($t[0] == '@')
587                                                         $mentions[] = $t;
588                                         }
589                                 }*/
590
591                                 $sp = false;
592                                 $profile_link = best_link_url($item,$sp);
593                                 if($profile_link === 'mailbox')
594                                         $profile_link = '';
595                                 if($sp)
596                                         $sparkle = ' sparkle';
597                                 else
598                                         $profile_link = zrl($profile_link);
599
600                                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
601                                 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
602                                         $profile_avatar = $a->contacts[$normalised]['thumb'];
603                                 else
604                                         $profile_avatar = ((strlen($item['author-avatar'])) ? $a->get_cached_avatar_image($item['author-avatar']) : $item['thumb']);
605
606                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
607                                 call_hooks('render_location',$locate);
608
609                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
610
611                                 localize_item($item);
612                                 if($mode === 'network-new')
613                                         $dropping = true;
614                                 else
615                                         $dropping = false;
616
617
618                                 $drop = array(
619                                         'dropping' => $dropping,
620                                         'pagedrop' => $page_dropping,
621                                         'select' => t('Select'),
622                                         'delete' => t('Delete'),
623                                 );
624
625                                 $star = false;
626                                 $isstarred = "unstarred";
627
628                                 $lock = false;
629                                 $likebuttons = false;
630                                 $shareable = false;
631
632                                 $body = prepare_body($item,true, $preview);
633
634
635                                 list($categories, $folders) = get_cats_and_terms($item);
636
637                                 if($a->theme['template_engine'] === 'internal') {
638                                         $profile_name_e = template_escape($profile_name);
639                                         $item['title_e'] = template_escape($item['title']);
640                                         $body_e = template_escape($body);
641                                         $tags_e = template_escape($tags);
642                                         $hashtags_e = template_escape($hashtags);
643                                         $mentions_e = template_escape($mentions);
644                                         $location_e = template_escape($location);
645                                         $owner_name_e = template_escape($owner_name);
646                                 }
647                                 else {
648                                         $profile_name_e = $profile_name;
649                                         $item['title_e'] = $item['title'];
650                                         $body_e = $body;
651                                         $tags_e = $tags;
652                                         $hashtags_e = $hashtags;
653                                         $mentions_e = $mentions;
654                                         $location_e = $location;
655                                         $owner_name_e = $owner_name;
656                                 }
657
658                                 $tmp_item = array(
659                                         'template' => $tpl,
660                                         'id' => (($preview) ? 'P0' : $item['item_id']),
661                                         'network' => $item['item_network'],
662                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
663                                         'profile_url' => $profile_link,
664                                         'item_photo_menu' => item_photo_menu($item),
665                                         'name' => $profile_name_e,
666                                         'sparkle' => $sparkle,
667                                         'lock' => $lock,
668                                         'thumb' => proxy_url($profile_avatar),
669                                         'title' => $item['title_e'],
670                                         'body' => $body_e,
671                                         'tags' => $tags_e,
672                                         'hashtags' => $hashtags_e,
673                                         'mentions' => $mentions_e,
674                                         'txt_cats' => t('Categories:'),
675                                         'txt_folders' => t('Filed under:'),
676                                         'has_cats' => ((count($categories)) ? 'true' : ''),
677                                         'has_folders' => ((count($folders)) ? 'true' : ''),
678                                         'categories' => $categories,
679                                         'folders' => $folders,
680                                         'text' => strip_tags($body_e),
681                                         'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
682                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
683                                         'location' => $location_e,
684                                         'indent' => '',
685                                         'owner_name' => $owner_name_e,
686                                         'owner_url' => $owner_url,
687                                         'owner_photo' => proxy_url($owner_photo),
688                                         'plink' => get_plink($item),
689                                         'edpost' => false,
690                                         'isstarred' => $isstarred,
691                                         'star' => $star,
692                                         'drop' => $drop,
693                                         'vote' => $likebuttons,
694                                         'like' => '',
695                                         'dislike' => '',
696                                         'comment' => '',
697                                         //'conv' => (($preview) ? '' : array('href'=> $a->get_baseurl($ssl_state) . '/display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
698                                         'conv' => (($preview) ? '' : array('href'=> $a->get_baseurl($ssl_state) . '/display/'.$item['guid'], 'title'=> t('View in context'))),
699                                         'previewing' => $previewing,
700                                         'wait' => t('Please wait'),
701                                         'thread_level' => 1,
702                                 );
703
704                                 $arr = array('item' => $item, 'output' => $tmp_item);
705                                 call_hooks('display_item', $arr);
706
707                                 $threads[$threadsid]['id'] = $item['item_id'];
708                                 $threads[$threadsid]['network'] = $item['item_network'];
709                                 $threads[$threadsid]['items'] = array($arr['output']);
710
711                         }
712                 }
713                 else
714                 {
715                         // Normal View
716                         $page_template = get_markup_template("threaded_conversation.tpl");
717
718                         require_once('object/Conversation.php');
719                         require_once('object/Item.php');
720
721                         $conv = new Conversation($mode, $preview);
722
723                         // get all the topmost parents
724                         // this shouldn't be needed, as we should have only them in our array
725                         // But for now, this array respects the old style, just in case
726
727                         $threads = array();
728                         foreach($items as $item) {
729
730                                 if($arr_blocked) {
731                                         $blocked = false;
732                                         foreach($arr_blocked as $b) {
733
734                                                 if($b && link_compare($item['author-link'],$b)) {
735                                                         $blocked = true;
736                                                         break;
737                                                 }
738                                         }
739                                         if($blocked)
740                                                 continue;
741                                 }
742
743
744
745                                 // Can we put this after the visibility check?
746                                 builtin_activity_puller($item, $conv_responses);
747
748                                 // Only add what is visible
749                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
750                                         continue;
751                                 }
752                                 if(! visible_activity($item)) {
753                                         continue;
754                                 }
755
756                                 call_hooks('display_item', $arr);
757
758                                 $item['pagedrop'] = $page_dropping;
759
760                                 if($item['id'] == $item['parent']) {
761                                         $item_object = new Item($item);
762                                         $conv->add_thread($item_object);
763                                 }
764                         }
765
766                         $threads = $conv->get_template_data($conv_responses);
767
768                         if(!$threads) {
769                                 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
770                                 $threads = array();
771                         }
772                 }
773         }
774
775         $o = replace_macros($page_template, array(
776                 '$baseurl' => $a->get_baseurl($ssl_state),
777                 '$return_path' => $a->query_string,
778                 '$live_update' => $live_update_div,
779                 '$remove' => t('remove'),
780                 '$mode' => $mode,
781                 '$user' => $a->user,
782                 '$threads' => $threads,
783                 '$dropping' => ($page_dropping && feature_enabled(local_user(),'multi_delete') ? t('Delete Selected Items') : False),
784         ));
785
786         return $o;
787 }}
788
789 function best_link_url($item,&$sparkle,$ssl_state = false) {
790
791         $a = get_app();
792
793         $best_url = '';
794         $sparkle  = false;
795
796         $clean_url = normalise_link($item['author-link']);
797
798         if((local_user()) && (local_user() == $item['uid'])) {
799                 if(isset($a->contacts) && x($a->contacts,$clean_url)) {
800                         if($a->contacts[$clean_url]['network'] === NETWORK_DFRN) {
801                                 $best_url = $a->get_baseurl($ssl_state) . '/redir/' . $a->contacts[$clean_url]['id'];
802                                 $sparkle = true;
803                         }
804                         else
805                                 $best_url = $a->contacts[$clean_url]['url'];
806                 }
807         }
808         if(! $best_url) {
809                 if(strlen($item['author-link']))
810                         $best_url = $item['author-link'];
811                 else
812                         $best_url = $item['url'];
813         }
814
815         return $best_url;
816 }
817
818
819 if(! function_exists('item_photo_menu')){
820 function item_photo_menu($item){
821         $a = get_app();
822
823         $ssl_state = false;
824
825         if(local_user()) {
826                 $ssl_state = true;
827                  if(! count($a->contacts))
828                         load_contact_links(local_user());
829         }
830         $sub_link="";
831         $poke_link="";
832         $contact_url="";
833         $pm_url="";
834         $status_link="";
835         $photos_link="";
836         $posts_link="";
837
838         if((local_user()) && local_user() == $item['uid'] && $item['parent'] == $item['id'] && (! $item['self'])) {
839                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
840         }
841
842         $sparkle = false;
843         $profile_link = best_link_url($item,$sparkle,$ssl_state);
844         if($profile_link === 'mailbox')
845                 $profile_link = '';
846
847         if($sparkle) {
848                 $cid = intval(basename($profile_link));
849                 $status_link = $profile_link . "?url=status";
850                 $photos_link = $profile_link . "?url=photos";
851                 $profile_link = $profile_link . "?url=profile";
852                 $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
853                 $zurl = '';
854         }
855         else {
856                 $profile_link = zrl($profile_link);
857                 if(local_user() && local_user() == $item['uid'] && link_compare($item['url'],$item['author-link'])) {
858                         $cid = $item['contact-id'];
859                 }
860                 else {
861                         $cid = 0;
862                 }
863         }
864         if(($cid) && (! $item['self'])) {
865                 $poke_link = $a->get_baseurl($ssl_state) . '/poke/?f=&c=' . $cid;
866                 $contact_url = $a->get_baseurl($ssl_state) . '/contacts/' . $cid;
867                 $posts_link = $a->get_baseurl($ssl_state) . '/network/0?nets=all&cid=' . $cid;
868
869                 $clean_url = normalise_link($item['author-link']);
870
871                 if((local_user()) && (local_user() == $item['uid'])) {
872                         if(isset($a->contacts) && x($a->contacts,$clean_url)) {
873                                 if($a->contacts[$clean_url]['network'] === NETWORK_DIASPORA) {
874                                         $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
875                                 }
876                         }
877                 }
878
879         }
880
881         $menu = Array(
882                 t("Follow Thread") => $sub_link,
883                 t("View Status") => $status_link,
884                 t("View Profile") => $profile_link,
885                 t("View Photos") => $photos_link,
886                 t("Network Posts") => $posts_link,
887                 t("Edit Contact") => $contact_url,
888                 t("Send PM") => $pm_url,
889                 t("Poke") => $poke_link
890         );
891
892
893         $args = array('item' => $item, 'menu' => $menu);
894
895         call_hooks('item_photo_menu', $args);
896
897         $menu = $args['menu'];
898
899         $o = "";
900         foreach($menu as $k=>$v){
901                 if(strpos($v,'javascript:') === 0) {
902                         $v = substr($v,11);
903                         $o .= "<li role=\"menuitem\"><a onclick=\"$v\">$k</a></li>\n";
904                 }
905                 elseif ($v!="") $o .= "<li role=\"menuitem\"><a href=\"$v\">$k</a></li>\n";
906         }
907         return $o;
908 }}
909
910 /**
911  * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
912  * Increments the count of each matching activity and adds a link to the author as needed.
913  *
914  * @param array $a (not used)
915  * @param array $item
916  * @param array &$conv_responses (already created with builtin activity structure)
917  * @return void
918  */
919 if(! function_exists(builtin_activity_puller)) {
920 function builtin_activity_puller($item, &$conv_responses) {
921         foreach($conv_responses as $mode => $v) {
922                 $url = '';
923                 $sparkle = '';
924
925                 switch($mode) {
926                         case 'like':
927                                 $verb = ACTIVITY_LIKE;
928                                 break;
929                         case 'dislike':
930                                 $verb = ACTIVITY_DISLIKE;
931                                 break;
932                         case 'attendyes':
933                                 $verb = ACTIVITY_ATTEND;
934                                 break;
935                         case 'attendno':
936                                 $verb = ACTIVITY_ATTENDNO;
937                                 break;
938                         case 'attendmaybe':
939                                 $verb = ACTIVITY_ATTENDMAYBE;
940                                 break;
941                         default:
942                                 return;
943                                 break;
944                 }
945
946                 if((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) {
947                         $url = $item['author-link'];
948                         if((local_user()) && (local_user() == $item['uid']) && ($item['network'] === NETWORK_DFRN) && (! $item['self']) && (link_compare($item['author-link'],$item['url']))) {
949                                 $url = z_root(true) . '/redir/' . $item['contact-id'];
950                                 $sparkle = ' class="sparkle" ';
951                         }
952                         else 
953                                 $url = zrl($url);
954                         
955                         $url = '<a href="'. $url . '"'. $sparkle .'>' . $item['author-name'] . '</a>';
956
957                         if(! $item['thr-parent'])
958                                 $item['thr-parent'] = $item['parent-uri'];
959
960                         if(! ((isset($conv_responses[$mode][$item['thr-parent'] . '-l'])) 
961                                 && (is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))))
962                                 $conv_responses[$mode][$item['thr-parent'] . '-l'] = array();
963
964                         // only list each unique author once
965                         if(in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l']))
966                                 continue;
967
968                         if(! isset($conv_responses[$mode][$item['thr-parent']]))
969                                 $conv_responses[$mode][$item['thr-parent']] = 1;
970                         else
971                                 $conv_responses[$mode][$item['thr-parent']] ++;
972
973                         $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
974
975                         // there can only be one activity verb per item so if we found anything, we can stop looking
976                         return;
977                 }
978         }
979 }}
980
981 // Format the vote text for a profile item
982 // $cnt = number of people who vote the item
983 // $arr = array of pre-linked names of likers/dislikers
984 // $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
985 // $id  = item id
986 // returns formatted text
987
988 if(! function_exists('format_like')) {
989 function format_like($cnt,$arr,$type,$id) {
990         $o = '';
991         $expanded = '';
992
993         if($cnt == 1)
994                 $likers = $arr[0];
995
996         else {
997                 $total = count($arr);
998                 if($total >= MAX_LIKERS)
999                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1000                 if($total < MAX_LIKERS) {
1001                         $last = t('and') . ' ' . $arr[count($arr)-1];
1002                         $arr2 = array_slice($arr, 0, -1);
1003                         $str = implode(', ', $arr2) . ' ' . $last;
1004                 }
1005                 if($total >= MAX_LIKERS) {
1006                         $str = implode(', ', $arr);
1007                         $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
1008                 }
1009
1010                 $likers = $str;
1011         }
1012
1013         // Phrase if there is only one liker. In other cases it will be uses for the expanded
1014         // list which show all likers
1015         switch($type) {
1016                 case 'like' :
1017                         $phrase = sprintf( t('%s likes this.'), $likers);
1018                         break;
1019                 case 'dislike' :
1020                         $phrase = sprintf( t('%s doesn\'t like this.'), $likers);
1021                         break;
1022                 case 'attendyes' :
1023                         $phrase = sprintf( t('%s attends.'), $likers);
1024                         break;
1025                 case 'attendno' :
1026                         $phrase = sprintf( t('%s doesn\'t attend.'), $likers);
1027                         break;
1028                 case 'attendmaybe' :
1029                         $phrase = sprintf( t('%s attends maybe.'), $likers);
1030                         break;
1031         }
1032
1033         if($cnt > 1) {
1034                 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1035                 $expanded .= "\t" . '<div class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $phrase . EOL . '</div>';
1036                 switch($type) {
1037                         case 'like':
1038                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> like this'), $spanatts, $cnt);
1039                                 break;
1040                         case 'dislike':
1041                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> don\'t like this'), $spanatts, $cnt);
1042                                 break;
1043                         case 'attendyes':
1044                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> attend'), $spanatts, $cnt);
1045                                 break;
1046                         case 'attendno':
1047                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> don\'t attend'), $spanatts, $cnt);
1048                                 break;
1049                         case 'attendmaybe':
1050                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> anttend maybe'), $spanatts, $cnt);
1051                         case 'agree':
1052                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> agree'), $spanatts, $cnt);
1053                                 break;
1054                         case 'disagree':
1055                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> don\'t agree'), $spanatts, $cnt);
1056                                 break;
1057                         case 'abstain':
1058                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> abstains'), $spanatts, $cnt);
1059                 }
1060         }
1061
1062         $phrase .= EOL ;
1063         $o .= replace_macros(get_markup_template('voting_fakelink.tpl'), array(
1064                 '$phrase' => $phrase,
1065                 '$type' => $type,
1066                 '$id' => $id
1067         ));
1068         $o .= $expanded;
1069
1070         return $o;
1071 }}
1072
1073
1074 function status_editor($a,$x, $notes_cid = 0, $popup=false) {
1075
1076         $o = '';
1077
1078         $geotag = (($x['allow_location']) ? replace_macros(get_markup_template('jot_geotag.tpl'), array()) : '');
1079
1080 /*      $plaintext = false;
1081         if( local_user() && (intval(get_pconfig(local_user(),'system','plaintext')) || !feature_enabled(local_user(),'richtext')) )
1082                 $plaintext = true;*/
1083         $plaintext = true;
1084         if( local_user() && feature_enabled(local_user(),'richtext') )
1085                 $plaintext = false;
1086
1087         $tpl = get_markup_template('jot-header.tpl');
1088         $a->page['htmlhead'] .= replace_macros($tpl, array(
1089                 '$newpost' => 'true',
1090                 '$baseurl' => $a->get_baseurl(true),
1091                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
1092                 '$geotag' => $geotag,
1093                 '$nickname' => $x['nickname'],
1094                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1095                 '$linkurl' => t('Please enter a link URL:'),
1096                 '$vidurl' => t("Please enter a video link/URL:"),
1097                 '$audurl' => t("Please enter an audio link/URL:"),
1098                 '$term' => t('Tag term:'),
1099                 '$fileas' => t('Save to Folder:'),
1100                 '$whereareu' => t('Where are you right now?'),
1101                 '$delitems' => t('Delete item(s)?')
1102         ));
1103
1104
1105         $tpl = get_markup_template('jot-end.tpl');
1106         $a->page['end'] .= replace_macros($tpl, array(
1107                 '$newpost' => 'true',
1108                 '$baseurl' => $a->get_baseurl(true),
1109                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
1110                 '$geotag' => $geotag,
1111                 '$nickname' => $x['nickname'],
1112                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1113                 '$linkurl' => t('Please enter a link URL:'),
1114                 '$vidurl' => t("Please enter a video link/URL:"),
1115                 '$audurl' => t("Please enter an audio link/URL:"),
1116                 '$term' => t('Tag term:'),
1117                 '$fileas' => t('Save to Folder:'),
1118                 '$whereareu' => t('Where are you right now?')
1119         ));
1120
1121         $jotplugins = '';
1122         call_hooks('jot_tool', $jotplugins);
1123
1124         // Private/public post links for the non-JS ACL form
1125         $private_post = 1;
1126         if($_REQUEST['public'])
1127                 $private_post = 0;
1128
1129         $query_str = $a->query_string;
1130         if(strpos($query_str, 'public=1') !== false)
1131                 $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
1132
1133         // I think $a->query_string may never have ? in it, but I could be wrong
1134         // It looks like it's from the index.php?q=[etc] rewrite that the web
1135         // server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1136         if(strpos($query_str, '?') === false)
1137                 $public_post_link = '?public=1';
1138         else
1139                 $public_post_link = '&public=1';
1140
1141
1142
1143 //      $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
1144         $tpl = get_markup_template("jot.tpl");
1145
1146         $o .= replace_macros($tpl,array(
1147                 '$return_path' => $query_str,
1148                 '$action' =>  $a->get_baseurl(true) . '/item',
1149                 '$share' => (x($x,'button') ? $x['button'] : t('Share')),
1150                 '$upload' => t('Upload photo'),
1151                 '$shortupload' => t('upload photo'),
1152                 '$attach' => t('Attach file'),
1153                 '$shortattach' => t('attach file'),
1154                 '$weblink' => t('Insert web link'),
1155                 '$shortweblink' => t('web link'),
1156                 '$video' => t('Insert video link'),
1157                 '$shortvideo' => t('video link'),
1158                 '$audio' => t('Insert audio link'),
1159                 '$shortaudio' => t('audio link'),
1160                 '$setloc' => t('Set your location'),
1161                 '$shortsetloc' => t('set location'),
1162                 '$noloc' => t('Clear browser location'),
1163                 '$shortnoloc' => t('clear location'),
1164                 '$title' => $x['title'],
1165                 '$placeholdertitle' => t('Set title'),
1166                 '$category' => $x['category'],
1167                 '$placeholdercategory' => (feature_enabled(local_user(),'categories') ? t('Categories (comma-separated list)') : ''),
1168                 '$wait' => t('Please wait'),
1169                 '$permset' => t('Permission settings'),
1170                 '$shortpermset' => t('permissions'),
1171                 '$ptyp' => (($notes_cid) ? 'note' : 'wall'),
1172                 '$content' => $x['content'],
1173                 '$post_id' => $x['post_id'],
1174                 '$baseurl' => $a->get_baseurl(true),
1175                 '$defloc' => $x['default_location'],
1176                 '$visitor' => $x['visitor'],
1177                 '$pvisit' => (($notes_cid) ? 'none' : $x['visitor']),
1178                 '$public' => t('Public post'),
1179                 '$jotnets' => $jotnets,
1180                 '$lockstate' => $x['lockstate'],
1181                 '$bang' => $x['bang'],
1182                 '$profile_uid' => $x['profile_uid'],
1183                 '$preview' => ((feature_enabled($x['profile_uid'],'preview')) ? t('Preview') : ''),
1184                 '$jotplugins' => $jotplugins,
1185                 '$notes_cid' => $notes_cid,
1186                 '$sourceapp' => t($a->sourcename),
1187                 '$cancel' => t('Cancel'),
1188                 '$rand_num' => random_digits(12),
1189
1190                 // ACL permissions box
1191                 '$acl' => $x['acl'],
1192                 '$acl_data' => $x['acl_data'],
1193                 '$group_perms' => t('Post to Groups'),
1194                 '$contact_perms' => t('Post to Contacts'),
1195                 '$private' => t('Private post'),
1196                 '$is_private' => $private_post,
1197                 '$public_link' => $public_post_link,
1198         ));
1199
1200
1201         if ($popup==true){
1202                 $o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
1203
1204         }
1205
1206         return $o;
1207 }
1208
1209
1210 function get_item_children($arr, $parent) {
1211         $children = array();
1212         $a = get_app();
1213         foreach($arr as $item) {
1214                 if($item['id'] != $item['parent']) {
1215                         if(get_config('system','thread_allow') && $a->theme_thread_allow) {
1216                                 // Fallback to parent-uri if thr-parent is not set
1217                                 $thr_parent = $item['thr-parent'];
1218                                 if($thr_parent == '')
1219                                         $thr_parent = $item['parent-uri'];
1220
1221                                 if($thr_parent == $parent['uri']) {
1222                                         $item['children'] = get_item_children($arr, $item);
1223                                         $children[] = $item;
1224                                 }
1225                         }
1226                         else if($item['parent'] == $parent['id']) {
1227                                 $children[] = $item;
1228                         }
1229                 }
1230         }
1231         return $children;
1232 }
1233
1234 function sort_item_children($items) {
1235         $result = $items;
1236         usort($result,'sort_thr_created_rev');
1237         foreach($result as $k => $i) {
1238                 if(count($result[$k]['children'])) {
1239                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1240                 }
1241         }
1242         return $result;
1243 }
1244
1245 function add_children_to_list($children, &$arr) {
1246         foreach($children as $y) {
1247                 $arr[] = $y;
1248                 if(count($y['children']))
1249                         add_children_to_list($y['children'], $arr);
1250         }
1251 }
1252
1253 function conv_sort($arr,$order) {
1254
1255         if((!(is_array($arr) && count($arr))))
1256                 return array();
1257
1258         $parents = array();
1259         $children = array();
1260
1261         foreach($arr as $x)
1262                 if($x['id'] == $x['parent'])
1263                                 $parents[] = $x;
1264
1265         if(stristr($order,'created'))
1266                 usort($parents,'sort_thr_created');
1267         elseif(stristr($order,'commented'))
1268                 usort($parents,'sort_thr_commented');
1269
1270         if(count($parents))
1271                 foreach($parents as $i=>$_x)
1272                         $parents[$i]['children'] = get_item_children($arr, $_x);
1273
1274         /*foreach($arr as $x) {
1275                 if($x['id'] != $x['parent']) {
1276                         $p = find_thread_parent_index($parents,$x);
1277                         if($p !== false)
1278                                 $parents[$p]['children'][] = $x;
1279                 }
1280         }*/
1281         if(count($parents)) {
1282                 foreach($parents as $k => $v) {
1283                         if(count($parents[$k]['children'])) {
1284                                 $parents[$k]['children'] = sort_item_children($parents[$k]['children']);
1285                                 /*$y = $parents[$k]['children'];
1286                                 usort($y,'sort_thr_created_rev');
1287                                 $parents[$k]['children'] = $y;*/
1288                         }
1289                 }
1290         }
1291
1292         $ret = array();
1293         if(count($parents)) {
1294                 foreach($parents as $x) {
1295                         $ret[] = $x;
1296                         if(count($x['children']))
1297                                 add_children_to_list($x['children'], $ret);
1298                                 /*foreach($x['children'] as $y)
1299                                         $ret[] = $y;*/
1300                 }
1301         }
1302
1303         return $ret;
1304 }
1305
1306
1307 function sort_thr_created($a,$b) {
1308         return strcmp($b['created'],$a['created']);
1309 }
1310
1311 function sort_thr_created_rev($a,$b) {
1312         return strcmp($a['created'],$b['created']);
1313 }
1314
1315 function sort_thr_commented($a,$b) {
1316         return strcmp($b['commented'],$a['commented']);
1317 }
1318
1319 function find_thread_parent_index($arr,$x) {
1320         foreach($arr as $k => $v)
1321                 if($v['id'] == $x['parent'])
1322                         return $k;
1323         return false;
1324 }
1325
1326 function render_location_dummy($item) {
1327         if ($item['location'] != "")
1328                 return $item['location'];
1329
1330         if ($item['coord'] != "")
1331                 return $item['coord'];
1332 }
1333
1334 function get_responses($conv_responses,$response_verbs,$ob,$item) {
1335         $ret = array();
1336         foreach($response_verbs as $v) {
1337                 $ret[$v] = array();
1338                 $ret[$v]['count'] = ((x($conv_responses[$v],$item['uri'])) ? $conv_responses[$v][$item['uri']] : '');
1339                 $ret[$v]['list']  = ((x($conv_responses[$v],$item['uri'])) ? $conv_responses[$v][$item['uri'] . '-l'] : '');
1340                 if(count($ret[$v]['list']) > MAX_LIKERS) {
1341                         $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
1342                         array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-' 
1343                                 . (($ob) ? $ob->get_id() : $item['id']) . '"><b>' . t('View all') . '</b></a>');
1344                 }
1345                 else {
1346                         $ret[$v]['list_part'] = '';
1347                 }
1348                 $ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']);
1349                 $ret[$v]['title'] = $conv_responses[$v]['title'];
1350         }
1351
1352         $count = 0;
1353         foreach($ret as $key) {
1354                 if ($key['count'] == true)
1355                         $count++;
1356         }
1357         $ret['count'] = $count;
1358
1359         return $ret;
1360 }
1361
1362 function get_response_button_text($v,$count) {
1363         switch($v) {
1364                 case 'like':
1365                         return tt('Like','Likes',$count,'noun');
1366                         break;
1367                 case 'dislike':
1368                         return tt('Dislike','Dislikes',$count,'noun');
1369                         break;
1370                 case 'attendyes':
1371                         return tt('Attending','Attending',$count,'noun');
1372                         break;
1373                 case 'attendno':
1374                         return tt('Not Attending','Not Attending',$count,'noun');
1375                         break;
1376                 case 'attendmaybe':
1377                         return tt('Undecided','Undecided',$count,'noun');
1378                         break;
1379         }
1380 }