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