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