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