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