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