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