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