]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
Rendering is now done by Item objects
[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                         $total += count_descendants($child);
311                 }
312         }
313
314         return $total;
315 }
316
317 /**
318  * Recursively prepare a thread for HTML
319  */
320
321 function prepare_threads_body($a, $items, $cmnt_tpl, $page_writeable, $mode, $profile_owner, $thread_level=1) {
322         $result = array();
323
324         $wall_template = 'wall_thread.tpl';
325         $wallwall_template = 'wallwall_thread.tpl';
326         $items_seen = 0;
327         $nb_items = count($items);
328         
329         $total_children = $nb_items;
330         
331         foreach($items as $item) {
332                 // prevent private email reply to public conversation from leaking.
333                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
334                         // Don't count it as a visible item
335                         $nb_items--;
336                         continue;
337                 }
338                 
339                 $items_seen++;
340                 
341                 $alike = array();
342                 $dlike = array();
343                 $comment = '';
344                 $template = $wall_template;
345                 $commentww = '';
346                 $sparkle = '';
347                 $owner_url = $owner_photo = $owner_name = '';
348                 $buttons = '';
349                 $dropping = false;
350                 $star = false;
351                 $isstarred = "unstarred";
352                 $photo = $item['photo'];
353                 $thumb = $item['thumb'];
354                 $indent = '';
355                 $osparkle = '';
356                 $lastcollapsed = false;
357                 $firstcollapsed = false;
358                 $total_children += count_descendants($item);
359
360                 $toplevelpost = (($item['id'] == $item['parent']) ? true : false);
361                 $item_writeable = (($item['writable'] || $item['self']) ? true : false);
362                 $show_comment_box = ((($page_writeable) && ($item_writeable)) ? true : false);
363                 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid']) 
364                         || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
365                         ? t('Private Message')
366                         : false);
367                 $redirect_url = $a->get_baseurl($ssl_state) . '/redir/' . $item['cid'] ;
368                 $shareable = ((($profile_owner == local_user()) && ($item['private'] != 1)) ? true : false);
369                 if(local_user() && link_compare($a->contact['url'],$item['author-link']))
370                         $edpost = array($a->get_baseurl($ssl_state)."/editpost/".$item['id'], t("Edit"));
371                 else
372                         $edpost = false;
373                 if((intval($item['contact-id']) && $item['contact-id'] == remote_user()) || ($item['uid'] == local_user()))
374                         $dropping = true;
375
376                 $drop = array(
377                         'dropping' => $dropping,
378                         'select' => t('Select'), 
379                         'delete' => t('Delete'),
380                 );
381                 
382                 $filer = (($profile_owner == local_user()) ? t("save to folder") : false);
383
384                 $diff_author    = ((link_compare($item['url'],$item['author-link'])) ? false : true);
385                 $profile_name   = (((strlen($item['author-name']))   && $diff_author) ? $item['author-name']   : $item['name']);
386                 if($item['author-link'] && (! $item['author-name']))
387                         $profile_name = $item['author-link'];
388
389                 $sp = false;
390                 $profile_link = best_link_url($item,$sp);
391                 if($profile_link === 'mailbox')
392                         $profile_link = '';
393                 if($sp)
394                         $sparkle = ' sparkle';
395                 else
396                         $profile_link = zrl($profile_link);                                     
397
398                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
399                 if(($normalised != 'mailbox') && (x($a->contacts,$normalised)))
400                         $profile_avatar = $a->contacts[$normalised]['thumb'];
401                 else
402                         $profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $a->get_cached_avatar_image($thumb));
403
404                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
405                 call_hooks('render_location',$locate);
406                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
407
408                 $tags=array();
409                 foreach(explode(',',$item['tag']) as $tag){
410                         $tag = trim($tag);
411                         if ($tag!="") $tags[] = bbcode($tag);
412                 }
413                 
414                 like_puller($a,$item,$alike,'like');
415                 like_puller($a,$item,$dlike,'dislike');
416
417                 $like    = ((x($alike,$item['uri'])) ? format_like($alike[$item['uri']],$alike[$item['uri'] . '-l'],'like',$item['uri']) : '');
418                 $dislike = ((x($dlike,$item['uri'])) ? format_like($dlike[$item['uri']],$dlike[$item['uri'] . '-l'],'dislike',$item['uri']) : '');
419
420                 if($toplevelpost) {
421                         if((! $item['self']) && ($mode !== 'profile')) {
422                                 if($item['wall']) {
423
424                                         // On the network page, I am the owner. On the display page it will be the profile owner.
425                                         // This will have been stored in $a->page_contact by our calling page.
426                                         // Put this person as the wall owner of the wall-to-wall notice.
427
428                                         $owner_url = zrl($a->page_contact['url']);
429                                         $owner_photo = $a->page_contact['thumb'];
430                                         $owner_name = $a->page_contact['name'];
431                                         $template = $wallwall_template;
432                                         $commentww = 'ww';      
433                                 }
434                         }
435                         else if($item['owner-link']) {
436
437                                 $owner_linkmatch = (($item['owner-link']) && link_compare($item['owner-link'],$item['author-link']));
438                                 $alias_linkmatch = (($item['alias']) && link_compare($item['alias'],$item['author-link']));
439                                 $owner_namematch = (($item['owner-name']) && $item['owner-name'] == $item['author-name']);
440                                 if((! $owner_linkmatch) && (! $alias_linkmatch) && (! $owner_namematch)) {
441
442                                         // The author url doesn't match the owner (typically the contact)
443                                         // and also doesn't match the contact alias. 
444                                         // The name match is a hack to catch several weird cases where URLs are 
445                                         // all over the park. It can be tricked, but this prevents you from
446                                         // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
447                                         // well that it's the same Bob Smith. 
448
449                                         // But it could be somebody else with the same name. It just isn't highly likely. 
450                                         
451
452                                         $owner_url = $item['owner-link'];
453                                         $owner_photo = $item['owner-avatar'];
454                                         $owner_name = $item['owner-name'];
455                                         $template = $wallwall_template;
456                                         $commentww = 'ww';
457                                         // If it is our contact, use a friendly redirect link
458                                         if((link_compare($item['owner-link'],$item['url'])) 
459                                                 && ($item['network'] === NETWORK_DFRN)) {
460                                                 $owner_url = $redirect_url;
461                                                 $osparkle = ' sparkle';
462                                         }
463                                         else
464                                                 $owner_url = zrl($owner_url);
465                                 }
466                         }
467                         if($profile_owner == local_user()) {
468                                 $isstarred = (($item['starred']) ? "starred" : "unstarred");
469
470                                 $star = array(
471                                         'do' => t("add star"),
472                                         'undo' => t("remove star"),
473                                         'toggle' => t("toggle star status"),
474                                         'classdo' => (($item['starred']) ? "hidden" : ""),
475                                         'classundo' => (($item['starred']) ? "" : "hidden"),
476                                         'starred' =>  t('starred'),
477                                         'tagger' => t("add tag"),
478                                         'classtagger' => "",
479                                 );
480                         }
481                 } else {
482                         $indent = 'comment';
483                         // Collapse comments
484                         if(($nb_items > 2) || ($thread_level > 2)) {
485                                 if($items_seen == 1) {
486                                         $firstcollapsed = true;
487                                 }
488                                 if($thread_level > 2) {
489                                         if($items_seen == $nb_items)
490                                                 $lastcollapsed = true;
491                                 }
492                                 else if($items_seen == ($nb_items - 2)) {
493                                         $lastcollapsed = true;
494                                 }
495                         }
496                 }
497
498                 if($page_writeable) {
499                         $buttons = array(
500                                 'like' => array( t("I like this \x28toggle\x29"), t("like")),
501                                 'dislike' => array( t("I don't like this \x28toggle\x29"), t("dislike")),
502                         );
503                         if ($shareable) $buttons['share'] = array( t('Share this'), t('share'));
504
505
506                         if($show_comment_box) {
507                                 $qc = $qcomment =  null;
508
509                                 if(in_array('qcomment',$a->plugins)) {
510                                         $qc = ((local_user()) ? get_pconfig(local_user(),'qcomment','words') : null);
511                                         $qcomment = (($qc) ? explode("\n",$qc) : null);
512                                 }
513                                 $comment = replace_macros($cmnt_tpl,array(
514                                         '$return_path' => '', 
515                                         '$jsreload' => (($mode === 'display') ? $_SESSION['return_url'] : ''),
516                                         '$type' => (($mode === 'profile') ? 'wall-comment' : 'net-comment'),
517                                         '$id' => $item['item_id'],
518                                         '$parent' => $item['item_id'],
519                                         '$qcomment' => $qcomment,
520                                         '$profile_uid' =>  $profile_owner,
521                                         '$mylink' => $a->contact['url'],
522                                         '$mytitle' => t('This is you'),
523                                         '$myphoto' => $a->contact['thumb'],
524                                         '$comment' => t('Comment'),
525                                         '$submit' => t('Submit'),
526                                         '$edbold' => t('Bold'),
527                                         '$editalic' => t('Italic'),
528                                         '$eduline' => t('Underline'),
529                                         '$edquote' => t('Quote'),
530                                         '$edcode' => t('Code'),
531                                         '$edimg' => t('Image'),
532                                         '$edurl' => t('Link'),
533                                         '$edvideo' => t('Video'),
534                                         '$preview' => t('Preview'),
535                                         '$sourceapp' => t($a->sourcename),
536                                         '$ww' => (($mode === 'network') ? $commentww : '')
537                                 ));
538                         }
539                 }
540
541                 if(strcmp(datetime_convert('UTC','UTC',$item['created']),datetime_convert('UTC','UTC','now - 12 hours')) > 0)
542                         $indent .= ' shiny';
543
544                 localize_item($item);
545
546                 $body = prepare_body($item,true);
547
548                 $tmp_item = array(
549                         // collapse comments in template. I don't like this much...
550                         'comment_firstcollapsed' => $firstcollapsed,
551                         'comment_lastcollapsed' => $lastcollapsed,
552                         // template to use to render item (wall, walltowall, search)
553                         'template' => $template,
554                         
555                         'type' => implode("",array_slice(explode("/",$item['verb']),-1)),
556                         'tags' => $tags,
557                         'body' => template_escape($body),
558                         'text' => strip_tags(template_escape($body)),
559                         'id' => $item['item_id'],
560                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
561                         'olinktitle' => sprintf( t('View %s\'s profile @ %s'), $owner_name, ((strlen($item['owner-link'])) ? $item['owner-link'] : $item['url'])),
562                         'to' => t('to'),
563                         'wall' => t('Wall-to-Wall'),
564                         'vwall' => t('via Wall-To-Wall:'),
565                         'profile_url' => $profile_link,
566                         'item_photo_menu' => item_photo_menu($item),
567                         'name' => template_escape($profile_name),
568                         'thumb' => $profile_avatar,
569                         'osparkle' => $osparkle,
570                         'sparkle' => $sparkle,
571                         'title' => template_escape($item['title']),
572                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
573                         'lock' => $lock,
574                         'location' => template_escape($location),
575                         'indent' => $indent,
576                         'owner_url' => $owner_url,
577                         'owner_photo' => $owner_photo,
578                         'owner_name' => template_escape($owner_name),
579                         'plink' => get_plink($item),
580                         'edpost' => $edpost,
581                         'isstarred' => $isstarred,
582                         'star' => $star,
583                         'filer' => $filer,
584                         'drop' => $drop,
585                         'vote' => $buttons,
586                         'like' => $like,
587                         'dislike' => $dislike,
588                         'comment' => $comment,
589                         'previewing' => $previewing,
590                         'wait' => t('Please wait'),
591                 );
592
593                 $arr = array('item' => $item, 'output' => $tmp_item);
594                 call_hooks('display_item', $arr);
595
596                 $item_result = $arr['output'];
597                 if($firstcollapsed) {
598                         $item_result['num_comments'] = sprintf( tt('%d comment','%d comments',$total_children),$total_children );
599                         $item_result['hide_text'] = t('show more');
600                 }
601
602                 $item_result['children'] = array();
603                 if(count($item['children'])) {
604                         $item_result['children'] = prepare_threads_body($a, $item['children'], $cmnt_tpl, $page_writeable, $mode, $profile_owner, ($thread_level + 1));
605                 }
606                 $item_result['private'] = $item['private'];
607                 $item_result['toplevel'] = ($toplevelpost ? 'toplevel_item' : '');
608
609                 /*
610                  * I don't like this very much...
611                  */
612                 if(get_config('system','thread_allow')) {
613                         $item_result['flatten'] = false;
614                         $item_result['threaded'] = true;
615                 }
616                 else {
617                         $item_result['flatten'] = true;
618                         $item_result['threaded'] = false;
619                         if(!$toplevelpost) {
620                                 $item_result['comment'] = false;
621                         }
622                 }
623                 
624                 $result[] = $item_result;
625         }
626
627         return $result;
628 }
629
630 /**
631  * "Render" a conversation or list of items for HTML display.
632  * There are two major forms of display:
633  *      - Sequential or unthreaded ("New Item View" or search results)
634  *      - conversation view
635  * The $mode parameter decides between the various renderings and also
636  * figures out how to determine page owner and other contextual items 
637  * that are based on unique features of the calling module.
638  *
639  */
640
641 if(!function_exists('conversation')) {
642 function conversation(&$a, $items, $mode, $update, $preview = false) {
643
644
645         require_once('bbcode.php');
646
647         $ssl_state = ((local_user()) ? true : false);
648
649         $profile_owner = 0;
650         $page_writeable      = false;
651
652         $previewing = (($preview) ? ' preview ' : '');
653
654         if($mode === 'network') {
655                 $profile_owner = local_user();
656                 $page_writeable = true;
657         }
658
659         if($mode === 'profile') {
660                 $profile_owner = $a->profile['profile_uid'];
661                 $page_writeable = can_write_wall($a,$profile_owner);
662         }
663
664         if($mode === 'notes') {
665                 $profile_owner = local_user();
666                 $page_writeable = true;
667         }
668
669         if($mode === 'display') {
670                 $profile_owner = $a->profile['uid'];
671                 $page_writeable = can_write_wall($a,$profile_owner);
672         }
673
674         if($mode === 'community') {
675                 $profile_owner = 0;
676                 $page_writeable = false;
677         }
678
679         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
680
681
682         if($update)
683                 $return_url = $_SESSION['return_url'];
684         else
685                 $return_url = $_SESSION['return_url'] = $a->query_string;
686
687         load_contact_links(local_user());
688
689         $cb = array('items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview);
690         call_hooks('conversation_start',$cb);
691
692         $items = $cb['items'];
693
694         $cmnt_tpl    = get_markup_template('comment_item.tpl');
695         $tpl         = 'wall_item.tpl';
696         $wallwall    = 'wallwall_item.tpl';
697         $hide_comments_tpl = get_markup_template('hide_comments.tpl');
698
699         $alike = array();
700         $dlike = array();
701         
702         
703         // array with html for each thread (parent+comments)
704         $threads = array();
705         $threadsid = -1;
706
707         $page_template = get_markup_template("conversation.tpl");
708                 
709         if($items && count($items)) {
710
711                 if($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
712
713                         // "New Item View" on network page or search page results 
714                         // - just loop through the items and format them minimally for display
715
716                         //$tpl = get_markup_template('search_item.tpl');
717                         $tpl = 'search_item.tpl';
718
719                         foreach($items as $item) {
720                                 $threadsid++;
721
722                                 $comment     = '';
723                                 $owner_url   = '';
724                                 $owner_photo = '';
725                                 $owner_name  = '';
726                                 $sparkle     = '';
727
728                                 if($mode === 'search' || $mode === 'community') {
729                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) 
730                                                 && ($item['id'] != $item['parent']))
731                                                 continue;
732                                         $nickname = $item['nickname'];
733                                 }
734                                 else
735                                         $nickname = $a->user['nickname'];
736                                 
737                                 // prevent private email from leaking.
738                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
739                                                 continue;
740                         
741                                 $profile_name   = ((strlen($item['author-name']))   ? $item['author-name']   : $item['name']);
742                                 if($item['author-link'] && (! $item['author-name']))
743                                         $profile_name = $item['author-link'];
744
745
746
747                                 $sp = false;
748                                 $profile_link = best_link_url($item,$sp);
749                                 if($profile_link === 'mailbox')
750                                         $profile_link = '';
751                                 if($sp)
752                                         $sparkle = ' sparkle';
753                                 else
754                                         $profile_link = zrl($profile_link);                                     
755
756                                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
757                                 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
758                                         $profile_avatar = $a->contacts[$normalised]['thumb'];
759                                 else
760                                         $profile_avatar = ((strlen($item['author-avatar'])) ? $a->get_cached_avatar_image($item['author-avatar']) : $item['thumb']);
761
762                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
763                                 call_hooks('render_location',$locate);
764
765                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
766
767                                 localize_item($item);
768                                 if($mode === 'network-new')
769                                         $dropping = true;
770                                 else
771                                         $dropping = false;
772
773
774                                 $drop = array(
775                                         'dropping' => $dropping,
776                                         'select' => t('Select'), 
777                                         'delete' => t('Delete'),
778                                 );
779
780                                 $star = false;
781                                 $isstarred = "unstarred";
782                                 
783                                 $lock = false;
784                                 $likebuttons = false;
785                                 $shareable = false;
786
787                                 $body = prepare_body($item,true);
788                                 
789                                 //$tmp_item = replace_macros($tpl,array(
790                                 $tmp_item = array(
791                                         'template' => $tpl,
792                                         'id' => (($preview) ? 'P0' : $item['item_id']),
793                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
794                                         'profile_url' => $profile_link,
795                                         'item_photo_menu' => item_photo_menu($item),
796                                         'name' => template_escape($profile_name),
797                                         'sparkle' => $sparkle,
798                                         'lock' => $lock,
799                                         'thumb' => $profile_avatar,
800                                         'title' => template_escape($item['title']),
801                                         'body' => template_escape($body),
802                                         'text' => strip_tags(template_escape($body)),
803                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
804                                         'location' => template_escape($location),
805                                         'indent' => '',
806                                         'owner_name' => template_escape($owner_name),
807                                         'owner_url' => $owner_url,
808                                         'owner_photo' => $owner_photo,
809                                         'plink' => get_plink($item),
810                                         'edpost' => false,
811                                         'isstarred' => $isstarred,
812                                         'star' => $star,
813                                         'drop' => $drop,
814                                         'vote' => $likebuttons,
815                                         'like' => '',
816                                         'dislike' => '',
817                                         'comment' => '',
818                                         'conv' => (($preview) ? '' : array('href'=> $a->get_baseurl($ssl_state) . '/display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
819                                         'previewing' => $previewing,
820                                         'wait' => t('Please wait'),
821                                 );
822
823                                 $arr = array('item' => $item, 'output' => $tmp_item);
824                                 call_hooks('display_item', $arr);
825
826                                 $threads[$threadsid]['id'] = $item['item_id'];
827                                 $threads[$threadsid]['items'] = array($arr['output']);
828
829                         }
830
831                 }
832                 else
833                 {
834                         // Normal View
835                         $page_template = get_markup_template("threaded_conversation.tpl");
836
837                         require_once('object/Conversation.php');
838                         require_once('object/Item.php');
839
840                         $conv = new Conversation($mode);
841
842                         // get all the topmost parents
843                         // this shouldn't be needed, as we should have only them in our array
844                         // But for now, this array respects the old style, just in case
845
846                         $threads = array();
847                         foreach($items as $item) {
848                                 if($item['id'] == $item['parent']) {
849                                         // $threads[] = $item;
850                                         $item_object = new Item($item);
851                                         $conv->add_thread($item_object);
852                                 }
853                         }
854
855                         //$threads = prepare_threads_body($a, $threads, $cmnt_tpl, $page_writeable, $mode, $profile_owner);
856                         $threads = $conv->get_template_data($cmnt_tpl);
857                         if(!$threads) {
858                                 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
859                                 $threads = array();
860                         }
861                         logger('[DEBUG] conversation : $threads = '. print_r($threads, true), LOGGER_DEBUG);
862                 }
863         }
864                 
865         $o = replace_macros($page_template, array(
866                 '$baseurl' => $a->get_baseurl($ssl_state),
867                 '$mode' => $mode,
868                 '$user' => $a->user,
869                 '$threads' => $threads,
870                 '$dropping' => ($page_dropping?t('Delete Selected Items'):False),
871         ));
872
873         return $o;
874 }}
875
876 function best_link_url($item,&$sparkle,$ssl_state = false) {
877
878         $a = get_app();
879
880         $best_url = '';
881         $sparkle  = false;
882
883         $clean_url = normalise_link($item['author-link']);
884
885         if((local_user()) && (local_user() == $item['uid'])) {
886                 if(isset($a->contacts) && x($a->contacts,$clean_url)) {
887                         if($a->contacts[$clean_url]['network'] === NETWORK_DFRN) {
888                                 $best_url = $a->get_baseurl($ssl_state) . '/redir/' . $a->contacts[$clean_url]['id'];
889                                 $sparkle = true;
890                         }
891                         else
892                                 $best_url = $a->contacts[$clean_url]['url'];
893                 }
894         }
895         if(! $best_url) {
896                 if(strlen($item['author-link']))
897                         $best_url = $item['author-link'];
898                 else
899                         $best_url = $item['url'];
900         }
901
902         return $best_url;
903 }
904
905
906 if(! function_exists('item_photo_menu')){
907 function item_photo_menu($item){
908         $a = get_app();
909
910         $ssl_state = false;
911
912         if(local_user()) {
913                 $ssl_state = true;
914                  if(! count($a->contacts))
915                         load_contact_links(local_user());
916         }
917         $poke_link="";
918         $contact_url="";
919         $pm_url="";
920         $status_link="";
921         $photos_link="";
922         $posts_link="";
923
924         $sparkle = false;
925     $profile_link = best_link_url($item,$sparkle,$ssl_state);
926         if($profile_link === 'mailbox')
927                 $profile_link = '';
928
929         if($sparkle) {
930                 $cid = intval(basename($profile_link));
931                 $status_link = $profile_link . "?url=status";
932                 $photos_link = $profile_link . "?url=photos";
933                 $profile_link = $profile_link . "?url=profile";
934                 $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
935                 $zurl = '';
936         }
937         else {
938                 $profile_link = zrl($profile_link);
939                 if(local_user() && local_user() == $item['uid'] && link_compare($item['url'],$item['author-link'])) {
940                         $cid = $item['contact-id'];
941                 }               
942                 else {
943                         $cid = 0;
944                 }
945         }
946         if(($cid) && (! $item['self'])) {
947                 $poke_link = $a->get_baseurl($ssl_state) . '/poke/?f=&c=' . $cid;
948                 $contact_url = $a->get_baseurl($ssl_state) . '/contacts/' . $cid;
949                 $posts_link = $a->get_baseurl($ssl_state) . '/network/?cid=' . $cid;
950
951                 $clean_url = normalise_link($item['author-link']);
952
953                 if((local_user()) && (local_user() == $item['uid'])) {
954                         if(isset($a->contacts) && x($a->contacts,$clean_url)) {
955                                 if($a->contacts[$clean_url]['network'] === NETWORK_DIASPORA) {
956                                         $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
957                                 }
958                         }
959                 }
960
961         }
962
963         $menu = Array(
964                 t("View Status") => $status_link,
965                 t("View Profile") => $profile_link,
966                 t("View Photos") => $photos_link,
967                 t("Network Posts") => $posts_link, 
968                 t("Edit Contact") => $contact_url,
969                 t("Send PM") => $pm_url,
970                 t("Poke") => $poke_link
971         );
972         
973         
974         $args = array('item' => $item, 'menu' => $menu);
975         
976         call_hooks('item_photo_menu', $args);
977
978         $menu = $args['menu'];  
979
980         $o = "";
981         foreach($menu as $k=>$v){
982                 if ($v!="") $o .= "<li><a href=\"$v\">$k</a></li>\n";
983         }
984         return $o;
985 }}
986
987 if(! function_exists('like_puller')) {
988 function like_puller($a,$item,&$arr,$mode) {
989
990         $url = '';
991         $sparkle = '';
992         $verb = (($mode === 'like') ? ACTIVITY_LIKE : ACTIVITY_DISLIKE);
993
994         if((activity_match($item['verb'],$verb)) && ($item['id'] != $item['parent'])) {
995                 $url = $item['author-link'];
996                 if((local_user()) && (local_user() == $item['uid']) && ($item['network'] === 'dfrn') && (! $item['self']) && (link_compare($item['author-link'],$item['url']))) {
997                         $url = $a->get_baseurl(true) . '/redir/' . $item['contact-id'];
998                         $sparkle = ' class="sparkle" ';
999                 }
1000                 else
1001                         $url = zrl($url);
1002
1003                 if(! $item['thr-parent'])
1004                         $item['thr-parent'] = $item['parent-uri'];
1005
1006                 if(! ((isset($arr[$item['thr-parent'] . '-l'])) && (is_array($arr[$item['thr-parent'] . '-l']))))
1007                         $arr[$item['thr-parent'] . '-l'] = array();
1008                 if(! isset($arr[$item['thr-parent']]))
1009                         $arr[$item['thr-parent']] = 1;
1010                 else    
1011                         $arr[$item['thr-parent']] ++;
1012                 $arr[$item['thr-parent'] . '-l'][] = '<a href="'. $url . '"'. $sparkle .'>' . $item['author-name'] . '</a>';
1013         }
1014         return;
1015 }}
1016
1017 // Format the like/dislike text for a profile item
1018 // $cnt = number of people who like/dislike the item
1019 // $arr = array of pre-linked names of likers/dislikers
1020 // $type = one of 'like, 'dislike'
1021 // $id  = item id
1022 // returns formatted text
1023
1024 if(! function_exists('format_like')) {
1025 function format_like($cnt,$arr,$type,$id) {
1026         $o = '';
1027         if($cnt == 1)
1028                 $o .= (($type === 'like') ? sprintf( t('%s likes this.'), $arr[0]) : sprintf( t('%s doesn\'t like this.'), $arr[0])) . EOL ;
1029         else {
1030                 $spanatts = 'class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');"';
1031                 $o .= (($type === 'like') ? 
1032                                         sprintf( t('<span  %1$s>%2$d people</span> like this.'), $spanatts, $cnt)
1033                                          : 
1034                                         sprintf( t('<span  %1$s>%2$d people</span> don\'t like this.'), $spanatts, $cnt) ); 
1035                 $o .= EOL ;
1036                 $total = count($arr);
1037                 if($total >= MAX_LIKERS)
1038                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1039                 if($total < MAX_LIKERS)
1040                         $arr[count($arr)-1] = t('and') . ' ' . $arr[count($arr)-1];
1041                 $str = implode(', ', $arr);
1042                 if($total >= MAX_LIKERS)
1043                         $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
1044                 $str = (($type === 'like') ? sprintf( t('%s like this.'), $str) : sprintf( t('%s don\'t like this.'), $str));
1045                 $o .= "\t" . '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
1046         }
1047         return $o;
1048 }}
1049
1050
1051 function status_editor($a,$x, $notes_cid = 0, $popup=false) {
1052
1053         $o = '';
1054                 
1055         $geotag = (($x['allow_location']) ? get_markup_template('jot_geotag.tpl') : '');
1056
1057         $plaintext = false;
1058         if(local_user() && intval(get_pconfig(local_user(),'system','plaintext')))
1059                 $plaintext = true;
1060
1061         $tpl = get_markup_template('jot-header.tpl');
1062         $a->page['htmlhead'] .= replace_macros($tpl, array(
1063                 '$newpost' => 'true',
1064                 '$baseurl' => $a->get_baseurl(true),
1065                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
1066                 '$geotag' => $geotag,
1067                 '$nickname' => $x['nickname'],
1068                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1069                 '$linkurl' => t('Please enter a link URL:'),
1070                 '$vidurl' => t("Please enter a video link/URL:"),
1071                 '$audurl' => t("Please enter an audio link/URL:"),
1072                 '$term' => t('Tag term:'),
1073                 '$fileas' => t('Save to Folder:'),
1074                 '$whereareu' => t('Where are you right now?')
1075         ));
1076
1077
1078         $tpl = get_markup_template('jot-end.tpl');
1079         $a->page['end'] .= replace_macros($tpl, array(
1080                 '$newpost' => 'true',
1081                 '$baseurl' => $a->get_baseurl(true),
1082                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
1083                 '$geotag' => $geotag,
1084                 '$nickname' => $x['nickname'],
1085                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1086                 '$linkurl' => t('Please enter a link URL:'),
1087                 '$vidurl' => t("Please enter a video link/URL:"),
1088                 '$audurl' => t("Please enter an audio link/URL:"),
1089                 '$term' => t('Tag term:'),
1090                 '$fileas' => t('Save to Folder:'),
1091                 '$whereareu' => t('Where are you right now?')
1092         ));
1093
1094
1095         $tpl = get_markup_template("jot.tpl");
1096                 
1097         $jotplugins = '';
1098         $jotnets = '';
1099
1100         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
1101
1102         $mail_enabled = false;
1103         $pubmail_enabled = false;
1104
1105         if(($x['is_owner']) && (! $mail_disabled)) {
1106                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
1107                         intval(local_user())
1108                 );
1109                 if(count($r)) {
1110                         $mail_enabled = true;
1111                         if(intval($r[0]['pubmail']))
1112                                 $pubmail_enabled = true;
1113                 }
1114         }
1115
1116         if($mail_enabled) {
1117                 $selected = (($pubmail_enabled) ? ' checked="checked" ' : '');
1118                 $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . t("Post to Email") . '</div>';
1119         }
1120
1121         call_hooks('jot_tool', $jotplugins);
1122         call_hooks('jot_networks', $jotnets);
1123
1124         if($notes_cid)
1125                 $jotnets .= '<input type="hidden" name="contact_allow[]" value="' . $notes_cid .'" />';
1126
1127         $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));        
1128
1129         $o .= replace_macros($tpl,array(
1130                 '$return_path' => $a->query_string,
1131                 '$action' =>  $a->get_baseurl(true) . '/item',
1132                 '$share' => (x($x,'button') ? $x['button'] : t('Share')),
1133                 '$upload' => t('Upload photo'),
1134                 '$shortupload' => t('upload photo'),
1135                 '$attach' => t('Attach file'),
1136                 '$shortattach' => t('attach file'),
1137                 '$weblink' => t('Insert web link'),
1138                 '$shortweblink' => t('web link'),
1139                 '$video' => t('Insert video link'),
1140                 '$shortvideo' => t('video link'),
1141                 '$audio' => t('Insert audio link'),
1142                 '$shortaudio' => t('audio link'),
1143                 '$setloc' => t('Set your location'),
1144                 '$shortsetloc' => t('set location'),
1145                 '$noloc' => t('Clear browser location'),
1146                 '$shortnoloc' => t('clear location'),
1147                 '$title' => "",
1148                 '$placeholdertitle' => t('Set title'),
1149                 '$category' => "",
1150                 '$placeholdercategory' => t('Categories (comma-separated list)'),
1151                 '$wait' => t('Please wait'),
1152                 '$permset' => t('Permission settings'),
1153                 '$shortpermset' => t('permissions'),
1154                 '$ptyp' => (($notes_cid) ? 'note' : 'wall'),
1155                 '$content' => '',
1156                 '$post_id' => '',
1157                 '$baseurl' => $a->get_baseurl(true),
1158                 '$defloc' => $x['default_location'],
1159                 '$visitor' => $x['visitor'],
1160                 '$pvisit' => (($notes_cid) ? 'none' : $x['visitor']),
1161                 '$emailcc' => t('CC: email addresses'),
1162                 '$public' => t('Public post'),
1163                 '$jotnets' => $jotnets,
1164                 '$emtitle' => t('Example: bob@example.com, mary@example.com'),
1165                 '$lockstate' => $x['lockstate'],
1166                 '$acl' => $x['acl'],
1167                 '$bang' => $x['bang'],
1168                 '$profile_uid' => $x['profile_uid'],
1169                 '$preview' => t('Preview'),
1170                 '$sourceapp' => t($a->sourcename),
1171         ));
1172
1173
1174         if ($popup==true){
1175                 $o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
1176                 
1177         }
1178
1179         return $o;
1180 }
1181
1182
1183 function get_item_children($arr, $parent) {
1184         $children = array();
1185         foreach($arr as $item) {
1186                 if($item['id'] != $item['parent']) {
1187                         if(get_config('system','thread_allow')) {
1188                                 // Fallback to parent-uri if thr-parent is not set
1189                                 $thr_parent = $item['thr-parent'];
1190                                 if($thr_parent == '')
1191                                         $thr_parent = $item['parent-uri'];
1192                                 
1193                                 if($thr_parent == $parent['uri']) {
1194                                         $item['children'] = get_item_children($arr, $item);
1195                                         $children[] = $item;
1196                                 }
1197                         }
1198                         else if($item['parent'] == $parent['id']) {
1199                                 $children[] = $item;
1200                         }
1201                 }
1202         }
1203         return $children;
1204 }
1205
1206 function sort_item_children($items) {
1207         $result = $items;
1208         usort($result,'sort_thr_created_rev');
1209         foreach($result as $k => $i) {
1210                 if(count($result[$k]['children'])) {
1211                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1212                 }
1213         }
1214         return $result;
1215 }
1216
1217 function add_children_to_list($children, &$arr) {
1218         foreach($children as $y) {
1219                 $arr[] = $y;
1220                 if(count($y['children']))
1221                         add_children_to_list($y['children'], $arr);
1222         }
1223 }
1224
1225 function conv_sort($arr,$order) {
1226
1227         if((!(is_array($arr) && count($arr))))
1228                 return array();
1229
1230         $parents = array();
1231         $children = array();
1232
1233         foreach($arr as $x)
1234                 if($x['id'] == $x['parent'])
1235                                 $parents[] = $x;
1236
1237         if(stristr($order,'created'))
1238                 usort($parents,'sort_thr_created');
1239         elseif(stristr($order,'commented'))
1240                 usort($parents,'sort_thr_commented');
1241
1242         if(count($parents))
1243                 foreach($parents as $i=>$_x) 
1244                         $parents[$i]['children'] = get_item_children($arr, $_x);
1245
1246         /*foreach($arr as $x) {
1247                 if($x['id'] != $x['parent']) {
1248                         $p = find_thread_parent_index($parents,$x);
1249                         if($p !== false)
1250                                 $parents[$p]['children'][] = $x;
1251                 }
1252         }*/
1253         if(count($parents)) {
1254                 foreach($parents as $k => $v) {
1255                         if(count($parents[$k]['children'])) {
1256                                 $parents[$k]['children'] = sort_item_children($parents[$k]['children']);
1257                                 /*$y = $parents[$k]['children'];
1258                                 usort($y,'sort_thr_created_rev');
1259                                 $parents[$k]['children'] = $y;*/
1260                         }
1261                 }       
1262         }
1263
1264         $ret = array();
1265         if(count($parents)) {
1266                 foreach($parents as $x) {
1267                         $ret[] = $x;
1268                         if(count($x['children']))
1269                                 add_children_to_list($x['children'], $ret);
1270                                 /*foreach($x['children'] as $y)
1271                                         $ret[] = $y;*/
1272                 }
1273         }
1274
1275         return $ret;
1276 }
1277
1278
1279 function sort_thr_created($a,$b) {
1280         return strcmp($b['created'],$a['created']);
1281 }
1282
1283 function sort_thr_created_rev($a,$b) {
1284         return strcmp($a['created'],$b['created']);
1285 }
1286
1287 function sort_thr_commented($a,$b) {
1288         return strcmp($b['commented'],$a['commented']);
1289 }
1290
1291 function find_thread_parent_index($arr,$x) {
1292         foreach($arr as $k => $v)
1293                 if($v['id'] == $x['parent'])
1294                         return $k;
1295         return false;
1296 }
1297
1298 function render_location_google($item) {
1299         $location = (($item['location']) ? '<a target="map" title="' . $item['location'] . '" href="http://maps.google.com/?q=' . urlencode($item['location']) . '">' . $item['location'] . '</a>' : '');
1300         $coord = (($item['coord']) ? '<a target="map" title="' . $item['coord'] . '" href="http://maps.google.com/?q=' . urlencode($item['coord']) . '">' . $item['coord'] . '</a>' : '');
1301         if($coord) {
1302                 if($location)
1303                         $location .= '<br /><span class="smalltext">(' . $coord . ')</span>';
1304                 else
1305                         $location = '<span class="smalltext">' . $coord . '</span>';
1306         }
1307         return $location;
1308 }