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