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