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