]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
getting comment counts correct in a threaded world
[friendica.git] / include / conversation.php
1 <?php
2
3 // Note: the code in 'item_extract_images' and 'item_redir_and_replace_images'
4 // is identical to the code in mod/message.php for 'item_extract_images' and
5 // 'item_redir_and_replace_images'
6 if(! function_exists('item_extract_images')) {
7 function item_extract_images($body) {
8
9         $saved_image = array();
10         $orig_body = $body;
11         $new_body = '';
12
13         $cnt = 0;
14         $img_start = strpos($orig_body, '[img');
15         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
16         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
17         while(($img_st_close !== false) && ($img_end !== false)) {
18
19                 $img_st_close++; // make it point to AFTER the closing bracket
20                 $img_end += $img_start;
21
22                 if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
23                         // This is an embedded image
24
25                         $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
26                         $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
27
28                         $cnt++;
29                 }
30                 else
31                         $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
32
33                 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
34
35                 if($orig_body === false) // in case the body ends on a closing image tag
36                         $orig_body = '';
37
38                 $img_start = strpos($orig_body, '[img');
39                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
40                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
41         }
42
43         $new_body = $new_body . $orig_body;
44
45         return array('body' => $new_body, 'images' => $saved_image);
46 }}
47
48 if(! function_exists('item_redir_and_replace_images')) {
49 function item_redir_and_replace_images($body, $images, $cid) {
50
51         $origbody = $body;
52         $newbody = '';
53
54         for($i = 0; $i < count($images); $i++) {
55                 $search = '/\[url\=(.*?)\]\[!#saved_image' . $i . '#!\]\[\/url\]' . '/is';
56                 $replace = '[url=' . z_path() . '/redir/' . $cid 
57                            . '?f=1&url=' . '$1' . '][!#saved_image' . $i . '#!][/url]' ;
58
59                 $img_end = strpos($origbody, '[!#saved_image' . $i . '#!][/url]') + strlen('[!#saved_image' . $i . '#!][/url]');
60                 $process_part = substr($origbody, 0, $img_end);
61                 $origbody = substr($origbody, $img_end);
62
63                 $process_part = preg_replace($search, $replace, $process_part);
64                 $newbody = $newbody . $process_part;
65         }
66         $newbody = $newbody . $origbody;
67
68         $cnt = 0;
69         foreach($images as $image) {
70                 // We're depending on the property of 'foreach' (specified on the PHP website) that
71                 // it loops over the array starting from the first element and going sequentially
72                 // to the last element
73                 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
74                 $cnt++;
75         }
76         return $newbody;
77 }}
78
79
80
81 /**
82  * Render actions localized
83  */
84 function localize_item(&$item){
85
86         $extracted = item_extract_images($item['body']);
87         if($extracted['images'])
88                 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
89
90         $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
91         if ($item['verb']=== ACTIVITY_LIKE || $item['verb']=== ACTIVITY_DISLIKE){
92
93                 $r = q("SELECT * from `item`,`contact` WHERE 
94                                 `item`.`contact-id`=`contact`.`id` AND `item`.`uri`='%s';",
95                                  dbesc($item['parent-uri']));
96                 if(count($r)==0) return;
97                 $obj=$r[0];
98                 
99                 $author  = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
100                 $objauthor =  '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]';
101                 
102                 switch($obj['verb']){
103                         case ACTIVITY_POST:
104                                 switch ($obj['object-type']){
105                                         case ACTIVITY_OBJ_EVENT:
106                                                 $post_type = t('event');
107                                                 break;
108                                         default:
109                                                 $post_type = t('status');
110                                 }
111                                 break;
112                         default:
113                                 if($obj['resource-id']){
114                                         $post_type = t('photo');
115                                         $m=array();     preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
116                                         $rr['plink'] = $m[1];
117                                 } else {
118                                         $post_type = t('status');
119                                 }
120                 }
121         
122                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
123                 
124                 switch($item['verb']){
125                         case ACTIVITY_LIKE :
126                                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
127                                 break;
128                         case ACTIVITY_DISLIKE:
129                                 $bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s');
130                                 break;
131                 }
132                 $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
133                         
134         }
135         if ($item['verb']=== ACTIVITY_FRIEND){
136
137                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
138
139                 $Aname = $item['author-name'];
140                 $Alink = $item['author-link'];
141                 
142                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
143                 
144                 $obj = parse_xml_string($xmlhead.$item['object']);
145                 $links = parse_xml_string($xmlhead."<links>".unxmlify($obj->link)."</links>");
146                 
147                 $Bname = $obj->title;
148                 $Blink = ""; $Bphoto = "";
149                 foreach ($links->link as $l){
150                         $atts = $l->attributes();
151                         switch($atts['rel']){
152                                 case "alternate": $Blink = $atts['href'];
153                                 case "photo": $Bphoto = $atts['href'];
154                         }
155                         
156                 }
157                 
158                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
159                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
160                 if ($Bphoto!="") $Bphoto = '[url=' . zrl($Blink) . '][img]' . $Bphoto . '[/img][/url]';
161
162                 $item['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
163
164         }
165         if (stristr($item['verb'],ACTIVITY_POKE)) {
166                 $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
167                 if(! $verb)
168                         return;
169                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
170
171                 $Aname = $item['author-name'];
172                 $Alink = $item['author-link'];
173                 
174                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
175                 
176                 $obj = parse_xml_string($xmlhead.$item['object']);
177                 $links = parse_xml_string($xmlhead."<links>".unxmlify($obj->link)."</links>");
178                 
179                 $Bname = $obj->title;
180                 $Blink = ""; $Bphoto = "";
181                 foreach ($links->link as $l){
182                         $atts = $l->attributes();
183                         switch($atts['rel']){
184                                 case "alternate": $Blink = $atts['href'];
185                                 case "photo": $Bphoto = $atts['href'];
186                         }
187                         
188                 }
189                 
190                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
191                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
192                 if ($Bphoto!="") $Bphoto = '[url=' . zrl($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
193
194                 // we can't have a translation string with three positions but no distinguishable text
195                 // So here is the translate string.
196
197                 $txt = t('%1$s poked %2$s');
198
199                 // now translate the verb
200
201                 $txt = str_replace( t('poked'), t($verb), $txt);
202
203                 // then do the sprintf on the translation string
204
205                 $item['body'] = sprintf($txt, $A, $B). "\n\n\n" . $Bphoto;
206
207         }
208     if ($item['verb']===ACTIVITY_TAG){
209                 $r = q("SELECT * from `item`,`contact` WHERE 
210                 `item`.`contact-id`=`contact`.`id` AND `item`.`uri`='%s';",
211                  dbesc($item['parent-uri']));
212                 if(count($r)==0) return;
213                 $obj=$r[0];
214                 
215                 $author  = '[url=' . zrl($item['author-link']) . ']' . $item['author-name'] . '[/url]';
216                 $objauthor =  '[url=' . zrl($obj['author-link']) . ']' . $obj['author-name'] . '[/url]';
217                 
218                 switch($obj['verb']){
219                         case ACTIVITY_POST:
220                                 switch ($obj['object-type']){
221                                         case ACTIVITY_OBJ_EVENT:
222                                                 $post_type = t('event');
223                                                 break;
224                                         default:
225                                                 $post_type = t('status');
226                                 }
227                                 break;
228                         default:
229                                 if($obj['resource-id']){
230                                         $post_type = t('photo');
231                                         $m=array();     preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
232                                         $rr['plink'] = $m[1];
233                                 } else {
234                                         $post_type = t('status');
235                                 }
236                 }
237                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
238                 
239                 $parsedobj = parse_xml_string($xmlhead.$item['object']);
240                 
241                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
242                 $item['body'] = sprintf( t('%1$s tagged %2$s\'s %3$s with %4$s'), $author, $objauthor, $plink, $tag );
243                 
244         }
245         if ($item['verb']=== ACTIVITY_FAVORITE){
246
247                 if ($item['object-type']== "")
248                         return;
249
250                 $Aname = $item['author-name'];
251                 $Alink = $item['author-link'];
252                 
253                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
254                 
255                 $obj = parse_xml_string($xmlhead.$item['object']);
256                 if(strlen($obj->id)) {
257                         $r = q("select * from item where uri = '%s' and uid = %d limit 1",
258                                         dbesc($obj->id),
259                                         intval($item['uid'])
260                         );
261                         if(count($r) && $r[0]['plink']) {
262                                 $target = $r[0];
263                                 $Bname = $target['author-name'];
264                                 $Blink = $target['author-link'];
265                                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
266                                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
267                                 $P = '[url=' . $target['plink'] . ']' . t('post/item') . '[/url]';
268                                 $item['body'] = sprintf( t('%1$s marked %2$s\'s %3$s as favorite'), $A, $B, $P)."\n";
269
270                         }
271                 }
272         }
273         $matches = null;
274         if(preg_match_all('/@\[url=(.*?)\]/is',$item['body'],$matches,PREG_SET_ORDER)) {
275                 foreach($matches as $mtch) {
276                         if(! strpos($mtch[1],'zrl='))
277                                 $item['body'] = str_replace($mtch[0],'@[url=' . zrl($mtch[1]). ']',$item['body']);
278                 }
279         }
280
281         // add zrl's to public images
282         if(preg_match_all('/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is',$item['body'],$matches,PREG_SET_ORDER)) {
283                 foreach($matches as $mtch) {
284                                 $item['body'] = str_replace($mtch[0],'[url=' . zrl($mtch[1] . '/photos/' . $mtch[2] . '/image/' . $mtch[3] ,true) . '][img' . $mtch[4] . ']h' . $mtch[5]  . '[/img][/url]',$item['body']);
285                 }
286         }
287
288         // add sparkle links to appropriate permalinks
289
290         $x = stristr($item['plink'],'/display/');
291         if($x) {
292                 $sparkle = false;
293                 $y = best_link_url($item,$sparkle,true);
294                 if(strstr($y,'/redir/'))
295                         $item['plink'] = $y . '?f=&url=' . $item['plink'];
296         } 
297
298
299
300 }
301
302 /**
303  * Count the total of comments on this item and its desendants
304  */
305 function count_descendants($item) {
306         $total = count($item['children']);
307
308         if($total > 0) {
309                 foreach($item['children'] as $child) {
310                         if($child['verb'] === ACTIVITY_LIKE || $child['verb'] === ACTIVITY_DISLIKE) {
311                                 $total --;
312                         }
313                         $total += count_descendants($child);
314                 }
315         }
316
317         return $total;
318 }
319
320 /**
321  * Recursively prepare a thread for HTML
322  */
323
324 function prepare_threads_body($a, $items, $cmnt_tpl, $page_writeable, $mode, $profile_owner, $alike, $dlike, $thread_level=1) {
325         $result = array();
326
327         $wall_template = 'wall_thread.tpl';
328         $wallwall_template = 'wallwall_thread.tpl';
329         $items_seen = 0;
330         $nb_items = count($items);
331         
332         $total_children = $nb_items;
333         
334         foreach($items as $item) {
335                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
336                         // Don't count it as a visible item
337                         $nb_items--;
338                         $total_children --;
339                 }
340                 if($item['verb'] === ACTIVITY_LIKE || $item['verb'] === ACTIVITY_DISLIKE) {
341                         $nb_items --;
342                         $total_children --;
343
344                 }
345         }
346
347         foreach($items as $item) {
348                 // prevent private email reply to public conversation from leaking.
349                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
350                         continue;
351                 }
352
353                 if($item['verb'] === ACTIVITY_LIKE || $item['verb'] === ACTIVITY_DISLIKE) {
354                         continue;
355                 }
356                 
357                 $items_seen++;
358                 
359                 $comment = '';
360                 $template = $wall_template;
361                 $commentww = '';
362                 $sparkle = '';
363                 $owner_url = $owner_photo = $owner_name = '';
364                 $buttons = '';
365                 $dropping = false;
366                 $star = false;
367                 $isstarred = "unstarred";
368                 $photo = $item['photo'];
369                 $thumb = $item['thumb'];
370                 $indent = '';
371                 $osparkle = '';
372                 $lastcollapsed = false;
373                 $firstcollapsed = false;
374                 $total_children += count_descendants($item);
375
376                 $toplevelpost = (($item['id'] == $item['parent']) ? true : false);
377                 $item_writeable = (($item['writable'] || $item['self']) ? true : false);
378                 $show_comment_box = ((($page_writeable) && ($item_writeable)) ? true : false);
379                 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid']) 
380                         || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
381                         ? t('Private Message')
382                         : false);
383                 $redirect_url = $a->get_baseurl($ssl_state) . '/redir/' . $item['cid'] ;
384                 $shareable = ((($profile_owner == local_user()) && ($item['private'] != 1)) ? true : false);
385                 if(local_user() && link_compare($a->contact['url'],$item['author-link']))
386                         $edpost = array($a->get_baseurl($ssl_state)."/editpost/".$item['id'], t("Edit"));
387                 else
388                         $edpost = false;
389                 if((intval($item['contact-id']) && $item['contact-id'] == remote_user()) || ($item['uid'] == local_user()))
390                         $dropping = true;
391
392                 $drop = array(
393                         'dropping' => $dropping,
394                         'select' => t('Select'), 
395                         'delete' => t('Delete'),
396                 );
397                 
398                 $filer = (($profile_owner == local_user()) ? t("save to folder") : false);
399
400                 $diff_author    = ((link_compare($item['url'],$item['author-link'])) ? false : true);
401                 $profile_name   = (((strlen($item['author-name']))   && $diff_author) ? $item['author-name']   : $item['name']);
402                 if($item['author-link'] && (! $item['author-name']))
403                         $profile_name = $item['author-link'];
404
405                 $sp = false;
406                 $profile_link = best_link_url($item,$sp);
407                 if($profile_link === 'mailbox')
408                         $profile_link = '';
409                 if($sp)
410                         $sparkle = ' sparkle';
411                 else
412                         $profile_link = zrl($profile_link);                                     
413
414                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
415                 if(($normalised != 'mailbox') && (x($a->contacts,$normalised)))
416                         $profile_avatar = $a->contacts[$normalised]['thumb'];
417                 else
418                         $profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $a->get_cached_avatar_image($thumb));
419
420                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
421                 call_hooks('render_location',$locate);
422                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
423
424                 $tags=array();
425                 foreach(explode(',',$item['tag']) as $tag){
426                         $tag = trim($tag);
427                         if ($tag!="") $tags[] = bbcode($tag);
428                 }
429
430                 $like    = ((x($alike,$item['uri'])) ? format_like($alike[$item['uri']],$alike[$item['uri'] . '-l'],'like',$item['uri']) : '');
431                 $dislike = ((x($dlike,$item['uri'])) ? format_like($dlike[$item['uri']],$dlike[$item['uri'] . '-l'],'dislike',$item['uri']) : '');
432
433                 if($toplevelpost) {
434                         if((! $item['self']) && ($mode !== 'profile')) {
435                                 if($item['wall']) {
436
437                                         // On the network page, I am the owner. On the display page it will be the profile owner.
438                                         // This will have been stored in $a->page_contact by our calling page.
439                                         // Put this person as the wall owner of the wall-to-wall notice.
440
441                                         $owner_url = zrl($a->page_contact['url']);
442                                         $owner_photo = $a->page_contact['thumb'];
443                                         $owner_name = $a->page_contact['name'];
444                                         $template = $wallwall_template;
445                                         $commentww = 'ww';      
446                                 }
447                         }
448                         else if($item['owner-link']) {
449
450                                 $owner_linkmatch = (($item['owner-link']) && link_compare($item['owner-link'],$item['author-link']));
451                                 $alias_linkmatch = (($item['alias']) && link_compare($item['alias'],$item['author-link']));
452                                 $owner_namematch = (($item['owner-name']) && $item['owner-name'] == $item['author-name']);
453                                 if((! $owner_linkmatch) && (! $alias_linkmatch) && (! $owner_namematch)) {
454
455                                         // The author url doesn't match the owner (typically the contact)
456                                         // and also doesn't match the contact alias. 
457                                         // The name match is a hack to catch several weird cases where URLs are 
458                                         // all over the park. It can be tricked, but this prevents you from
459                                         // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
460                                         // well that it's the same Bob Smith. 
461
462                                         // But it could be somebody else with the same name. It just isn't highly likely. 
463                                         
464
465                                         $owner_url = $item['owner-link'];
466                                         $owner_photo = $item['owner-avatar'];
467                                         $owner_name = $item['owner-name'];
468                                         $template = $wallwall_template;
469                                         $commentww = 'ww';
470                                         // If it is our contact, use a friendly redirect link
471                                         if((link_compare($item['owner-link'],$item['url'])) 
472                                                 && ($item['network'] === NETWORK_DFRN)) {
473                                                 $owner_url = $redirect_url;
474                                                 $osparkle = ' sparkle';
475                                         }
476                                         else
477                                                 $owner_url = zrl($owner_url);
478                                 }
479                         }
480                         if($profile_owner == local_user()) {
481                                 $isstarred = (($item['starred']) ? "starred" : "unstarred");
482
483                                 $star = array(
484                                         'do' => t("add star"),
485                                         'undo' => t("remove star"),
486                                         'toggle' => t("toggle star status"),
487                                         'classdo' => (($item['starred']) ? "hidden" : ""),
488                                         'classundo' => (($item['starred']) ? "" : "hidden"),
489                                         'starred' =>  t('starred'),
490                                         'tagger' => t("add tag"),
491                                         'classtagger' => "",
492                                 );
493                         }
494                 } else {
495                         $indent = 'comment';
496                         // Collapse comments
497                         if(($nb_items > 2) || ($thread_level > 2)) {
498                                 if($items_seen == 1) {
499                                         $firstcollapsed = true;
500                                 }
501                                 if($thread_level > 2) {
502                                         if($items_seen == $nb_items)
503                                                 $lastcollapsed = true;
504                                 }
505                                 else if($items_seen == ($nb_items - 2)) {
506                                         $lastcollapsed = true;
507                                 }
508                         }
509                 }
510
511                 if($page_writeable) {
512                         $buttons = array(
513                                 'like' => array( t("I like this \x28toggle\x29"), t("like")),
514                                 'dislike' => array( t("I don't like this \x28toggle\x29"), t("dislike")),
515                         );
516                         if ($shareable) $buttons['share'] = array( t('Share this'), t('share'));
517
518
519                         if($show_comment_box) {
520                                 $qc = $qcomment =  null;
521
522                                 if(in_array('qcomment',$a->plugins)) {
523                                         $qc = ((local_user()) ? get_pconfig(local_user(),'qcomment','words') : null);
524                                         $qcomment = (($qc) ? explode("\n",$qc) : null);
525                                 }
526                                 $comment = replace_macros($cmnt_tpl,array(
527                                         '$return_path' => '', 
528                                         '$jsreload' => (($mode === 'display') ? $_SESSION['return_url'] : ''),
529                                         '$type' => (($mode === 'profile') ? 'wall-comment' : 'net-comment'),
530                                         '$id' => $item['item_id'],
531                                         '$parent' => $item['item_id'],
532                                         '$qcomment' => $qcomment,
533                                         '$profile_uid' =>  $profile_owner,
534                                         '$mylink' => $a->contact['url'],
535                                         '$mytitle' => t('This is you'),
536                                         '$myphoto' => $a->contact['thumb'],
537                                         '$comment' => t('Comment'),
538                                         '$submit' => t('Submit'),
539                                         '$edbold' => t('Bold'),
540                                         '$editalic' => t('Italic'),
541                                         '$eduline' => t('Underline'),
542                                         '$edquote' => t('Quote'),
543                                         '$edcode' => t('Code'),
544                                         '$edimg' => t('Image'),
545                                         '$edurl' => t('Link'),
546                                         '$edvideo' => t('Video'),
547                                         '$preview' => t('Preview'),
548                                         '$sourceapp' => t($a->sourcename),
549                                         '$ww' => (($mode === 'network') ? $commentww : '')
550                                 ));
551                         }
552                 }
553
554                 if(strcmp(datetime_convert('UTC','UTC',$item['created']),datetime_convert('UTC','UTC','now - 12 hours')) > 0)
555                         $indent .= ' shiny';
556
557                 localize_item($item);
558
559                 $body = prepare_body($item,true);
560
561                 $tmp_item = array(
562                         // collapse comments in template. I don't like this much...
563                         'comment_firstcollapsed' => $firstcollapsed,
564                         'comment_lastcollapsed' => $lastcollapsed,
565                         // template to use to render item (wall, walltowall, search)
566                         'template' => $template,
567                         
568                         'type' => implode("",array_slice(explode("/",$item['verb']),-1)),
569                         'tags' => $tags,
570                         'body' => template_escape($body),
571                         'text' => strip_tags(template_escape($body)),
572                         'id' => $item['item_id'],
573                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
574                         'olinktitle' => sprintf( t('View %s\'s profile @ %s'), $owner_name, ((strlen($item['owner-link'])) ? $item['owner-link'] : $item['url'])),
575                         'to' => t('to'),
576                         'wall' => t('Wall-to-Wall'),
577                         'vwall' => t('via Wall-To-Wall:'),
578                         'profile_url' => $profile_link,
579                         'item_photo_menu' => item_photo_menu($item),
580                         'name' => template_escape($profile_name),
581                         'thumb' => $profile_avatar,
582                         'osparkle' => $osparkle,
583                         'sparkle' => $sparkle,
584                         'title' => template_escape($item['title']),
585                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
586                         'lock' => $lock,
587                         'location' => template_escape($location),
588                         'indent' => $indent,
589                         'owner_url' => $owner_url,
590                         'owner_photo' => $owner_photo,
591                         'owner_name' => template_escape($owner_name),
592                         'plink' => get_plink($item),
593                         'edpost' => $edpost,
594                         'isstarred' => $isstarred,
595                         'star' => $star,
596                         'filer' => $filer,
597                         'drop' => $drop,
598                         'vote' => $buttons,
599                         'like' => $like,
600                         'dislike' => $dislike,
601                         'comment' => $comment,
602                         'previewing' => $previewing,
603                         'wait' => t('Please wait'),
604                         'thread_level' => $thread_level,
605                 );
606
607                 $arr = array('item' => $item, 'output' => $tmp_item);
608                 call_hooks('display_item', $arr);
609
610                 $item_result = $arr['output'];
611                 if($firstcollapsed) {
612                         $item_result['num_comments'] = sprintf( tt('%d comment','%d comments',$total_children),$total_children );
613                         $item_result['hide_text'] = t('show more');
614                 }
615
616                 $item_result['children'] = array();
617                 if(count($item['children'])) {
618                         $item_result['children'] = prepare_threads_body($a, $item['children'], $cmnt_tpl, $page_writeable, $mode, $profile_owner, $alike, $dlike, ($thread_level + 1));
619                 }
620                 $item_result['private'] = $item['private'];
621                 $item_result['toplevel'] = ($toplevelpost ? 'toplevel_item' : '');
622
623                 /*
624                  * I don't like this very much...
625                  */
626                 if(get_config('system','thread_allow')) {
627                         $item_result['flatten'] = false;
628                         $item_result['threaded'] = true;
629                 }
630                 else {
631                         $item_result['flatten'] = true;
632                         $item_result['threaded'] = false;
633                         if(!$toplevelpost) {
634                                 $item_result['comment'] = false;
635                         }
636                 }
637                 
638                 $result[] = $item_result;
639         }
640
641         return $result;
642 }
643
644 /**
645  * "Render" a conversation or list of items for HTML display.
646  * There are two major forms of display:
647  *      - Sequential or unthreaded ("New Item View" or search results)
648  *      - conversation view
649  * The $mode parameter decides between the various renderings and also
650  * figures out how to determine page owner and other contextual items 
651  * that are based on unique features of the calling module.
652  *
653  */
654
655 if(!function_exists('conversation')) {
656 function conversation(&$a, $items, $mode, $update, $preview = false) {
657
658
659         require_once('bbcode.php');
660
661         $ssl_state = ((local_user()) ? true : false);
662
663         $profile_owner = 0;
664         $page_writeable      = false;
665
666         $previewing = (($preview) ? ' preview ' : '');
667
668         if($mode === 'network') {
669                 $profile_owner = local_user();
670                 $page_writeable = true;
671         }
672
673         if($mode === 'profile') {
674                 $profile_owner = $a->profile['profile_uid'];
675                 $page_writeable = can_write_wall($a,$profile_owner);
676         }
677
678         if($mode === 'notes') {
679                 $profile_owner = local_user();
680                 $page_writeable = true;
681         }
682
683         if($mode === 'display') {
684                 $profile_owner = $a->profile['uid'];
685                 $page_writeable = can_write_wall($a,$profile_owner);
686         }
687
688         if($mode === 'community') {
689                 $profile_owner = 0;
690                 $page_writeable = false;
691         }
692
693         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
694
695
696         if($update)
697                 $return_url = $_SESSION['return_url'];
698         else
699                 $return_url = $_SESSION['return_url'] = $a->query_string;
700
701         load_contact_links(local_user());
702
703         $cb = array('items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview);
704         call_hooks('conversation_start',$cb);
705
706         $items = $cb['items'];
707
708         $cmnt_tpl    = get_markup_template('comment_item.tpl');
709         $tpl         = 'wall_item.tpl';
710         $wallwall    = 'wallwall_item.tpl';
711         $hide_comments_tpl = get_markup_template('hide_comments.tpl');
712
713         $alike = array();
714         $dlike = array();
715         
716         
717         // array with html for each thread (parent+comments)
718         $threads = array();
719         $threadsid = -1;
720
721         $page_template = get_markup_template("conversation.tpl");
722                 
723         if($items && count($items)) {
724
725                 if($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
726
727                         // "New Item View" on network page or search page results 
728                         // - just loop through the items and format them minimally for display
729
730                         //$tpl = get_markup_template('search_item.tpl');
731                         $tpl = 'search_item.tpl';
732
733                         foreach($items as $item) {
734                                 $threadsid++;
735
736                                 $comment     = '';
737                                 $owner_url   = '';
738                                 $owner_photo = '';
739                                 $owner_name  = '';
740                                 $sparkle     = '';
741
742                                 if($mode === 'search' || $mode === 'community') {
743                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) 
744                                                 && ($item['id'] != $item['parent']))
745                                                 continue;
746                                         $nickname = $item['nickname'];
747                                 }
748                                 else
749                                         $nickname = $a->user['nickname'];
750                                 
751                                 // prevent private email from leaking.
752                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
753                                                 continue;
754                         
755                                 $profile_name   = ((strlen($item['author-name']))   ? $item['author-name']   : $item['name']);
756                                 if($item['author-link'] && (! $item['author-name']))
757                                         $profile_name = $item['author-link'];
758
759
760
761                                 $sp = false;
762                                 $profile_link = best_link_url($item,$sp);
763                                 if($profile_link === 'mailbox')
764                                         $profile_link = '';
765                                 if($sp)
766                                         $sparkle = ' sparkle';
767                                 else
768                                         $profile_link = zrl($profile_link);                                     
769
770                                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
771                                 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
772                                         $profile_avatar = $a->contacts[$normalised]['thumb'];
773                                 else
774                                         $profile_avatar = ((strlen($item['author-avatar'])) ? $a->get_cached_avatar_image($item['author-avatar']) : $item['thumb']);
775
776                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
777                                 call_hooks('render_location',$locate);
778
779                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
780
781                                 localize_item($item);
782                                 if($mode === 'network-new')
783                                         $dropping = true;
784                                 else
785                                         $dropping = false;
786
787
788                                 $drop = array(
789                                         'dropping' => $dropping,
790                                         'select' => t('Select'), 
791                                         'delete' => t('Delete'),
792                                 );
793
794                                 $star = false;
795                                 $isstarred = "unstarred";
796                                 
797                                 $lock = false;
798                                 $likebuttons = false;
799                                 $shareable = false;
800
801                                 $body = prepare_body($item,true);
802                                 
803                                 //$tmp_item = replace_macros($tpl,array(
804                                 $tmp_item = array(
805                                         'template' => $tpl,
806                                         'id' => (($preview) ? 'P0' : $item['item_id']),
807                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
808                                         'profile_url' => $profile_link,
809                                         'item_photo_menu' => item_photo_menu($item),
810                                         'name' => template_escape($profile_name),
811                                         'sparkle' => $sparkle,
812                                         'lock' => $lock,
813                                         'thumb' => $profile_avatar,
814                                         'title' => template_escape($item['title']),
815                                         'body' => template_escape($body),
816                                         'text' => strip_tags(template_escape($body)),
817                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
818                                         'location' => template_escape($location),
819                                         'indent' => '',
820                                         'owner_name' => template_escape($owner_name),
821                                         'owner_url' => $owner_url,
822                                         'owner_photo' => $owner_photo,
823                                         'plink' => get_plink($item),
824                                         'edpost' => false,
825                                         'isstarred' => $isstarred,
826                                         'star' => $star,
827                                         'drop' => $drop,
828                                         'vote' => $likebuttons,
829                                         'like' => '',
830                                         'dislike' => '',
831                                         'comment' => '',
832                                         'conv' => (($preview) ? '' : array('href'=> $a->get_baseurl($ssl_state) . '/display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
833                                         'previewing' => $previewing,
834                                         'wait' => t('Please wait'),
835                                         'thread_level' => 1,
836                                 );
837
838                                 $arr = array('item' => $item, 'output' => $tmp_item);
839                                 call_hooks('display_item', $arr);
840
841                                 $threads[$threadsid]['id'] = $item['item_id'];
842                                 $threads[$threadsid]['items'] = array($arr['output']);
843
844                         }
845
846                 }
847                 else
848                 {
849                         // Normal View
850                         $page_template = get_markup_template("threaded_conversation.tpl");
851
852                         // get all the topmost parents
853                         // this shouldn't be needed, as we should have only them in ou array
854                         // But for now, this array respects the old style, just in case
855
856                         $threads = array();
857                         foreach($items as $item) {
858
859                                 like_puller($a,$item,$alike,'like');
860                                 like_puller($a,$item,$dlike,'dislike');
861
862                                 if($item['id'] == $item['parent']) {
863                                         $threads[] = $item;
864                                 }
865                         }
866
867                         $threads = prepare_threads_body($a, $threads, $cmnt_tpl, $page_writeable, $mode,  $profile_owner, $alike, $dlike);
868                 }
869         }
870                 
871         $o = replace_macros($page_template, array(
872                 '$baseurl' => $a->get_baseurl($ssl_state),
873                 '$mode' => $mode,
874                 '$user' => $a->user,
875                 '$threads' => $threads,
876                 '$dropping' => ($page_dropping?t('Delete Selected Items'):False),
877         ));
878
879         return $o;
880 }}
881
882 function best_link_url($item,&$sparkle,$ssl_state = false) {
883
884         $a = get_app();
885
886         $best_url = '';
887         $sparkle  = false;
888
889         $clean_url = normalise_link($item['author-link']);
890
891         if((local_user()) && (local_user() == $item['uid'])) {
892                 if(isset($a->contacts) && x($a->contacts,$clean_url)) {
893                         if($a->contacts[$clean_url]['network'] === NETWORK_DFRN) {
894                                 $best_url = $a->get_baseurl($ssl_state) . '/redir/' . $a->contacts[$clean_url]['id'];
895                                 $sparkle = true;
896                         }
897                         else
898                                 $best_url = $a->contacts[$clean_url]['url'];
899                 }
900         }
901         if(! $best_url) {
902                 if(strlen($item['author-link']))
903                         $best_url = $item['author-link'];
904                 else
905                         $best_url = $item['url'];
906         }
907
908         return $best_url;
909 }
910
911
912 if(! function_exists('item_photo_menu')){
913 function item_photo_menu($item){
914         $a = get_app();
915
916         $ssl_state = false;
917
918         if(local_user()) {
919                 $ssl_state = true;
920                  if(! count($a->contacts))
921                         load_contact_links(local_user());
922         }
923         $poke_link="";
924         $contact_url="";
925         $pm_url="";
926         $status_link="";
927         $photos_link="";
928         $posts_link="";
929
930         $sparkle = false;
931     $profile_link = best_link_url($item,$sparkle,$ssl_state);
932         if($profile_link === 'mailbox')
933                 $profile_link = '';
934
935         if($sparkle) {
936                 $cid = intval(basename($profile_link));
937                 $status_link = $profile_link . "?url=status";
938                 $photos_link = $profile_link . "?url=photos";
939                 $profile_link = $profile_link . "?url=profile";
940                 $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
941                 $zurl = '';
942         }
943         else {
944                 $profile_link = zrl($profile_link);
945                 if(local_user() && local_user() == $item['uid'] && link_compare($item['url'],$item['author-link'])) {
946                         $cid = $item['contact-id'];
947                 }               
948                 else {
949                         $cid = 0;
950                 }
951         }
952         if(($cid) && (! $item['self'])) {
953                 $poke_link = $a->get_baseurl($ssl_state) . '/poke/?f=&c=' . $cid;
954                 $contact_url = $a->get_baseurl($ssl_state) . '/contacts/' . $cid;
955                 $posts_link = $a->get_baseurl($ssl_state) . '/network/?cid=' . $cid;
956
957                 $clean_url = normalise_link($item['author-link']);
958
959                 if((local_user()) && (local_user() == $item['uid'])) {
960                         if(isset($a->contacts) && x($a->contacts,$clean_url)) {
961                                 if($a->contacts[$clean_url]['network'] === NETWORK_DIASPORA) {
962                                         $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
963                                 }
964                         }
965                 }
966
967         }
968
969         $menu = Array(
970                 t("View Status") => $status_link,
971                 t("View Profile") => $profile_link,
972                 t("View Photos") => $photos_link,
973                 t("Network Posts") => $posts_link, 
974                 t("Edit Contact") => $contact_url,
975                 t("Send PM") => $pm_url,
976                 t("Poke") => $poke_link
977         );
978         
979         
980         $args = array('item' => $item, 'menu' => $menu);
981         
982         call_hooks('item_photo_menu', $args);
983
984         $menu = $args['menu'];  
985
986         $o = "";
987         foreach($menu as $k=>$v){
988                 if ($v!="") $o .= "<li><a href=\"$v\">$k</a></li>\n";
989         }
990         return $o;
991 }}
992
993 if(! function_exists('like_puller')) {
994 function like_puller($a,$item,&$arr,$mode) {
995
996         $url = '';
997         $sparkle = '';
998         $verb = (($mode === 'like') ? ACTIVITY_LIKE : ACTIVITY_DISLIKE);
999
1000         if((activity_match($item['verb'],$verb)) && ($item['id'] != $item['parent'])) {
1001                 $url = $item['author-link'];
1002                 if((local_user()) && (local_user() == $item['uid']) && ($item['network'] === 'dfrn') && (! $item['self']) && (link_compare($item['author-link'],$item['url']))) {
1003                         $url = $a->get_baseurl(true) . '/redir/' . $item['contact-id'];
1004                         $sparkle = ' class="sparkle" ';
1005                 }
1006                 else
1007                         $url = zrl($url);
1008
1009                 if(! $item['thr-parent'])
1010                         $item['thr-parent'] = $item['parent-uri'];
1011
1012                 if(! ((isset($arr[$item['thr-parent'] . '-l'])) && (is_array($arr[$item['thr-parent'] . '-l']))))
1013                         $arr[$item['thr-parent'] . '-l'] = array();
1014                 if(! isset($arr[$item['thr-parent']]))
1015                         $arr[$item['thr-parent']] = 1;
1016                 else    
1017                         $arr[$item['thr-parent']] ++;
1018                 $arr[$item['thr-parent'] . '-l'][] = '<a href="'. $url . '"'. $sparkle .'>' . $item['author-name'] . '</a>';
1019         }
1020         return;
1021 }}
1022
1023 // Format the like/dislike text for a profile item
1024 // $cnt = number of people who like/dislike the item
1025 // $arr = array of pre-linked names of likers/dislikers
1026 // $type = one of 'like, 'dislike'
1027 // $id  = item id
1028 // returns formatted text
1029
1030 if(! function_exists('format_like')) {
1031 function format_like($cnt,$arr,$type,$id) {
1032         $o = '';
1033         if($cnt == 1)
1034                 $o .= (($type === 'like') ? sprintf( t('%s likes this.'), $arr[0]) : sprintf( t('%s doesn\'t like this.'), $arr[0])) . EOL ;
1035         else {
1036                 $spanatts = 'class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');"';
1037                 $o .= (($type === 'like') ? 
1038                                         sprintf( t('<span  %1$s>%2$d people</span> like this.'), $spanatts, $cnt)
1039                                          : 
1040                                         sprintf( t('<span  %1$s>%2$d people</span> don\'t like this.'), $spanatts, $cnt) ); 
1041                 $o .= EOL ;
1042                 $total = count($arr);
1043                 if($total >= MAX_LIKERS)
1044                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1045                 if($total < MAX_LIKERS)
1046                         $arr[count($arr)-1] = t('and') . ' ' . $arr[count($arr)-1];
1047                 $str = implode(', ', $arr);
1048                 if($total >= MAX_LIKERS)
1049                         $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
1050                 $str = (($type === 'like') ? sprintf( t('%s like this.'), $str) : sprintf( t('%s don\'t like this.'), $str));
1051                 $o .= "\t" . '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
1052         }
1053         return $o;
1054 }}
1055
1056
1057 function status_editor($a,$x, $notes_cid = 0, $popup=false) {
1058
1059         $o = '';
1060                 
1061         $geotag = (($x['allow_location']) ? get_markup_template('jot_geotag.tpl') : '');
1062
1063         $plaintext = false;
1064         if(local_user() && intval(get_pconfig(local_user(),'system','plaintext')))
1065                 $plaintext = true;
1066
1067         $tpl = get_markup_template('jot-header.tpl');
1068         $a->page['htmlhead'] .= replace_macros($tpl, array(
1069                 '$newpost' => 'true',
1070                 '$baseurl' => $a->get_baseurl(true),
1071                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
1072                 '$geotag' => $geotag,
1073                 '$nickname' => $x['nickname'],
1074                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1075                 '$linkurl' => t('Please enter a link URL:'),
1076                 '$vidurl' => t("Please enter a video link/URL:"),
1077                 '$audurl' => t("Please enter an audio link/URL:"),
1078                 '$term' => t('Tag term:'),
1079                 '$fileas' => t('Save to Folder:'),
1080                 '$whereareu' => t('Where are you right now?')
1081         ));
1082
1083
1084         $tpl = get_markup_template('jot-end.tpl');
1085         $a->page['end'] .= replace_macros($tpl, array(
1086                 '$newpost' => 'true',
1087                 '$baseurl' => $a->get_baseurl(true),
1088                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
1089                 '$geotag' => $geotag,
1090                 '$nickname' => $x['nickname'],
1091                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1092                 '$linkurl' => t('Please enter a link URL:'),
1093                 '$vidurl' => t("Please enter a video link/URL:"),
1094                 '$audurl' => t("Please enter an audio link/URL:"),
1095                 '$term' => t('Tag term:'),
1096                 '$fileas' => t('Save to Folder:'),
1097                 '$whereareu' => t('Where are you right now?')
1098         ));
1099
1100
1101         $tpl = get_markup_template("jot.tpl");
1102                 
1103         $jotplugins = '';
1104         $jotnets = '';
1105
1106         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
1107
1108         $mail_enabled = false;
1109         $pubmail_enabled = false;
1110
1111         if(($x['is_owner']) && (! $mail_disabled)) {
1112                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
1113                         intval(local_user())
1114                 );
1115                 if(count($r)) {
1116                         $mail_enabled = true;
1117                         if(intval($r[0]['pubmail']))
1118                                 $pubmail_enabled = true;
1119                 }
1120         }
1121
1122         if($mail_enabled) {
1123                 $selected = (($pubmail_enabled) ? ' checked="checked" ' : '');
1124                 $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . t("Post to Email") . '</div>';
1125         }
1126
1127         call_hooks('jot_tool', $jotplugins);
1128         call_hooks('jot_networks', $jotnets);
1129
1130         if($notes_cid)
1131                 $jotnets .= '<input type="hidden" name="contact_allow[]" value="' . $notes_cid .'" />';
1132
1133         $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));        
1134
1135         $o .= replace_macros($tpl,array(
1136                 '$return_path' => $a->query_string,
1137                 '$action' =>  $a->get_baseurl(true) . '/item',
1138                 '$share' => (x($x,'button') ? $x['button'] : t('Share')),
1139                 '$upload' => t('Upload photo'),
1140                 '$shortupload' => t('upload photo'),
1141                 '$attach' => t('Attach file'),
1142                 '$shortattach' => t('attach file'),
1143                 '$weblink' => t('Insert web link'),
1144                 '$shortweblink' => t('web link'),
1145                 '$video' => t('Insert video link'),
1146                 '$shortvideo' => t('video link'),
1147                 '$audio' => t('Insert audio link'),
1148                 '$shortaudio' => t('audio link'),
1149                 '$setloc' => t('Set your location'),
1150                 '$shortsetloc' => t('set location'),
1151                 '$noloc' => t('Clear browser location'),
1152                 '$shortnoloc' => t('clear location'),
1153                 '$title' => "",
1154                 '$placeholdertitle' => t('Set title'),
1155                 '$category' => "",
1156                 '$placeholdercategory' => t('Categories (comma-separated list)'),
1157                 '$wait' => t('Please wait'),
1158                 '$permset' => t('Permission settings'),
1159                 '$shortpermset' => t('permissions'),
1160                 '$ptyp' => (($notes_cid) ? 'note' : 'wall'),
1161                 '$content' => '',
1162                 '$post_id' => '',
1163                 '$baseurl' => $a->get_baseurl(true),
1164                 '$defloc' => $x['default_location'],
1165                 '$visitor' => $x['visitor'],
1166                 '$pvisit' => (($notes_cid) ? 'none' : $x['visitor']),
1167                 '$emailcc' => t('CC: email addresses'),
1168                 '$public' => t('Public post'),
1169                 '$jotnets' => $jotnets,
1170                 '$emtitle' => t('Example: bob@example.com, mary@example.com'),
1171                 '$lockstate' => $x['lockstate'],
1172                 '$acl' => $x['acl'],
1173                 '$bang' => $x['bang'],
1174                 '$profile_uid' => $x['profile_uid'],
1175                 '$preview' => t('Preview'),
1176                 '$sourceapp' => t($a->sourcename),
1177         ));
1178
1179
1180         if ($popup==true){
1181                 $o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
1182                 
1183         }
1184
1185         return $o;
1186 }
1187
1188
1189 function get_item_children($arr, $parent) {
1190         $children = array();
1191         foreach($arr as $item) {
1192                 if($item['id'] != $item['parent']) {
1193                         if(get_config('system','thread_allow')) {
1194                                 // Fallback to parent-uri if thr-parent is not set
1195                                 $thr_parent = $item['thr-parent'];
1196                                 if($thr_parent == '')
1197                                         $thr_parent = $item['parent-uri'];
1198                                 
1199                                 if($thr_parent == $parent['uri']) {
1200                                         $item['children'] = get_item_children($arr, $item);
1201                                         $children[] = $item;
1202                                 }
1203                         }
1204                         else if($item['parent'] == $parent['id']) {
1205                                 $children[] = $item;
1206                         }
1207                 }
1208         }
1209         return $children;
1210 }
1211
1212 function sort_item_children($items) {
1213         $result = $items;
1214         usort($result,'sort_thr_created_rev');
1215         foreach($result as $k => $i) {
1216                 if(count($result[$k]['children'])) {
1217                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1218                 }
1219         }
1220         return $result;
1221 }
1222
1223 function add_children_to_list($children, &$arr) {
1224         foreach($children as $y) {
1225                 $arr[] = $y;
1226                 if(count($y['children']))
1227                         add_children_to_list($y['children'], $arr);
1228         }
1229 }
1230
1231 function conv_sort($arr,$order) {
1232
1233         if((!(is_array($arr) && count($arr))))
1234                 return array();
1235
1236         $parents = array();
1237         $children = array();
1238
1239         foreach($arr as $x)
1240                 if($x['id'] == $x['parent'])
1241                                 $parents[] = $x;
1242
1243         if(stristr($order,'created'))
1244                 usort($parents,'sort_thr_created');
1245         elseif(stristr($order,'commented'))
1246                 usort($parents,'sort_thr_commented');
1247
1248         if(count($parents))
1249                 foreach($parents as $i=>$_x) 
1250                         $parents[$i]['children'] = get_item_children($arr, $_x);
1251
1252         /*foreach($arr as $x) {
1253                 if($x['id'] != $x['parent']) {
1254                         $p = find_thread_parent_index($parents,$x);
1255                         if($p !== false)
1256                                 $parents[$p]['children'][] = $x;
1257                 }
1258         }*/
1259         if(count($parents)) {
1260                 foreach($parents as $k => $v) {
1261                         if(count($parents[$k]['children'])) {
1262                                 $parents[$k]['children'] = sort_item_children($parents[$k]['children']);
1263                                 /*$y = $parents[$k]['children'];
1264                                 usort($y,'sort_thr_created_rev');
1265                                 $parents[$k]['children'] = $y;*/
1266                         }
1267                 }       
1268         }
1269
1270         $ret = array();
1271         if(count($parents)) {
1272                 foreach($parents as $x) {
1273                         $ret[] = $x;
1274                         if(count($x['children']))
1275                                 add_children_to_list($x['children'], $ret);
1276                                 /*foreach($x['children'] as $y)
1277                                         $ret[] = $y;*/
1278                 }
1279         }
1280
1281         return $ret;
1282 }
1283
1284
1285 function sort_thr_created($a,$b) {
1286         return strcmp($b['created'],$a['created']);
1287 }
1288
1289 function sort_thr_created_rev($a,$b) {
1290         return strcmp($a['created'],$b['created']);
1291 }
1292
1293 function sort_thr_commented($a,$b) {
1294         return strcmp($b['commented'],$a['commented']);
1295 }
1296
1297 function find_thread_parent_index($arr,$x) {
1298         foreach($arr as $k => $v)
1299                 if($v['id'] == $x['parent'])
1300                         return $k;
1301         return false;
1302 }
1303
1304 function render_location_google($item) {
1305         $location = (($item['location']) ? '<a target="map" title="' . $item['location'] . '" href="http://maps.google.com/?q=' . urlencode($item['location']) . '">' . $item['location'] . '</a>' : '');
1306         $coord = (($item['coord']) ? '<a target="map" title="' . $item['coord'] . '" href="http://maps.google.com/?q=' . urlencode($item['coord']) . '">' . $item['coord'] . '</a>' : '');
1307         if($coord) {
1308                 if($location)
1309                         $location .= '<br /><span class="smalltext">(' . $coord . ')</span>';
1310                 else
1311                         $location = '<span class="smalltext">' . $coord . '</span>';
1312         }
1313         return $location;
1314 }