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