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