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