]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
Merge pull request #1315 from annando/1501-issue-1283
[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) || activity_match($item['verb'],ACTIVITY_DISLIKE)){
104
105                 $r = q("SELECT * from `item`,`contact` WHERE
106                                 `item`.`contact-id`=`contact`.`id` AND `item`.`uri`='%s';",
107                                  dbesc($item['parent-uri']));
108                 if(count($r)==0) return;
109                 $obj=$r[0];
110
111                 $author  = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
112                 $objauthor =  '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]';
113
114                 switch($obj['verb']){
115                         case ACTIVITY_POST:
116                                 switch ($obj['object-type']){
117                                         case ACTIVITY_OBJ_EVENT:
118                                                 $post_type = t('event');
119                                                 break;
120                                         default:
121                                                 $post_type = t('status');
122                                 }
123                                 break;
124                         default:
125                                 if($obj['resource-id']){
126                                         $post_type = t('photo');
127                                         $m=array(); preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
128                                         $rr['plink'] = $m[1];
129                                 } else {
130                                         $post_type = t('status');
131                                 }
132                 }
133
134                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
135
136                 if(activity_match($item['verb'],ACTIVITY_LIKE)) {
137                         $bodyverb = t('%1$s likes %2$s\'s %3$s');
138                 }
139                 elseif(activity_match($item['verb'],ACTIVITY_DISLIKE)) {
140                         $bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s');
141                 }
142                 $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
143
144         }
145         if (activity_match($item['verb'],ACTIVITY_FRIEND)) {
146
147                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
148
149                 $Aname = $item['author-name'];
150                 $Alink = $item['author-link'];
151
152                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
153
154                 $obj = parse_xml_string($xmlhead.$item['object']);
155                 $links = parse_xml_string($xmlhead."<links>".unxmlify($obj->link)."</links>");
156
157                 $Bname = $obj->title;
158                 $Blink = ""; $Bphoto = "";
159                 foreach ($links->link as $l){
160                         $atts = $l->attributes();
161                         switch($atts['rel']){
162                                 case "alternate": $Blink = $atts['href'];
163                                 case "photo": $Bphoto = $atts['href'];
164                         }
165
166                 }
167
168                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
169                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
170                 if ($Bphoto!="") $Bphoto = '[url=' . zrl($Blink) . '][img]' . $Bphoto . '[/img][/url]';
171
172                 $item['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
173
174         }
175         if (stristr($item['verb'],ACTIVITY_POKE)) {
176                 $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
177                 if(! $verb)
178                         return;
179                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
180
181                 $Aname = $item['author-name'];
182                 $Alink = $item['author-link'];
183
184                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
185
186                 $obj = parse_xml_string($xmlhead.$item['object']);
187                 $links = parse_xml_string($xmlhead."<links>".unxmlify($obj->link)."</links>");
188
189                 $Bname = $obj->title;
190                 $Blink = ""; $Bphoto = "";
191                 foreach ($links->link as $l){
192                         $atts = $l->attributes();
193                         switch($atts['rel']){
194                                 case "alternate": $Blink = $atts['href'];
195                                 case "photo": $Bphoto = $atts['href'];
196                         }
197
198                 }
199
200                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
201                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
202                 if ($Bphoto!="") $Bphoto = '[url=' . zrl($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
203
204                 // we can't have a translation string with three positions but no distinguishable text
205                 // So here is the translate string.
206
207                 $txt = t('%1$s poked %2$s');
208
209                 // now translate the verb
210
211                 $txt = str_replace( t('poked'), t($verb), $txt);
212
213                 // then do the sprintf on the translation string
214
215                 $item['body'] = sprintf($txt, $A, $B). "\n\n\n" . $Bphoto;
216
217         }
218         if (stristr($item['verb'],ACTIVITY_MOOD)) {
219                 $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
220                 if(! $verb)
221                         return;
222
223                 $Aname = $item['author-name'];
224                 $Alink = $item['author-link'];
225                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
226
227                 $txt = t('%1$s is currently %2$s');
228
229                 $item['body'] = sprintf($txt, $A, t($verb));
230         }
231
232         if (activity_match($item['verb'],ACTIVITY_TAG)) {
233                 $r = q("SELECT * from `item`,`contact` WHERE
234                 `item`.`contact-id`=`contact`.`id` AND `item`.`uri`='%s';",
235                  dbesc($item['parent-uri']));
236                 if(count($r)==0) return;
237                 $obj=$r[0];
238
239                 $author  = '[url=' . zrl($item['author-link']) . ']' . $item['author-name'] . '[/url]';
240                 $objauthor =  '[url=' . zrl($obj['author-link']) . ']' . $obj['author-name'] . '[/url]';
241
242                 switch($obj['verb']){
243                         case ACTIVITY_POST:
244                                 switch ($obj['object-type']){
245                                         case ACTIVITY_OBJ_EVENT:
246                                                 $post_type = t('event');
247                                                 break;
248                                         default:
249                                                 $post_type = t('status');
250                                 }
251                                 break;
252                         default:
253                                 if($obj['resource-id']){
254                                         $post_type = t('photo');
255                                         $m=array(); preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
256                                         $rr['plink'] = $m[1];
257                                 } else {
258                                         $post_type = t('status');
259                                 }
260                 }
261                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
262
263                 $parsedobj = parse_xml_string($xmlhead.$item['object']);
264
265                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
266                 $item['body'] = sprintf( t('%1$s tagged %2$s\'s %3$s with %4$s'), $author, $objauthor, $plink, $tag );
267
268         }
269         if (activity_match($item['verb'],ACTIVITY_FAVORITE)){
270
271                 if ($item['object-type']== "")
272                         return;
273
274                 $Aname = $item['author-name'];
275                 $Alink = $item['author-link'];
276
277                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
278
279                 $obj = parse_xml_string($xmlhead.$item['object']);
280                 if(strlen($obj->id)) {
281                         $r = q("select * from item where uri = '%s' and uid = %d limit 1",
282                                         dbesc($obj->id),
283                                         intval($item['uid'])
284                         );
285                         if(count($r) && $r[0]['plink']) {
286                                 $target = $r[0];
287                                 $Bname = $target['author-name'];
288                                 $Blink = $target['author-link'];
289                                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
290                                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
291                                 $P = '[url=' . $target['plink'] . ']' . t('post/item') . '[/url]';
292                                 $item['body'] = sprintf( t('%1$s marked %2$s\'s %3$s as favorite'), $A, $B, $P)."\n";
293
294                         }
295                 }
296         }
297         $matches = null;
298         if(preg_match_all('/@\[url=(.*?)\]/is',$item['body'],$matches,PREG_SET_ORDER)) {
299                 foreach($matches as $mtch) {
300                         if(! strpos($mtch[1],'zrl='))
301                                 $item['body'] = str_replace($mtch[0],'@[url=' . zrl($mtch[1]). ']',$item['body']);
302                 }
303         }
304
305         // add zrl's to public images
306         $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
307         if(preg_match($photo_pattern,$item['body'])) {
308                 $photo_replace = '[url=' . zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5'  . '[/img][/url]';
309                 $item['body'] = bb_tag_preg_replace($photo_pattern, $photo_replace, 'url', $item['body']);
310         }
311
312         // add sparkle links to appropriate permalinks
313
314         $x = stristr($item['plink'],'/display/');
315         if($x) {
316                 $sparkle = false;
317                 $y = best_link_url($item,$sparkle,true);
318                 if(strstr($y,'/redir/'))
319                         $item['plink'] = $y . '?f=&url=' . $item['plink'];
320         }
321
322
323
324 }
325
326 /**
327  * Count the total of comments on this item and its desendants
328  */
329 function count_descendants($item) {
330         $total = count($item['children']);
331
332         if($total > 0) {
333                 foreach($item['children'] as $child) {
334                         if(! visible_activity($child))
335                                 $total --;
336                         $total += count_descendants($child);
337                 }
338         }
339
340         return $total;
341 }
342
343 function visible_activity($item) {
344
345         if(activity_match($item['verb'],ACTIVITY_LIKE) || activity_match($item['verb'],ACTIVITY_DISLIKE))
346                 return false;
347
348         if(activity_match($item['verb'],ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE) {
349                 if(! (($item['self']) && ($item['uid'] == local_user()))) {
350                         return false;
351                 }
352         }
353
354         return true;
355 }
356
357
358 /**
359  * "Render" a conversation or list of items for HTML display.
360  * There are two major forms of display:
361  *      - Sequential or unthreaded ("New Item View" or search results)
362  *      - conversation view
363  * The $mode parameter decides between the various renderings and also
364  * figures out how to determine page owner and other contextual items
365  * that are based on unique features of the calling module.
366  *
367  */
368
369 if(!function_exists('conversation')) {
370 function conversation(&$a, $items, $mode, $update, $preview = false) {
371
372         require_once('include/bbcode.php');
373         require_once('mod/proxy.php');
374
375         $ssl_state = ((local_user()) ? true : false);
376
377         $profile_owner = 0;
378         $page_writeable = false;
379         $live_update_div = '';
380
381         $arr_blocked = null;
382
383         if(local_user()) {
384                 $str_blocked = get_pconfig(local_user(),'system','blocked');
385                 if($str_blocked) {
386                         $arr_blocked = explode(',',$str_blocked);
387                         for($x = 0; $x < count($arr_blocked); $x ++)
388                                 $arr_blocked[$x] = trim($arr_blocked[$x]);
389                 }
390
391         }
392
393         $previewing = (($preview) ? ' preview ' : '');
394
395         if($mode === 'network') {
396                 $profile_owner = local_user();
397                 $page_writeable = true;
398                 if(!$update) {
399                         // The special div is needed for liveUpdate to kick in for this page.
400                         // We only launch liveUpdate if you aren't filtering in some incompatible 
401                         // way and also you aren't writing a comment (discovered in javascript).
402
403                         $live_update_div = '<div id="live-network"></div>' . "\r\n"
404                                 . "<script> var profile_uid = " . $_SESSION['uid'] 
405                                 . "; var netargs = '" . substr($a->cmd,8)
406                                 . '?f='
407                                 . ((x($_GET,'cid'))    ? '&cid='    . $_GET['cid']    : '')
408                                 . ((x($_GET,'search')) ? '&search=' . $_GET['search'] : '') 
409                                 . ((x($_GET,'star'))   ? '&star='   . $_GET['star']   : '') 
410                                 . ((x($_GET,'order'))  ? '&order='  . $_GET['order']  : '') 
411                                 . ((x($_GET,'bmark'))  ? '&bmark='  . $_GET['bmark']  : '') 
412                                 . ((x($_GET,'liked'))  ? '&liked='  . $_GET['liked']  : '') 
413                                 . ((x($_GET,'conv'))   ? '&conv='   . $_GET['conv']   : '') 
414                                 . ((x($_GET,'spam'))   ? '&spam='   . $_GET['spam']   : '') 
415                                 . ((x($_GET,'nets'))   ? '&nets='   . $_GET['nets']   : '') 
416                                 . ((x($_GET,'cmin'))   ? '&cmin='   . $_GET['cmin']   : '') 
417                                 . ((x($_GET,'cmax'))   ? '&cmax='   . $_GET['cmax']   : '') 
418                                 . ((x($_GET,'file'))   ? '&file='   . $_GET['file']   : '') 
419
420                                 . "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
421                 }
422         }
423         else if($mode === 'profile') {
424                 $profile_owner = $a->profile['profile_uid'];
425                 $page_writeable = can_write_wall($a,$profile_owner);
426
427                 if(!$update) {
428                         $tab = notags(trim($_GET['tab']));
429                         $tab = ( $tab ? $tab : 'posts' );
430                         if($tab === 'posts') {
431                                 // This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
432                                 // because browser prefetching might change it on us. We have to deliver it with the page.
433
434                                 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
435                                         . "<script> var profile_uid = " . $a->profile['profile_uid'] 
436                                         . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
437                         }
438                 }
439         }
440         else if($mode === 'notes') {
441                 $profile_owner = local_user();
442                 $page_writeable = true;
443                 if(!$update) {
444                         $live_update_div = '<div id="live-notes"></div>' . "\r\n"
445                                 . "<script> var profile_uid = " . local_user() 
446                                 . "; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
447                 }
448         }
449         else if($mode === 'display') {
450                 $profile_owner = $a->profile['uid'];
451                 $page_writeable = can_write_wall($a,$profile_owner);
452                 if(!$update) {
453                         $live_update_div = '<div id="live-display"></div>' . "\r\n"
454                                 . "<script> var profile_uid = " . $_SESSION['uid'] . ";"
455                                 . " var profile_page = 1; </script>";
456                 }
457         }
458         else if($mode === 'community') {
459                 $profile_owner = 0;
460                 $page_writeable = false;
461                 if(!$update) {
462                         $live_update_div = '<div id="live-community"></div>' . "\r\n"
463                                 . "<script> var profile_uid = -1; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
464                 }
465         }
466         else if($mode === 'search') {
467                 $live_update_div = '<div id="live-search"></div>' . "\r\n";
468         }
469
470         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
471
472
473         if($update)
474                 $return_url = $_SESSION['return_url'];
475         else
476                 $return_url = $_SESSION['return_url'] = $a->query_string;
477
478         load_contact_links(local_user());
479
480         $cb = array('items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview);
481         call_hooks('conversation_start',$cb);
482
483         $items = $cb['items'];
484
485         $cmnt_tpl    = get_markup_template('comment_item.tpl');
486         $hide_comments_tpl = get_markup_template('hide_comments.tpl');
487
488         $alike = array();
489         $dlike = array();
490
491         // array with html for each thread (parent+comments)
492         $threads = array();
493         $threadsid = -1;
494
495         $page_template = get_markup_template("conversation.tpl");
496
497         if($items && count($items)) {
498
499                 if($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
500
501                         // "New Item View" on network page or search page results
502                         // - just loop through the items and format them minimally for display
503
504 //                      $tpl = get_markup_template('search_item.tpl');
505                         $tpl = 'search_item.tpl';
506
507                         foreach($items as $item) {
508
509                                 if($arr_blocked) {
510                                         $blocked = false;
511                                         foreach($arr_blocked as $b) {
512                                                 if($b && link_compare($item['author-link'],$b)) {
513                                                         $blocked = true;
514                                                         break;
515                                                 }
516                                         }
517                                         if($blocked)
518                                                 continue;
519                                 }
520
521
522                                 $threadsid++;
523
524                                 $comment     = '';
525                                 $owner_url   = '';
526                                 $owner_photo = '';
527                                 $owner_name  = '';
528                                 $sparkle     = '';
529
530                                 if($mode === 'search' || $mode === 'community') {
531                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE)))
532                                                 && ($item['id'] != $item['parent']))
533                                                 continue;
534                                         $nickname = $item['nickname'];
535                                 }
536                                 else
537                                         $nickname = $a->user['nickname'];
538
539                                 // prevent private email from leaking.
540                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
541                                                 continue;
542
543                                 $profile_name   = ((strlen($item['author-name']))   ? $item['author-name']   : $item['name']);
544                                 if($item['author-link'] && (! $item['author-name']))
545                                         $profile_name = $item['author-link'];
546
547
548
549                                 $tags=array();
550                                 $hashtags = array();
551                                 $mentions = array();
552
553                                 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
554                                                 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
555
556                                 foreach($taglist as $tag) {
557
558                                         if ($tag["url"] == "")
559                                                 $tag["url"] = $searchpath.strtolower($tag["term"]);
560
561                                         if ($tag["type"] == TERM_HASHTAG) {
562                                                 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
563                                                 $prefix = "#";
564                                         } elseif ($tag["type"] == TERM_MENTION) {
565                                                 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
566                                                 $prefix = "@";
567                                         }
568                                         $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
569                                 }
570
571                                 /*foreach(explode(',',$item['tag']) as $tag){
572                                         $tag = trim($tag);
573                                         if ($tag!="") {
574                                                 $t = bbcode($tag);
575                                                 $tags[] = $t;
576                                                 if($t[0] == '#')
577                                                         $hashtags[] = $t;
578                                                 elseif($t[0] == '@')
579                                                         $mentions[] = $t;
580                                         }
581                                 }*/
582
583                                 $sp = false;
584                                 $profile_link = best_link_url($item,$sp);
585                                 if($profile_link === 'mailbox')
586                                         $profile_link = '';
587                                 if($sp)
588                                         $sparkle = ' sparkle';
589                                 else
590                                         $profile_link = zrl($profile_link);
591
592                                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
593                                 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
594                                         $profile_avatar = $a->contacts[$normalised]['thumb'];
595                                 else
596                                         $profile_avatar = ((strlen($item['author-avatar'])) ? $a->get_cached_avatar_image($item['author-avatar']) : $item['thumb']);
597
598                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
599                                 call_hooks('render_location',$locate);
600
601                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
602
603                                 localize_item($item);
604                                 if($mode === 'network-new')
605                                         $dropping = true;
606                                 else
607                                         $dropping = false;
608
609
610                                 $drop = array(
611                                         'dropping' => $dropping,
612                                         'pagedrop' => $page_dropping,
613                                         'select' => t('Select'),
614                                         'delete' => t('Delete'),
615                                 );
616
617                                 $star = false;
618                                 $isstarred = "unstarred";
619
620                                 $lock = false;
621                                 $likebuttons = false;
622                                 $shareable = false;
623
624                                 $body = prepare_body($item,true, $preview);
625
626
627                                 list($categories, $folders) = get_cats_and_terms($item);
628
629                                 if($a->theme['template_engine'] === 'internal') {
630                                         $profile_name_e = template_escape($profile_name);
631                                         $item['title_e'] = template_escape($item['title']);
632                                         $body_e = template_escape($body);
633                                         $tags_e = template_escape($tags);
634                                         $hashtags_e = template_escape($hashtags);
635                                         $mentions_e = template_escape($mentions);
636                                         $location_e = template_escape($location);
637                                         $owner_name_e = template_escape($owner_name);
638                                 }
639                                 else {
640                                         $profile_name_e = $profile_name;
641                                         $item['title_e'] = $item['title'];
642                                         $body_e = $body;
643                                         $tags_e = $tags;
644                                         $hashtags_e = $hashtags;
645                                         $mentions_e = $mentions;
646                                         $location_e = $location;
647                                         $owner_name_e = $owner_name;
648                                 }
649
650                                 $tmp_item = array(
651                                         'template' => $tpl,
652                                         'id' => (($preview) ? 'P0' : $item['item_id']),
653                                         'network' => $item['item_network'],
654                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
655                                         'profile_url' => $profile_link,
656                                         'item_photo_menu' => item_photo_menu($item),
657                                         'name' => $profile_name_e,
658                                         'sparkle' => $sparkle,
659                                         'lock' => $lock,
660                                         'thumb' => proxy_url($profile_avatar),
661                                         'title' => $item['title_e'],
662                                         'body' => $body_e,
663                                         'tags' => $tags_e,
664                                         'hashtags' => $hashtags_e,
665                                         'mentions' => $mentions_e,
666                                         'txt_cats' => t('Categories:'),
667                                         'txt_folders' => t('Filed under:'),
668                                         'has_cats' => ((count($categories)) ? 'true' : ''),
669                                         'has_folders' => ((count($folders)) ? 'true' : ''),
670                                         'categories' => $categories,
671                                         'folders' => $folders,
672                                         'text' => strip_tags($body_e),
673                                         'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
674                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
675                                         'location' => $location_e,
676                                         'indent' => '',
677                                         'owner_name' => $owner_name_e,
678                                         'owner_url' => $owner_url,
679                                         'owner_photo' => proxy_url($owner_photo),
680                                         'plink' => get_plink($item),
681                                         'edpost' => false,
682                                         'isstarred' => $isstarred,
683                                         'star' => $star,
684                                         'drop' => $drop,
685                                         'vote' => $likebuttons,
686                                         'like' => '',
687                                         'dislike' => '',
688                                         'comment' => '',
689                                         //'conv' => (($preview) ? '' : array('href'=> $a->get_baseurl($ssl_state) . '/display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
690                                         'conv' => (($preview) ? '' : array('href'=> $a->get_baseurl($ssl_state) . '/display/'.$item['guid'], 'title'=> t('View in context'))),
691                                         'previewing' => $previewing,
692                                         'wait' => t('Please wait'),
693                                         'thread_level' => 1,
694                                 );
695
696                                 $arr = array('item' => $item, 'output' => $tmp_item);
697                                 call_hooks('display_item', $arr);
698
699                                 $threads[$threadsid]['id'] = $item['item_id'];
700                                 $threads[$threadsid]['network'] = $item['item_network'];
701                                 $threads[$threadsid]['items'] = array($arr['output']);
702
703                         }
704                 }
705                 else
706                 {
707                         // Normal View
708                         $page_template = get_markup_template("threaded_conversation.tpl");
709
710                         require_once('object/Conversation.php');
711                         require_once('object/Item.php');
712
713                         $conv = new Conversation($mode, $preview);
714
715                         // get all the topmost parents
716                         // this shouldn't be needed, as we should have only them in our array
717                         // But for now, this array respects the old style, just in case
718
719                         $threads = array();
720                         foreach($items as $item) {
721
722                                 if($arr_blocked) {
723                                         $blocked = false;
724                                         foreach($arr_blocked as $b) {
725
726                                                 if($b && link_compare($item['author-link'],$b)) {
727                                                         $blocked = true;
728                                                         break;
729                                                 }
730                                         }
731                                         if($blocked)
732                                                 continue;
733                                 }
734
735
736
737                                 // Can we put this after the visibility check?
738                                 like_puller($a,$item,$alike,'like');
739                                 like_puller($a,$item,$dlike,'dislike');
740
741                                 // Only add what is visible
742                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
743                                         continue;
744                                 }
745                                 if(! visible_activity($item)) {
746                                         continue;
747                                 }
748
749                                 call_hooks('display_item', $arr);
750
751                                 $item['pagedrop'] = $page_dropping;
752
753                                 if($item['id'] == $item['parent']) {
754                                         $item_object = new Item($item);
755                                         $conv->add_thread($item_object);
756                                 }
757                         }
758
759                         $threads = $conv->get_template_data($alike, $dlike);
760
761                         if(!$threads) {
762                                 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
763                                 $threads = array();
764                         }
765                 }
766         }
767
768         $o = replace_macros($page_template, array(
769                 '$baseurl' => $a->get_baseurl($ssl_state),
770                 '$return_path' => $a->query_string,
771                 '$live_update' => $live_update_div,
772                 '$remove' => t('remove'),
773                 '$mode' => $mode,
774                 '$user' => $a->user,
775                 '$threads' => $threads,
776                 '$dropping' => ($page_dropping && feature_enabled(local_user(),'multi_delete') ? t('Delete Selected Items') : False),
777         ));
778
779         return $o;
780 }}
781
782 function best_link_url($item,&$sparkle,$ssl_state = false) {
783
784         $a = get_app();
785
786         $best_url = '';
787         $sparkle  = false;
788
789         $clean_url = normalise_link($item['author-link']);
790
791         if((local_user()) && (local_user() == $item['uid'])) {
792                 if(isset($a->contacts) && x($a->contacts,$clean_url)) {
793                         if($a->contacts[$clean_url]['network'] === NETWORK_DFRN) {
794                                 $best_url = $a->get_baseurl($ssl_state) . '/redir/' . $a->contacts[$clean_url]['id'];
795                                 $sparkle = true;
796                         }
797                         else
798                                 $best_url = $a->contacts[$clean_url]['url'];
799                 }
800         }
801         if(! $best_url) {
802                 if(strlen($item['author-link']))
803                         $best_url = $item['author-link'];
804                 else
805                         $best_url = $item['url'];
806         }
807
808         return $best_url;
809 }
810
811
812 if(! function_exists('item_photo_menu')){
813 function item_photo_menu($item){
814         $a = get_app();
815
816         $ssl_state = false;
817
818         if(local_user()) {
819                 $ssl_state = true;
820                  if(! count($a->contacts))
821                         load_contact_links(local_user());
822         }
823         $sub_link="";
824         $poke_link="";
825         $contact_url="";
826         $pm_url="";
827         $status_link="";
828         $photos_link="";
829         $posts_link="";
830
831         if((local_user()) && local_user() == $item['uid'] && $item['parent'] == $item['id'] && (! $item['self'])) {
832                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
833         }
834
835         $sparkle = false;
836         $profile_link = best_link_url($item,$sparkle,$ssl_state);
837         if($profile_link === 'mailbox')
838                 $profile_link = '';
839
840         if($sparkle) {
841                 $cid = intval(basename($profile_link));
842                 $status_link = $profile_link . "?url=status";
843                 $photos_link = $profile_link . "?url=photos";
844                 $profile_link = $profile_link . "?url=profile";
845                 $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
846                 $zurl = '';
847         }
848         else {
849                 $profile_link = zrl($profile_link);
850                 if(local_user() && local_user() == $item['uid'] && link_compare($item['url'],$item['author-link'])) {
851                         $cid = $item['contact-id'];
852                 }
853                 else {
854                         $cid = 0;
855                 }
856         }
857         if(($cid) && (! $item['self'])) {
858                 $poke_link = $a->get_baseurl($ssl_state) . '/poke/?f=&c=' . $cid;
859                 $contact_url = $a->get_baseurl($ssl_state) . '/contacts/' . $cid;
860                 $posts_link = $a->get_baseurl($ssl_state) . '/network/0?nets=all&cid=' . $cid;
861
862                 $clean_url = normalise_link($item['author-link']);
863
864                 if((local_user()) && (local_user() == $item['uid'])) {
865                         if(isset($a->contacts) && x($a->contacts,$clean_url)) {
866                                 if($a->contacts[$clean_url]['network'] === NETWORK_DIASPORA) {
867                                         $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
868                                 }
869                         }
870                 }
871
872         }
873
874         $menu = Array(
875                 t("Follow Thread") => $sub_link,
876                 t("View Status") => $status_link,
877                 t("View Profile") => $profile_link,
878                 t("View Photos") => $photos_link,
879                 t("Network Posts") => $posts_link,
880                 t("Edit Contact") => $contact_url,
881                 t("Send PM") => $pm_url,
882                 t("Poke") => $poke_link
883         );
884
885
886         $args = array('item' => $item, 'menu' => $menu);
887
888         call_hooks('item_photo_menu', $args);
889
890         $menu = $args['menu'];
891
892         $o = "";
893         foreach($menu as $k=>$v){
894                 if(strpos($v,'javascript:') === 0) {
895                         $v = substr($v,11);
896                         $o .= "<li><a href=\"#\" onclick=\"$v\">$k</a></li>\n";
897                 }
898                 elseif ($v!="") $o .= "<li><a href=\"$v\">$k</a></li>\n";
899         }
900         return $o;
901 }}
902
903 if(! function_exists('like_puller')) {
904 function like_puller($a,$item,&$arr,$mode) {
905
906         $url = '';
907         $sparkle = '';
908         $verb = (($mode === 'like') ? ACTIVITY_LIKE : ACTIVITY_DISLIKE);
909
910         if((activity_match($item['verb'],$verb)) && ($item['id'] != $item['parent'])) {
911                 $url = $item['author-link'];
912                 if((local_user()) && (local_user() == $item['uid']) && ($item['network'] === 'dfrn') && (! $item['self']) && (link_compare($item['author-link'],$item['url']))) {
913                         $url = $a->get_baseurl(true) . '/redir/' . $item['contact-id'];
914                         $sparkle = ' class="sparkle" ';
915                 }
916                 else
917                         $url = zrl($url);
918
919                 if(! $item['thr-parent'])
920                         $item['thr-parent'] = $item['parent-uri'];
921
922                 if(! ((isset($arr[$item['thr-parent'] . '-l'])) && (is_array($arr[$item['thr-parent'] . '-l']))))
923                         $arr[$item['thr-parent'] . '-l'] = array();
924                 if(! isset($arr[$item['thr-parent']]))
925                         $arr[$item['thr-parent']] = 1;
926                 else
927                         $arr[$item['thr-parent']] ++;
928                 $arr[$item['thr-parent'] . '-l'][] = '<a href="'. $url . '"'. $sparkle .'>' . $item['author-name'] . '</a>';
929         }
930         return;
931 }}
932
933 // Format the like/dislike text for a profile item
934 // $cnt = number of people who like/dislike the item
935 // $arr = array of pre-linked names of likers/dislikers
936 // $type = one of 'like, 'dislike'
937 // $id  = item id
938 // returns formatted text
939
940 if(! function_exists('format_like')) {
941 function format_like($cnt,$arr,$type,$id) {
942         $o = '';
943         if($cnt == 1)
944                 $o .= (($type === 'like') ? sprintf( t('%s likes this.'), $arr[0]) : sprintf( t('%s doesn\'t like this.'), $arr[0])) . EOL ;
945         else {
946                 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
947                 switch($type) {
948                         case 'like':
949                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> like this'), $spanatts, $cnt);
950                                 break;
951                         case 'dislike':
952                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> don\'t like this'), $spanatts, $cnt);
953                                 break;
954                 }
955                 $phrase .= EOL ;
956                 $o .= replace_macros(get_markup_template('voting_fakelink.tpl'), array(
957                         '$phrase' => $phrase,
958                         '$type' => $type,
959                         '$id' => $id
960                 ));
961
962                 $total = count($arr);
963                 if($total >= MAX_LIKERS)
964                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
965                 if($total < MAX_LIKERS) {
966                         $last = t('and') . ' ' . $arr[count($arr)-1];
967                         $arr2 = array_slice($arr, 0, -1);
968                         $str = implode(', ', $arr2) . ' ' . $last;
969                 }
970                 if($total >= MAX_LIKERS) {
971                         $str = implode(', ', $arr);
972                         $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
973                 }
974                 $str = (($type === 'like') ? sprintf( t('%s like this.'), $str) : sprintf( t('%s don\'t like this.'), $str));
975                 $o .= "\t" . '<div class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
976         }
977         return $o;
978 }}
979
980
981 function status_editor($a,$x, $notes_cid = 0, $popup=false) {
982
983         $o = '';
984
985         $geotag = (($x['allow_location']) ? replace_macros(get_markup_template('jot_geotag.tpl'), array()) : '');
986
987 /*      $plaintext = false;
988         if( local_user() && (intval(get_pconfig(local_user(),'system','plaintext')) || !feature_enabled(local_user(),'richtext')) )
989                 $plaintext = true;*/
990         $plaintext = true;
991         if( local_user() && feature_enabled(local_user(),'richtext') )
992                 $plaintext = false;
993
994         $tpl = get_markup_template('jot-header.tpl');
995         $a->page['htmlhead'] .= replace_macros($tpl, array(
996                 '$newpost' => 'true',
997                 '$baseurl' => $a->get_baseurl(true),
998                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
999                 '$geotag' => $geotag,
1000                 '$nickname' => $x['nickname'],
1001                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1002                 '$linkurl' => t('Please enter a link URL:'),
1003                 '$vidurl' => t("Please enter a video link/URL:"),
1004                 '$audurl' => t("Please enter an audio link/URL:"),
1005                 '$term' => t('Tag term:'),
1006                 '$fileas' => t('Save to Folder:'),
1007                 '$whereareu' => t('Where are you right now?'),
1008                 '$delitems' => t('Delete item(s)?')
1009         ));
1010
1011
1012         $tpl = get_markup_template('jot-end.tpl');
1013         $a->page['end'] .= replace_macros($tpl, array(
1014                 '$newpost' => 'true',
1015                 '$baseurl' => $a->get_baseurl(true),
1016                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
1017                 '$geotag' => $geotag,
1018                 '$nickname' => $x['nickname'],
1019                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1020                 '$linkurl' => t('Please enter a link URL:'),
1021                 '$vidurl' => t("Please enter a video link/URL:"),
1022                 '$audurl' => t("Please enter an audio link/URL:"),
1023                 '$term' => t('Tag term:'),
1024                 '$fileas' => t('Save to Folder:'),
1025                 '$whereareu' => t('Where are you right now?')
1026         ));
1027
1028
1029         $jotplugins = '';
1030         $jotnets = '';
1031
1032         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
1033
1034         $mail_enabled = false;
1035         $pubmail_enabled = false;
1036
1037         if(($x['is_owner']) && (! $mail_disabled)) {
1038                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
1039                         intval(local_user())
1040                 );
1041                 if(count($r)) {
1042                         $mail_enabled = true;
1043                         if(intval($r[0]['pubmail']))
1044                                 $pubmail_enabled = true;
1045                 }
1046         }
1047
1048         if (!$a->user['hidewall']) {
1049                 if($mail_enabled) {
1050                         $selected = (($pubmail_enabled) ? ' checked="checked" ' : '');
1051                         $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . t("Post to Email") . '</div>';
1052                 }
1053
1054                 call_hooks('jot_networks', $jotnets);
1055         } else
1056                 $jotnets .= sprintf(t('Connectors disabled, since "%s" is enabled.'),
1057                                     t('Hide your profile details from unknown viewers?'));
1058
1059         call_hooks('jot_tool', $jotplugins);
1060
1061         if($notes_cid)
1062                 $jotnets .= '<input type="hidden" name="contact_allow[]" value="' . $notes_cid .'" />';
1063
1064
1065         // Private/public post links for the non-JS ACL form
1066         $private_post = 1;
1067         if($_REQUEST['public'])
1068                 $private_post = 0;
1069
1070         $query_str = $a->query_string;
1071         if(strpos($query_str, 'public=1') !== false)
1072                 $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
1073
1074         // I think $a->query_string may never have ? in it, but I could be wrong
1075         // It looks like it's from the index.php?q=[etc] rewrite that the web
1076         // server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1077         if(strpos($query_str, '?') === false)
1078                 $public_post_link = '?public=1';
1079         else
1080                 $public_post_link = '&public=1';
1081
1082
1083
1084 //      $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
1085         $tpl = get_markup_template("jot.tpl");
1086
1087         $o .= replace_macros($tpl,array(
1088                 '$return_path' => $query_str,
1089                 '$action' =>  $a->get_baseurl(true) . '/item',
1090                 '$share' => (x($x,'button') ? $x['button'] : t('Share')),
1091                 '$upload' => t('Upload photo'),
1092                 '$shortupload' => t('upload photo'),
1093                 '$attach' => t('Attach file'),
1094                 '$shortattach' => t('attach file'),
1095                 '$weblink' => t('Insert web link'),
1096                 '$shortweblink' => t('web link'),
1097                 '$video' => t('Insert video link'),
1098                 '$shortvideo' => t('video link'),
1099                 '$audio' => t('Insert audio link'),
1100                 '$shortaudio' => t('audio link'),
1101                 '$setloc' => t('Set your location'),
1102                 '$shortsetloc' => t('set location'),
1103                 '$noloc' => t('Clear browser location'),
1104                 '$shortnoloc' => t('clear location'),
1105                 '$title' => $x['title'],
1106                 '$placeholdertitle' => t('Set title'),
1107                 '$category' => $x['category'],
1108                 '$placeholdercategory' => (feature_enabled(local_user(),'categories') ? t('Categories (comma-separated list)') : ''),
1109                 '$wait' => t('Please wait'),
1110                 '$permset' => t('Permission settings'),
1111                 '$shortpermset' => t('permissions'),
1112                 '$ptyp' => (($notes_cid) ? 'note' : 'wall'),
1113                 '$content' => $x['content'],
1114                 '$post_id' => $x['post_id'],
1115                 '$baseurl' => $a->get_baseurl(true),
1116                 '$defloc' => $x['default_location'],
1117                 '$visitor' => $x['visitor'],
1118                 '$pvisit' => (($notes_cid) ? 'none' : $x['visitor']),
1119                 '$emailcc' => t('CC: email addresses'),
1120                 '$public' => t('Public post'),
1121                 '$jotnets' => $jotnets,
1122                 '$emtitle' => t('Example: bob@example.com, mary@example.com'),
1123                 '$lockstate' => $x['lockstate'],
1124                 '$bang' => $x['bang'],
1125                 '$profile_uid' => $x['profile_uid'],
1126                 '$preview' => ((feature_enabled($x['profile_uid'],'preview')) ? t('Preview') : ''),
1127                 '$jotplugins' => $jotplugins,
1128                 '$sourceapp' => t($a->sourcename),
1129                 '$cancel' => t('Cancel'),
1130                 '$rand_num' => random_digits(12),
1131
1132                 // ACL permissions box
1133                 '$acl' => $x['acl'],
1134                 '$acl_data' => $x['acl_data'],
1135                 '$group_perms' => t('Post to Groups'),
1136                 '$contact_perms' => t('Post to Contacts'),
1137                 '$private' => t('Private post'),
1138                 '$is_private' => $private_post,
1139                 '$public_link' => $public_post_link,
1140         ));
1141
1142
1143         if ($popup==true){
1144                 $o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
1145
1146         }
1147
1148         return $o;
1149 }
1150
1151
1152 function get_item_children($arr, $parent) {
1153         $children = array();
1154         $a = get_app();
1155         foreach($arr as $item) {
1156                 if($item['id'] != $item['parent']) {
1157                         if(get_config('system','thread_allow') && $a->theme_thread_allow) {
1158                                 // Fallback to parent-uri if thr-parent is not set
1159                                 $thr_parent = $item['thr-parent'];
1160                                 if($thr_parent == '')
1161                                         $thr_parent = $item['parent-uri'];
1162
1163                                 if($thr_parent == $parent['uri']) {
1164                                         $item['children'] = get_item_children($arr, $item);
1165                                         $children[] = $item;
1166                                 }
1167                         }
1168                         else if($item['parent'] == $parent['id']) {
1169                                 $children[] = $item;
1170                         }
1171                 }
1172         }
1173         return $children;
1174 }
1175
1176 function sort_item_children($items) {
1177         $result = $items;
1178         usort($result,'sort_thr_created_rev');
1179         foreach($result as $k => $i) {
1180                 if(count($result[$k]['children'])) {
1181                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1182                 }
1183         }
1184         return $result;
1185 }
1186
1187 function add_children_to_list($children, &$arr) {
1188         foreach($children as $y) {
1189                 $arr[] = $y;
1190                 if(count($y['children']))
1191                         add_children_to_list($y['children'], $arr);
1192         }
1193 }
1194
1195 function conv_sort($arr,$order) {
1196
1197         if((!(is_array($arr) && count($arr))))
1198                 return array();
1199
1200         $parents = array();
1201         $children = array();
1202
1203         foreach($arr as $x)
1204                 if($x['id'] == $x['parent'])
1205                                 $parents[] = $x;
1206
1207         if(stristr($order,'created'))
1208                 usort($parents,'sort_thr_created');
1209         elseif(stristr($order,'commented'))
1210                 usort($parents,'sort_thr_commented');
1211
1212         if(count($parents))
1213                 foreach($parents as $i=>$_x)
1214                         $parents[$i]['children'] = get_item_children($arr, $_x);
1215
1216         /*foreach($arr as $x) {
1217                 if($x['id'] != $x['parent']) {
1218                         $p = find_thread_parent_index($parents,$x);
1219                         if($p !== false)
1220                                 $parents[$p]['children'][] = $x;
1221                 }
1222         }*/
1223         if(count($parents)) {
1224                 foreach($parents as $k => $v) {
1225                         if(count($parents[$k]['children'])) {
1226                                 $parents[$k]['children'] = sort_item_children($parents[$k]['children']);
1227                                 /*$y = $parents[$k]['children'];
1228                                 usort($y,'sort_thr_created_rev');
1229                                 $parents[$k]['children'] = $y;*/
1230                         }
1231                 }
1232         }
1233
1234         $ret = array();
1235         if(count($parents)) {
1236                 foreach($parents as $x) {
1237                         $ret[] = $x;
1238                         if(count($x['children']))
1239                                 add_children_to_list($x['children'], $ret);
1240                                 /*foreach($x['children'] as $y)
1241                                         $ret[] = $y;*/
1242                 }
1243         }
1244
1245         return $ret;
1246 }
1247
1248
1249 function sort_thr_created($a,$b) {
1250         return strcmp($b['created'],$a['created']);
1251 }
1252
1253 function sort_thr_created_rev($a,$b) {
1254         return strcmp($a['created'],$b['created']);
1255 }
1256
1257 function sort_thr_commented($a,$b) {
1258         return strcmp($b['commented'],$a['commented']);
1259 }
1260
1261 function find_thread_parent_index($arr,$x) {
1262         foreach($arr as $k => $v)
1263                 if($v['id'] == $x['parent'])
1264                         return $k;
1265         return false;
1266 }
1267
1268 function render_location_google($item) {
1269         $location = (($item['location']) ? '<a target="map" title="' . $item['location'] . '" href="http://maps.google.com/?q=' . urlencode($item['location']) . '">' . $item['location'] . '</a>' : '');
1270         $coord = (($item['coord']) ? '<a target="map" title="' . $item['coord'] . '" href="http://maps.google.com/?q=' . urlencode($item['coord']) . '">' . $item['coord'] . '</a>' : '');
1271         if($coord) {
1272                 if($location)
1273                         $location .= '<br /><span class="smalltext">(' . $coord . ')</span>';
1274                 else
1275                         $location = '<span class="smalltext">' . $coord . '</span>';
1276         }
1277         return $location;
1278 }