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