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