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