]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
416efa1509e9df5c4a72b9011458f30ffdfa19b3
[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  * @brief List of all contact fields that are needed for the conversation function
378  */
379 function contact_fieldlist() {
380
381         $fieldlist = "`contact`.`network`, `contact`.`url`, `contact`.`name`, `contact`.`writable`,
382                         `contact`.`self`, `contact`.`id` AS `cid`, `contact`.`alias`";
383
384         return $fieldlist;
385 }
386
387 /**
388  * @brief SQL condition for contacts
389  */
390 function contact_condition() {
391
392         $condition = "NOT `contact`.`blocked` AND NOT `contact`.`pending`";
393
394         return $condition;
395 }
396
397 /**
398  * @brief List of all item fields that are needed for the conversation function
399  */
400 function item_fieldlist() {
401
402 /*
403 These Fields are not added below (yet). They are here to for bug search.
404 `item`.`type`,
405 `item`.`extid`,
406 `item`.`received`,
407 `item`.`changed`,
408 `item`.`author-avatar`,
409 `item`.`object`,
410 `item`.`target-type`,
411 `item`.`target`,
412 `item`.`resource-id`,
413 `item`.`tag`,
414 `item`.`attach`,
415 `item`.`inform`,
416 `item`.`file`,
417 `item`.`pubmail`,
418 `item`.`moderated`,
419 `item`.`visible`,
420 `item`.`spam`,
421 `item`.`starred`,
422 `item`.`bookmark`,
423 `item`.`unseen`,
424 `item`.`deleted`,
425 `item`.`origin`,
426 `item`.`forum_mode`,
427 `item`.`last-child`,
428 `item`.`mention`,
429 `item`.`global`,
430 `item`.`gcontact-id`,
431 `item`.`shadow`,
432 */
433
434         $fieldlist = "`item`.`author-link`, `item`.`verb`, `item`.`id`, `item`.`parent`,
435                         `item`.`uid`, `item`.`author-name`, `item`.`location`, `item`.`coord`,
436                         `item`.`title`, `item`.`uri`, `item`.`created`, `item`.`app`, `item`.`guid`,
437                         `item`.`contact-id`, `item`.`thr-parent`, `item`.`parent-uri`, `item`.`rendered-hash`,
438                         `item`.`body`, `item`.`rendered-html`, `item`.`private`, `item`.`edited`,
439                         `item`.`allow_cid`, `item`.`allow_gid`, `item`.`deny_cid`, `item`.`deny_gid`,
440                         `item`.`event-id`, `item`.`object-type`, `item`.`starred`, `item`.`created`,
441                         `item`.`postopts`, `item`.`owner-link`, `item`.`owner-name`, `item`.`owner-avatar`,
442                         `item`.`plink`, `item`.`wall`, `item`.`commented`,
443                         `item`.`id` AS `item_id`, `item`.`network` AS `item_network`";
444
445         return $fieldlist;
446 }
447
448 /**
449  * @brief SQL condition for items
450  */
451 function item_condition() {
452
453         $condition = "`item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`";
454
455         return $condition;
456 }
457
458 /**
459  * "Render" a conversation or list of items for HTML display.
460  * There are two major forms of display:
461  *      - Sequential or unthreaded ("New Item View" or search results)
462  *      - conversation view
463  * The $mode parameter decides between the various renderings and also
464  * figures out how to determine page owner and other contextual items
465  * that are based on unique features of the calling module.
466  *
467  */
468
469 if(!function_exists('conversation')) {
470 function conversation(&$a, $items, $mode, $update, $preview = false) {
471
472         require_once('include/bbcode.php');
473         require_once('include/Contact.php');
474         require_once('mod/proxy.php');
475
476         $ssl_state = ((local_user()) ? true : false);
477
478         $profile_owner = 0;
479         $page_writeable = false;
480         $live_update_div = '';
481
482         $arr_blocked = null;
483
484         if(local_user()) {
485                 $str_blocked = get_pconfig(local_user(),'system','blocked');
486                 if($str_blocked) {
487                         $arr_blocked = explode(',',$str_blocked);
488                         for($x = 0; $x < count($arr_blocked); $x ++)
489                                 $arr_blocked[$x] = trim($arr_blocked[$x]);
490                 }
491
492         }
493
494         $previewing = (($preview) ? ' preview ' : '');
495
496         if($mode === 'network') {
497                 $profile_owner = local_user();
498                 $page_writeable = true;
499                 if(!$update) {
500                         // The special div is needed for liveUpdate to kick in for this page.
501                         // We only launch liveUpdate if you aren't filtering in some incompatible
502                         // way and also you aren't writing a comment (discovered in javascript).
503
504                         $live_update_div = '<div id="live-network"></div>' . "\r\n"
505                                 . "<script> var profile_uid = " . $_SESSION['uid']
506                                 . "; var netargs = '" . substr($a->cmd,8)
507                                 . '?f='
508                                 . ((x($_GET,'cid'))    ? '&cid='    . $_GET['cid']    : '')
509                                 . ((x($_GET,'search')) ? '&search=' . $_GET['search'] : '')
510                                 . ((x($_GET,'star'))   ? '&star='   . $_GET['star']   : '')
511                                 . ((x($_GET,'order'))  ? '&order='  . $_GET['order']  : '')
512                                 . ((x($_GET,'bmark'))  ? '&bmark='  . $_GET['bmark']  : '')
513                                 . ((x($_GET,'liked'))  ? '&liked='  . $_GET['liked']  : '')
514                                 . ((x($_GET,'conv'))   ? '&conv='   . $_GET['conv']   : '')
515                                 . ((x($_GET,'spam'))   ? '&spam='   . $_GET['spam']   : '')
516                                 . ((x($_GET,'nets'))   ? '&nets='   . $_GET['nets']   : '')
517                                 . ((x($_GET,'cmin'))   ? '&cmin='   . $_GET['cmin']   : '')
518                                 . ((x($_GET,'cmax'))   ? '&cmax='   . $_GET['cmax']   : '')
519                                 . ((x($_GET,'file'))   ? '&file='   . $_GET['file']   : '')
520
521                                 . "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
522                 }
523         }
524         else if($mode === 'profile') {
525                 $profile_owner = $a->profile['profile_uid'];
526                 $page_writeable = can_write_wall($a,$profile_owner);
527
528                 if(!$update) {
529                         $tab = notags(trim($_GET['tab']));
530                         $tab = ( $tab ? $tab : 'posts' );
531                         if($tab === 'posts') {
532                                 // This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
533                                 // because browser prefetching might change it on us. We have to deliver it with the page.
534
535                                 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
536                                         . "<script> var profile_uid = " . $a->profile['profile_uid']
537                                         . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
538                         }
539                 }
540         }
541         else if($mode === 'notes') {
542                 $profile_owner = local_user();
543                 $page_writeable = true;
544                 if(!$update) {
545                         $live_update_div = '<div id="live-notes"></div>' . "\r\n"
546                                 . "<script> var profile_uid = " . local_user()
547                                 . "; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
548                 }
549         }
550         else if($mode === 'display') {
551                 $profile_owner = $a->profile['uid'];
552                 $page_writeable = can_write_wall($a,$profile_owner);
553                 if(!$update) {
554                         $live_update_div = '<div id="live-display"></div>' . "\r\n"
555                                 . "<script> var profile_uid = " . $_SESSION['uid'] . ";"
556                                 . " var profile_page = 1; </script>";
557                 }
558         }
559         else if($mode === 'community') {
560                 $profile_owner = 0;
561                 $page_writeable = false;
562                 if(!$update) {
563                         $live_update_div = '<div id="live-community"></div>' . "\r\n"
564                                 . "<script> var profile_uid = -1; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
565                 }
566         }
567         else if($mode === 'search') {
568                 $live_update_div = '<div id="live-search"></div>' . "\r\n";
569         }
570
571         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
572
573
574         if($update)
575                 $return_url = $_SESSION['return_url'];
576         else
577                 $return_url = $_SESSION['return_url'] = $a->query_string;
578
579         $cb = array('items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview);
580         call_hooks('conversation_start',$cb);
581
582         $items = $cb['items'];
583
584         $cmnt_tpl    = get_markup_template('comment_item.tpl');
585         $hide_comments_tpl = get_markup_template('hide_comments.tpl');
586
587         $conv_responses = array(
588                 'like' => array('title' => t('Likes','title')), 'dislike' => array('title' => t('Dislikes','title')),
589                 'attendyes' => array('title' => t('Attending','title')), 'attendno' => array('title' => t('Not attending','title')), 'attendmaybe' => array('title' => t('Might attend','title'))
590         );
591
592         // array with html for each thread (parent+comments)
593         $threads = array();
594         $threadsid = -1;
595
596         $page_template = get_markup_template("conversation.tpl");
597
598         if($items && count($items)) {
599
600                 if($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
601
602                         // "New Item View" on network page or search page results
603                         // - just loop through the items and format them minimally for display
604
605 //                      $tpl = get_markup_template('search_item.tpl');
606                         $tpl = 'search_item.tpl';
607
608                         foreach($items as $item) {
609
610                                 if($arr_blocked) {
611                                         $blocked = false;
612                                         foreach($arr_blocked as $b) {
613                                                 if($b && link_compare($item['author-link'],$b)) {
614                                                         $blocked = true;
615                                                         break;
616                                                 }
617                                         }
618                                         if($blocked)
619                                                 continue;
620                                 }
621
622
623                                 $threadsid++;
624
625                                 $comment     = '';
626                                 $owner_url   = '';
627                                 $owner_photo = '';
628                                 $owner_name  = '';
629                                 $sparkle     = '';
630
631                                 if($mode === 'search' || $mode === 'community') {
632                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE)))
633                                                 && ($item['id'] != $item['parent']))
634                                                 continue;
635                                         $nickname = $item['nickname'];
636                                 }
637                                 else
638                                         $nickname = $a->user['nickname'];
639
640                                 // prevent private email from leaking.
641                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
642                                                 continue;
643
644                                 $profile_name   = ((strlen($item['author-name']))   ? $item['author-name']   : $item['name']);
645                                 if($item['author-link'] && (! $item['author-name']))
646                                         $profile_name = $item['author-link'];
647
648
649
650                                 $tags=array();
651                                 $hashtags = array();
652                                 $mentions = array();
653
654                                 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
655                                                 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
656
657                                 foreach($taglist as $tag) {
658
659                                         if ($tag["url"] == "")
660                                                 $tag["url"] = $searchpath.strtolower($tag["term"]);
661
662                                         if ($tag["type"] == TERM_HASHTAG) {
663                                                 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
664                                                 $prefix = "#";
665                                         } elseif ($tag["type"] == TERM_MENTION) {
666                                                 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
667                                                 $prefix = "@";
668                                         }
669                                         $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
670                                 }
671
672                                 /*foreach(explode(',',$item['tag']) as $tag){
673                                         $tag = trim($tag);
674                                         if ($tag!="") {
675                                                 $t = bbcode($tag);
676                                                 $tags[] = $t;
677                                                 if($t[0] == '#')
678                                                         $hashtags[] = $t;
679                                                 elseif($t[0] == '@')
680                                                         $mentions[] = $t;
681                                         }
682                                 }*/
683
684                                 $sp = false;
685                                 $profile_link = best_link_url($item,$sp);
686                                 if($profile_link === 'mailbox')
687                                         $profile_link = '';
688                                 if($sp)
689                                         $sparkle = ' sparkle';
690                                 else
691                                         $profile_link = zrl($profile_link);
692
693                                 // Don't rely on the author-avatar. It is better to use the data from the contact table
694                                 $author_contact = get_contact_details_by_url($item['author-link'], $profile_owner);
695                                 if ($author_contact["thumb"])
696                                         $profile_avatar = $author_contact["thumb"];
697                                 else
698                                         $profile_avatar = $item['author-avatar'];
699
700                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
701                                 call_hooks('render_location',$locate);
702
703                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
704
705                                 localize_item($item);
706                                 if($mode === 'network-new')
707                                         $dropping = true;
708                                 else
709                                         $dropping = false;
710
711
712                                 $drop = array(
713                                         'dropping' => $dropping,
714                                         'pagedrop' => $page_dropping,
715                                         'select' => t('Select'),
716                                         'delete' => t('Delete'),
717                                 );
718
719                                 $star = false;
720                                 $isstarred = "unstarred";
721
722                                 $lock = false;
723                                 $likebuttons = false;
724                                 $shareable = false;
725
726                                 $body = prepare_body($item,true, $preview);
727
728
729                                 list($categories, $folders) = get_cats_and_terms($item);
730
731                                 if($a->theme['template_engine'] === 'internal') {
732                                         $profile_name_e = template_escape($profile_name);
733                                         $item['title_e'] = template_escape($item['title']);
734                                         $body_e = template_escape($body);
735                                         $tags_e = template_escape($tags);
736                                         $hashtags_e = template_escape($hashtags);
737                                         $mentions_e = template_escape($mentions);
738                                         $location_e = template_escape($location);
739                                         $owner_name_e = template_escape($owner_name);
740                                 }
741                                 else {
742                                         $profile_name_e = $profile_name;
743                                         $item['title_e'] = $item['title'];
744                                         $body_e = $body;
745                                         $tags_e = $tags;
746                                         $hashtags_e = $hashtags;
747                                         $mentions_e = $mentions;
748                                         $location_e = $location;
749                                         $owner_name_e = $owner_name;
750                                 }
751
752                                 if ($item['item_network'] == "")
753                                         $item['item_network'] = $item['network'];
754
755                                 $tmp_item = array(
756                                         'template' => $tpl,
757                                         'id' => (($preview) ? 'P0' : $item['item_id']),
758                                         'network' => $item['item_network'],
759                                         'network_name' => network_to_name($item['item_network'], $profile_link),
760                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
761                                         'profile_url' => $profile_link,
762                                         'item_photo_menu' => item_photo_menu($item),
763                                         'name' => $profile_name_e,
764                                         'sparkle' => $sparkle,
765                                         'lock' => $lock,
766                                         'thumb' => App::remove_baseurl(proxy_url($profile_avatar, false, PROXY_SIZE_THUMB)),
767                                         'title' => $item['title_e'],
768                                         'body' => $body_e,
769                                         'tags' => $tags_e,
770                                         'hashtags' => $hashtags_e,
771                                         'mentions' => $mentions_e,
772                                         'txt_cats' => t('Categories:'),
773                                         'txt_folders' => t('Filed under:'),
774                                         'has_cats' => ((count($categories)) ? 'true' : ''),
775                                         'has_folders' => ((count($folders)) ? 'true' : ''),
776                                         'categories' => $categories,
777                                         'folders' => $folders,
778                                         'text' => strip_tags($body_e),
779                                         'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
780                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
781                                         'location' => $location_e,
782                                         'indent' => '',
783                                         'owner_name' => $owner_name_e,
784                                         'owner_url' => $owner_url,
785                                         'owner_photo' => proxy_url($owner_photo, false, PROXY_SIZE_THUMB),
786                                         'plink' => get_plink($item),
787                                         'edpost' => false,
788                                         'isstarred' => $isstarred,
789                                         'star' => $star,
790                                         'drop' => $drop,
791                                         'vote' => $likebuttons,
792                                         'like' => '',
793                                         'dislike' => '',
794                                         'comment' => '',
795                                         //'conv' => (($preview) ? '' : array('href'=> 'display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
796                                         'conv' => (($preview) ? '' : array('href'=> 'display/'.$item['guid'], 'title'=> t('View in context'))),
797                                         'previewing' => $previewing,
798                                         'wait' => t('Please wait'),
799                                         'thread_level' => 1,
800                                 );
801
802                                 $arr = array('item' => $item, 'output' => $tmp_item);
803                                 call_hooks('display_item', $arr);
804
805                                 $threads[$threadsid]['id'] = $item['item_id'];
806                                 $threads[$threadsid]['network'] = $item['item_network'];
807                                 $threads[$threadsid]['items'] = array($arr['output']);
808
809                         }
810                 }
811                 else
812                 {
813                         // Normal View
814                         $page_template = get_markup_template("threaded_conversation.tpl");
815
816                         require_once('object/Conversation.php');
817                         require_once('object/Item.php');
818
819                         $conv = new Conversation($mode, $preview);
820
821                         // get all the topmost parents
822                         // this shouldn't be needed, as we should have only them in our array
823                         // But for now, this array respects the old style, just in case
824
825                         $threads = array();
826                         foreach($items as $item) {
827
828                                 if($arr_blocked) {
829                                         $blocked = false;
830                                         foreach($arr_blocked as $b) {
831
832                                                 if($b && link_compare($item['author-link'],$b)) {
833                                                         $blocked = true;
834                                                         break;
835                                                 }
836                                         }
837                                         if($blocked)
838                                                 continue;
839                                 }
840
841
842
843                                 // Can we put this after the visibility check?
844                                 builtin_activity_puller($item, $conv_responses);
845
846                                 // Only add what is visible
847                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
848                                         continue;
849                                 }
850                                 if(! visible_activity($item)) {
851                                         continue;
852                                 }
853
854                                 call_hooks('display_item', $arr);
855
856                                 $item['pagedrop'] = $page_dropping;
857
858                                 if($item['id'] == $item['parent']) {
859                                         $item_object = new Item($item);
860                                         $conv->add_thread($item_object);
861                                 }
862                         }
863
864                         $threads = $conv->get_template_data($conv_responses);
865
866                         if(!$threads) {
867                                 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
868                                 $threads = array();
869                         }
870                 }
871         }
872
873         $o = replace_macros($page_template, array(
874                 '$baseurl' => $a->get_baseurl($ssl_state),
875                 '$return_path' => $a->query_string,
876                 '$live_update' => $live_update_div,
877                 '$remove' => t('remove'),
878                 '$mode' => $mode,
879                 '$user' => $a->user,
880                 '$threads' => $threads,
881                 '$dropping' => ($page_dropping && feature_enabled(local_user(),'multi_delete') ? t('Delete Selected Items') : False),
882         ));
883
884         return $o;
885 }}
886
887 function best_link_url($item,&$sparkle,$ssl_state = false) {
888
889         $a = get_app();
890
891         $best_url = '';
892         $sparkle  = false;
893
894         $clean_url = normalise_link($item['author-link']);
895
896         if (local_user()) {
897                 $r = q("SELECT `id` FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` = '%s' LIMIT 1",
898                         dbesc(NETWORK_DFRN), intval(local_user()), dbesc(normalise_link($clean_url)));
899                 if ($r) {
900                         $best_url = 'redir/'.$r[0]['id'];
901                         $sparkle = true;
902                 }
903         }
904         if(! $best_url) {
905                 if(strlen($item['author-link']))
906                         $best_url = $item['author-link'];
907                 else
908                         $best_url = $item['url'];
909         }
910
911         return $best_url;
912 }
913
914
915 if(! function_exists('item_photo_menu')){
916 function item_photo_menu($item){
917         $a = get_app();
918
919         $ssl_state = false;
920
921         if(local_user())
922                 $ssl_state = true;
923
924         $sub_link="";
925         $poke_link="";
926         $contact_url="";
927         $pm_url="";
928         $status_link="";
929         $photos_link="";
930         $posts_link="";
931         $network = "";
932
933         if((local_user()) && local_user() == $item['uid'] && $item['parent'] == $item['id'] && (! $item['self'])) {
934                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
935         }
936
937         $sparkle = false;
938         $profile_link = best_link_url($item,$sparkle,$ssl_state);
939         if($profile_link === 'mailbox')
940                 $profile_link = '';
941
942         $cid = 0;
943         $network = "";
944         $rel = 0;
945         $r = q("SELECT `id`, `network`, `rel` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' LIMIT 1",
946                 intval(local_user()), dbesc(normalise_link($item['author-link'])));
947         if ($r) {
948                 $cid = $r[0]["id"];
949                 $network = $r[0]["network"];
950                 $rel = $r[0]["rel"];
951         }
952
953         if($sparkle) {
954                 $status_link = $profile_link."?url=status";
955                 $photos_link = $profile_link."?url=photos";
956                 $profile_link = $profile_link."?url=profile";
957                 $zurl = '';
958         } else
959                 $profile_link = zrl($profile_link);
960
961         if($cid && !$item['self']) {
962                 $poke_link = 'poke/?f=&c='.$cid;
963                 $contact_url = 'contacts/'.$cid;
964                 $posts_link = 'contacts/'.$cid.'/posts';
965
966                 if (in_array($network, array(NETWORK_DFRN, NETWORK_DIASPORA)))
967                         $pm_url = 'message/new/'.$cid;
968         }
969
970         if (local_user()) {
971                 $menu = Array(
972                         t("Follow Thread") => $sub_link,
973                         t("View Status") => $status_link,
974                         t("View Profile") => $profile_link,
975                         t("View Photos") => $photos_link,
976                         t("Network Posts") => $posts_link,
977                         t("Edit Contact") => $contact_url,
978                         t("Send PM") => $pm_url
979                 );
980
981                 if ($network == NETWORK_DFRN)
982                         $menu[t("Poke")] = $poke_link;
983
984                 if ((($cid == 0) OR ($rel == CONTACT_IS_FOLLOWER)) AND
985                         in_array($item['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
986                         $menu[t("Connect/Follow")] = "follow?url=".urlencode($item['author-link']);
987         } else
988                 $menu = array(t("View Profile") => $item['author-link']);
989
990         $args = array('item' => $item, 'menu' => $menu);
991
992         call_hooks('item_photo_menu', $args);
993
994         $menu = $args['menu'];
995
996         $o = "";
997         foreach($menu as $k=>$v){
998                 if(strpos($v,'javascript:') === 0) {
999                         $v = substr($v,11);
1000                         $o .= "<li role=\"menuitem\"><a onclick=\"$v\">$k</a></li>\n";
1001                 }
1002                 elseif ($v!="") $o .= "<li role=\"menuitem\"><a href=\"$v\">$k</a></li>\n";
1003         }
1004         return $o;
1005 }}
1006
1007 /**
1008  * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
1009  * Increments the count of each matching activity and adds a link to the author as needed.
1010  *
1011  * @param array $item
1012  * @param array &$conv_responses (already created with builtin activity structure)
1013  * @return void
1014  */
1015 if(! function_exists('builtin_activity_puller')) {
1016 function builtin_activity_puller($item, &$conv_responses) {
1017         foreach($conv_responses as $mode => $v) {
1018                 $url = '';
1019                 $sparkle = '';
1020
1021                 switch($mode) {
1022                         case 'like':
1023                                 $verb = ACTIVITY_LIKE;
1024                                 break;
1025                         case 'dislike':
1026                                 $verb = ACTIVITY_DISLIKE;
1027                                 break;
1028                         case 'attendyes':
1029                                 $verb = ACTIVITY_ATTEND;
1030                                 break;
1031                         case 'attendno':
1032                                 $verb = ACTIVITY_ATTENDNO;
1033                                 break;
1034                         case 'attendmaybe':
1035                                 $verb = ACTIVITY_ATTENDMAYBE;
1036                                 break;
1037                         default:
1038                                 return;
1039                                 break;
1040                 }
1041
1042                 if((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) {
1043                         $url = $item['author-link'];
1044                         if((local_user()) && (local_user() == $item['uid']) && ($item['network'] === NETWORK_DFRN) && (! $item['self']) && (link_compare($item['author-link'],$item['url']))) {
1045                                 $url = 'redir/' . $item['contact-id'];
1046                                 $sparkle = ' class="sparkle" ';
1047                         }
1048                         else
1049                                 $url = zrl($url);
1050
1051                         $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
1052
1053                         if(! $item['thr-parent'])
1054                                 $item['thr-parent'] = $item['parent-uri'];
1055
1056                         if(! ((isset($conv_responses[$mode][$item['thr-parent'] . '-l']))
1057                                 && (is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))))
1058                                 $conv_responses[$mode][$item['thr-parent'] . '-l'] = array();
1059
1060                         // only list each unique author once
1061                         if(in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l']))
1062                                 continue;
1063
1064                         if(! isset($conv_responses[$mode][$item['thr-parent']]))
1065                                 $conv_responses[$mode][$item['thr-parent']] = 1;
1066                         else
1067                                 $conv_responses[$mode][$item['thr-parent']] ++;
1068
1069                         $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
1070
1071                         // there can only be one activity verb per item so if we found anything, we can stop looking
1072                         return;
1073                 }
1074         }
1075 }}
1076
1077 // Format the vote text for a profile item
1078 // $cnt = number of people who vote the item
1079 // $arr = array of pre-linked names of likers/dislikers
1080 // $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1081 // $id  = item id
1082 // returns formatted text
1083
1084 if(! function_exists('format_like')) {
1085 function format_like($cnt,$arr,$type,$id) {
1086         $o = '';
1087         $expanded = '';
1088
1089         if($cnt == 1) {
1090                 $likers = $arr[0];
1091
1092                 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1093                 // list which show all likers
1094                 switch($type) {
1095                         case 'like' :
1096                                 $phrase = sprintf( t('%s likes this.'), $likers);
1097                                 break;
1098                         case 'dislike' :
1099                                 $phrase = sprintf( t('%s doesn\'t like this.'), $likers);
1100                                 break;
1101                         case 'attendyes' :
1102                                 $phrase = sprintf( t('%s attends.'), $likers);
1103                                 break;
1104                         case 'attendno' :
1105                                 $phrase = sprintf( t('%s doesn\'t attend.'), $likers);
1106                                 break;
1107                         case 'attendmaybe' :
1108                                 $phrase = sprintf( t('%s attends maybe.'), $likers);
1109                                 break;
1110                 }
1111         }
1112
1113         if($cnt > 1) {
1114                 $total = count($arr);
1115                 if($total >= MAX_LIKERS)
1116                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1117                 if($total < MAX_LIKERS) {
1118                         $last = t('and') . ' ' . $arr[count($arr)-1];
1119                         $arr2 = array_slice($arr, 0, -1);
1120                         $str = implode(', ', $arr2) . ' ' . $last;
1121                 }
1122                 if($total >= MAX_LIKERS) {
1123                         $str = implode(', ', $arr);
1124                         $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
1125                 }
1126
1127                 $likers = $str;
1128
1129                 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1130
1131                 switch($type) {
1132                         case 'like':
1133                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> like this'), $spanatts, $cnt);
1134                                 $explikers = sprintf( t('%s like this.'), $likers);
1135                                 break;
1136                         case 'dislike':
1137                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> don\'t like this'), $spanatts, $cnt);
1138                                 $explikers = sprintf( t('%s don\'t like this.'), $likers);
1139                                 break;
1140                         case 'attendyes':
1141                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> attend'), $spanatts, $cnt);
1142                                 $explikers = sprintf( t('%s attend.'), $likers);
1143                                 break;
1144                         case 'attendno':
1145                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> don\'t attend'), $spanatts, $cnt);
1146                                 $explikers = sprintf( t('%s don\'t attend.'), $likers);
1147                                 break;
1148                         case 'attendmaybe':
1149                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> anttend maybe'), $spanatts, $cnt);
1150                                 $explikers = sprintf( t('%s anttend maybe.'), $likers);
1151                                 break;
1152                 }
1153
1154                 $expanded .= "\t" . '<div class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</div>';
1155         }
1156
1157         $phrase .= EOL ;
1158         $o .= replace_macros(get_markup_template('voting_fakelink.tpl'), array(
1159                 '$phrase' => $phrase,
1160                 '$type' => $type,
1161                 '$id' => $id
1162         ));
1163         $o .= $expanded;
1164
1165         return $o;
1166 }}
1167
1168
1169 function status_editor($a,$x, $notes_cid = 0, $popup=false) {
1170
1171         $o = '';
1172
1173         $geotag = (($x['allow_location']) ? replace_macros(get_markup_template('jot_geotag.tpl'), array()) : '');
1174
1175 /*      $plaintext = false;
1176         if( local_user() && (intval(get_pconfig(local_user(),'system','plaintext')) || !feature_enabled(local_user(),'richtext')) )
1177                 $plaintext = true;*/
1178         $plaintext = true;
1179         if( local_user() && feature_enabled(local_user(),'richtext') )
1180                 $plaintext = false;
1181
1182         $tpl = get_markup_template('jot-header.tpl');
1183         $a->page['htmlhead'] .= replace_macros($tpl, array(
1184                 '$newpost' => 'true',
1185                 '$baseurl' => $a->get_baseurl(true),
1186                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
1187                 '$geotag' => $geotag,
1188                 '$nickname' => $x['nickname'],
1189                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1190                 '$linkurl' => t('Please enter a link URL:'),
1191                 '$vidurl' => t("Please enter a video link/URL:"),
1192                 '$audurl' => t("Please enter an audio link/URL:"),
1193                 '$term' => t('Tag term:'),
1194                 '$fileas' => t('Save to Folder:'),
1195                 '$whereareu' => t('Where are you right now?'),
1196                 '$delitems' => t('Delete item(s)?')
1197         ));
1198
1199
1200         $tpl = get_markup_template('jot-end.tpl');
1201         $a->page['end'] .= replace_macros($tpl, array(
1202                 '$newpost' => 'true',
1203                 '$baseurl' => $a->get_baseurl(true),
1204                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
1205                 '$geotag' => $geotag,
1206                 '$nickname' => $x['nickname'],
1207                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1208                 '$linkurl' => t('Please enter a link URL:'),
1209                 '$vidurl' => t("Please enter a video link/URL:"),
1210                 '$audurl' => t("Please enter an audio link/URL:"),
1211                 '$term' => t('Tag term:'),
1212                 '$fileas' => t('Save to Folder:'),
1213                 '$whereareu' => t('Where are you right now?')
1214         ));
1215
1216         $jotplugins = '';
1217         call_hooks('jot_tool', $jotplugins);
1218
1219         // Private/public post links for the non-JS ACL form
1220         $private_post = 1;
1221         if($_REQUEST['public'])
1222                 $private_post = 0;
1223
1224         $query_str = $a->query_string;
1225         if(strpos($query_str, 'public=1') !== false)
1226                 $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
1227
1228         // I think $a->query_string may never have ? in it, but I could be wrong
1229         // It looks like it's from the index.php?q=[etc] rewrite that the web
1230         // server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1231         if(strpos($query_str, '?') === false)
1232                 $public_post_link = '?public=1';
1233         else
1234                 $public_post_link = '&public=1';
1235
1236
1237
1238 //      $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
1239         $tpl = get_markup_template("jot.tpl");
1240
1241         $o .= replace_macros($tpl,array(
1242                 '$return_path' => $query_str,
1243                 '$action' =>  'item',
1244                 '$share' => (x($x,'button') ? $x['button'] : t('Share')),
1245                 '$upload' => t('Upload photo'),
1246                 '$shortupload' => t('upload photo'),
1247                 '$attach' => t('Attach file'),
1248                 '$shortattach' => t('attach file'),
1249                 '$weblink' => t('Insert web link'),
1250                 '$shortweblink' => t('web link'),
1251                 '$video' => t('Insert video link'),
1252                 '$shortvideo' => t('video link'),
1253                 '$audio' => t('Insert audio link'),
1254                 '$shortaudio' => t('audio link'),
1255                 '$setloc' => t('Set your location'),
1256                 '$shortsetloc' => t('set location'),
1257                 '$noloc' => t('Clear browser location'),
1258                 '$shortnoloc' => t('clear location'),
1259                 '$title' => $x['title'],
1260                 '$placeholdertitle' => t('Set title'),
1261                 '$category' => $x['category'],
1262                 '$placeholdercategory' => (feature_enabled(local_user(),'categories') ? t('Categories (comma-separated list)') : ''),
1263                 '$wait' => t('Please wait'),
1264                 '$permset' => t('Permission settings'),
1265                 '$shortpermset' => t('permissions'),
1266                 '$ptyp' => (($notes_cid) ? 'note' : 'wall'),
1267                 '$content' => $x['content'],
1268                 '$post_id' => $x['post_id'],
1269                 '$baseurl' => $a->get_baseurl(true),
1270                 '$defloc' => $x['default_location'],
1271                 '$visitor' => $x['visitor'],
1272                 '$pvisit' => (($notes_cid) ? 'none' : $x['visitor']),
1273                 '$public' => t('Public post'),
1274                 '$jotnets' => $jotnets,
1275                 '$lockstate' => $x['lockstate'],
1276                 '$bang' => $x['bang'],
1277                 '$profile_uid' => $x['profile_uid'],
1278                 '$preview' => ((feature_enabled($x['profile_uid'],'preview')) ? t('Preview') : ''),
1279                 '$jotplugins' => $jotplugins,
1280                 '$notes_cid' => $notes_cid,
1281                 '$sourceapp' => t($a->sourcename),
1282                 '$cancel' => t('Cancel'),
1283                 '$rand_num' => random_digits(12),
1284
1285                 // ACL permissions box
1286                 '$acl' => $x['acl'],
1287                 '$acl_data' => $x['acl_data'],
1288                 '$group_perms' => t('Post to Groups'),
1289                 '$contact_perms' => t('Post to Contacts'),
1290                 '$private' => t('Private post'),
1291                 '$is_private' => $private_post,
1292                 '$public_link' => $public_post_link,
1293         ));
1294
1295
1296         if ($popup==true){
1297                 $o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
1298
1299         }
1300
1301         return $o;
1302 }
1303
1304
1305 function get_item_children($arr, $parent) {
1306         $children = array();
1307         $a = get_app();
1308         foreach($arr as $item) {
1309                 if($item['id'] != $item['parent']) {
1310                         if(get_config('system','thread_allow') && $a->theme_thread_allow) {
1311                                 // Fallback to parent-uri if thr-parent is not set
1312                                 $thr_parent = $item['thr-parent'];
1313                                 if($thr_parent == '')
1314                                         $thr_parent = $item['parent-uri'];
1315
1316                                 if($thr_parent == $parent['uri']) {
1317                                         $item['children'] = get_item_children($arr, $item);
1318                                         $children[] = $item;
1319                                 }
1320                         }
1321                         else if($item['parent'] == $parent['id']) {
1322                                 $children[] = $item;
1323                         }
1324                 }
1325         }
1326         return $children;
1327 }
1328
1329 function sort_item_children($items) {
1330         $result = $items;
1331         usort($result,'sort_thr_created_rev');
1332         foreach($result as $k => $i) {
1333                 if(count($result[$k]['children'])) {
1334                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1335                 }
1336         }
1337         return $result;
1338 }
1339
1340 function add_children_to_list($children, &$arr) {
1341         foreach($children as $y) {
1342                 $arr[] = $y;
1343                 if(count($y['children']))
1344                         add_children_to_list($y['children'], $arr);
1345         }
1346 }
1347
1348 function conv_sort($arr,$order) {
1349
1350         if((!(is_array($arr) && count($arr))))
1351                 return array();
1352
1353         $parents = array();
1354         $children = array();
1355         $newarr = array();
1356
1357         // This is a preparation for having two different items with the same uri in one thread
1358         // This will otherwise lead to an endless loop.
1359         foreach($arr as $x)
1360                 if (!isset($newarr[$x['uri']]))
1361                         $newarr[$x['uri']] = $x;
1362
1363         $arr = $newarr;
1364
1365         foreach($arr as $x)
1366                 if($x['id'] == $x['parent'])
1367                                 $parents[] = $x;
1368
1369         if(stristr($order,'created'))
1370                 usort($parents,'sort_thr_created');
1371         elseif(stristr($order,'commented'))
1372                 usort($parents,'sort_thr_commented');
1373
1374         if(count($parents))
1375                 foreach($parents as $i=>$_x)
1376                         $parents[$i]['children'] = get_item_children($arr, $_x);
1377
1378         /*foreach($arr as $x) {
1379                 if($x['id'] != $x['parent']) {
1380                         $p = find_thread_parent_index($parents,$x);
1381                         if($p !== false)
1382                                 $parents[$p]['children'][] = $x;
1383                 }
1384         }*/
1385         if(count($parents)) {
1386                 foreach($parents as $k => $v) {
1387                         if(count($parents[$k]['children'])) {
1388                                 $parents[$k]['children'] = sort_item_children($parents[$k]['children']);
1389                                 /*$y = $parents[$k]['children'];
1390                                 usort($y,'sort_thr_created_rev');
1391                                 $parents[$k]['children'] = $y;*/
1392                         }
1393                 }
1394         }
1395
1396         $ret = array();
1397         if(count($parents)) {
1398                 foreach($parents as $x) {
1399                         $ret[] = $x;
1400                         if(count($x['children']))
1401                                 add_children_to_list($x['children'], $ret);
1402                                 /*foreach($x['children'] as $y)
1403                                         $ret[] = $y;*/
1404                 }
1405         }
1406
1407         return $ret;
1408 }
1409
1410
1411 function sort_thr_created($a,$b) {
1412         return strcmp($b['created'],$a['created']);
1413 }
1414
1415 function sort_thr_created_rev($a,$b) {
1416         return strcmp($a['created'],$b['created']);
1417 }
1418
1419 function sort_thr_commented($a,$b) {
1420         return strcmp($b['commented'],$a['commented']);
1421 }
1422
1423 function find_thread_parent_index($arr,$x) {
1424         foreach($arr as $k => $v)
1425                 if($v['id'] == $x['parent'])
1426                         return $k;
1427         return false;
1428 }
1429
1430 function render_location_dummy($item) {
1431         if ($item['location'] != "")
1432                 return $item['location'];
1433
1434         if ($item['coord'] != "")
1435                 return $item['coord'];
1436 }
1437
1438 function get_responses($conv_responses,$response_verbs,$ob,$item) {
1439         $ret = array();
1440         foreach($response_verbs as $v) {
1441                 $ret[$v] = array();
1442                 $ret[$v]['count'] = ((x($conv_responses[$v],$item['uri'])) ? $conv_responses[$v][$item['uri']] : '');
1443                 $ret[$v]['list']  = ((x($conv_responses[$v],$item['uri'])) ? $conv_responses[$v][$item['uri'] . '-l'] : '');
1444                 if(count($ret[$v]['list']) > MAX_LIKERS) {
1445                         $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
1446                         array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
1447                                 . (($ob) ? $ob->get_id() : $item['id']) . '"><b>' . t('View all') . '</b></a>');
1448                 }
1449                 else {
1450                         $ret[$v]['list_part'] = '';
1451                 }
1452                 $ret[$v]['button'] = get_response_button_text($v,$ret[$v]['count']);
1453                 $ret[$v]['title'] = $conv_responses[$v]['title'];
1454         }
1455
1456         $count = 0;
1457         foreach($ret as $key) {
1458                 if ($key['count'] == true)
1459                         $count++;
1460         }
1461         $ret['count'] = $count;
1462
1463         return $ret;
1464 }
1465
1466 function get_response_button_text($v,$count) {
1467         switch($v) {
1468                 case 'like':
1469                         return tt('Like','Likes',$count,'noun');
1470                         break;
1471                 case 'dislike':
1472                         return tt('Dislike','Dislikes',$count,'noun');
1473                         break;
1474                 case 'attendyes':
1475                         return tt('Attending','Attending',$count,'noun');
1476                         break;
1477                 case 'attendno':
1478                         return tt('Not Attending','Not Attending',$count,'noun');
1479                         break;
1480                 case 'attendmaybe':
1481                         return tt('Undecided','Undecided',$count,'noun');
1482                         break;
1483         }
1484 }