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