]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
e4f3ec9ff63a8c1932e766c78cc24e6ad351cfcd
[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($item['verb'],ACTIVITY_LIKE) || activity_match($item['verb'],ACTIVITY_DISLIKE))
345                 return false;
346
347         if(activity_match($item['verb'],ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE) {
348                 if(! (($item['self']) && ($item['uid'] == local_user()))) {
349                         return false;
350                 }
351         }
352
353         return true;
354 }
355
356
357 /**
358  * "Render" a conversation or list of items for HTML display.
359  * There are two major forms of display:
360  *      - Sequential or unthreaded ("New Item View" or search results)
361  *      - conversation view
362  * The $mode parameter decides between the various renderings and also
363  * figures out how to determine page owner and other contextual items
364  * that are based on unique features of the calling module.
365  *
366  */
367
368 if(!function_exists('conversation')) {
369 function conversation(&$a, $items, $mode, $update, $preview = false) {
370
371
372         require_once('bbcode.php');
373
374         $ssl_state = ((local_user()) ? true : false);
375
376         $profile_owner = 0;
377         $page_writeable = false;
378         $live_update_div = '';
379
380         $previewing = (($preview) ? ' preview ' : '');
381
382         if($mode === 'network') {
383                 $profile_owner = local_user();
384                 $page_writeable = true;
385                 if(!$update) {
386                         // The special div is needed for liveUpdate to kick in for this page.
387                         // We only launch liveUpdate if you aren't filtering in some incompatible 
388                         // way and also you aren't writing a comment (discovered in javascript).
389
390                         $live_update_div = '<div id="live-network"></div>' . "\r\n"
391                                 . "<script> var profile_uid = " . $_SESSION['uid'] 
392                                 . "; var netargs = '" . substr($a->cmd,8)
393                                 . '?f='
394                                 . ((x($_GET,'cid'))    ? '&cid='    . $_GET['cid']    : '')
395                                 . ((x($_GET,'search')) ? '&search=' . $_GET['search'] : '') 
396                                 . ((x($_GET,'star'))   ? '&star='   . $_GET['star']   : '') 
397                                 . ((x($_GET,'order'))  ? '&order='  . $_GET['order']  : '') 
398                                 . ((x($_GET,'bmark'))  ? '&bmark='  . $_GET['bmark']  : '') 
399                                 . ((x($_GET,'liked'))  ? '&liked='  . $_GET['liked']  : '') 
400                                 . ((x($_GET,'conv'))   ? '&conv='   . $_GET['conv']   : '') 
401                                 . ((x($_GET,'spam'))   ? '&spam='   . $_GET['spam']   : '') 
402                                 . ((x($_GET,'nets'))   ? '&nets='   . $_GET['nets']   : '') 
403                                 . ((x($_GET,'cmin'))   ? '&cmin='   . $_GET['cmin']   : '') 
404                                 . ((x($_GET,'cmax'))   ? '&cmax='   . $_GET['cmax']   : '') 
405                                 . ((x($_GET,'file'))   ? '&file='   . $_GET['file']   : '') 
406
407                                 . "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
408                 }
409         }
410         else if($mode === 'profile') {
411                 $profile_owner = $a->profile['profile_uid'];
412                 $page_writeable = can_write_wall($a,$profile_owner);
413
414                 if(!$update) {
415                         $tab = notags(trim($_GET['tab']));
416                         $tab = ( $tab ? $tab : 'posts' );
417                         if($tab === 'posts') {
418                                 // This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
419                                 // because browser prefetching might change it on us. We have to deliver it with the page.
420
421                                 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
422                                         . "<script> var profile_uid = " . $a->profile['profile_uid'] 
423                                         . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
424                         }
425                 }
426         }
427         else if($mode === 'notes') {
428                 $profile_owner = local_user();
429                 $page_writeable = true;
430                 if(!$update) {
431                         $live_update_div = '<div id="live-notes"></div>' . "\r\n"
432                                 . "<script> var profile_uid = " . local_user() 
433                                 . "; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
434                 }
435         }
436         else if($mode === 'display') {
437                 $profile_owner = $a->profile['uid'];
438                 $page_writeable = can_write_wall($a,$profile_owner);
439                 if(!$update) {
440                         $live_update_div = '<div id="live-display"></div>' . "\r\n"
441                                 . "<script> var profile_uid = " . $_SESSION['uid'] . ";"
442                                 . " var profile_page = 1; </script>";
443                 }
444         }
445         else if($mode === 'community') {
446                 $profile_owner = 0;
447                 $page_writeable = false;
448                 if(!$update) {
449                         $live_update_div = '<div id="live-community"></div>' . "\r\n"
450                                 . "<script> var profile_uid = -1; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
451                 }
452         }
453         else if($mode === 'search') {
454                 $live_update_div = '<div id="live-search"></div>' . "\r\n";
455         }
456
457         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
458
459
460         if($update)
461                 $return_url = $_SESSION['return_url'];
462         else
463                 $return_url = $_SESSION['return_url'] = $a->query_string;
464
465         load_contact_links(local_user());
466
467         $cb = array('items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview);
468         call_hooks('conversation_start',$cb);
469
470         $items = $cb['items'];
471
472         $cmnt_tpl    = get_markup_template('comment_item.tpl');
473         $hide_comments_tpl = get_markup_template('hide_comments.tpl');
474
475         $alike = array();
476         $dlike = array();
477
478
479         // array with html for each thread (parent+comments)
480         $threads = array();
481         $threadsid = -1;
482
483         $page_template = get_markup_template("conversation.tpl");
484
485         if($items && count($items)) {
486
487                 if($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
488
489                         // "New Item View" on network page or search page results
490                         // - just loop through the items and format them minimally for display
491
492 //                      $tpl = get_markup_template('search_item.tpl');
493                         $tpl = 'search_item.tpl';
494
495                         foreach($items as $item) {
496                                 $threadsid++;
497
498                                 $comment     = '';
499                                 $owner_url   = '';
500                                 $owner_photo = '';
501                                 $owner_name  = '';
502                                 $sparkle     = '';
503
504                                 if($mode === 'search' || $mode === 'community') {
505                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE)))
506                                                 && ($item['id'] != $item['parent']))
507                                                 continue;
508                                         $nickname = $item['nickname'];
509                                 }
510                                 else
511                                         $nickname = $a->user['nickname'];
512
513                                 // prevent private email from leaking.
514                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
515                                                 continue;
516
517                                 $profile_name   = ((strlen($item['author-name']))   ? $item['author-name']   : $item['name']);
518                                 if($item['author-link'] && (! $item['author-name']))
519                                         $profile_name = $item['author-link'];
520
521
522
523                                 $tags=array();
524                                 $hashtags = array();
525                                 $mentions = array();
526                                 foreach(explode(',',$item['tag']) as $tag){
527                                         $tag = trim($tag);
528                                         if ($tag!="") {
529                                                 $t = bbcode($tag);
530                                                 $tags[] = $t;
531                                                 if($t[0] == '#')
532                                                         $hashtags[] = $t;
533                                                 elseif($t[0] == '@')
534                                                         $mentions[] = $t;
535                                         }
536                                 }
537
538                                 $sp = false;
539                                 $profile_link = best_link_url($item,$sp);
540                                 if($profile_link === 'mailbox')
541                                         $profile_link = '';
542                                 if($sp)
543                                         $sparkle = ' sparkle';
544                                 else
545                                         $profile_link = zrl($profile_link);
546
547                                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
548                                 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
549                                         $profile_avatar = $a->contacts[$normalised]['thumb'];
550                                 else
551                                         $profile_avatar = ((strlen($item['author-avatar'])) ? $a->get_cached_avatar_image($item['author-avatar']) : $item['thumb']);
552
553                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
554                                 call_hooks('render_location',$locate);
555
556                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
557
558                                 localize_item($item);
559                                 if($mode === 'network-new')
560                                         $dropping = true;
561                                 else
562                                         $dropping = false;
563
564
565                                 $drop = array(
566                                         'dropping' => $dropping,
567                                         'pagedrop' => $page_dropping,
568                                         'select' => t('Select'),
569                                         'delete' => t('Delete'),
570                                 );
571
572                                 $star = false;
573                                 $isstarred = "unstarred";
574
575                                 $lock = false;
576                                 $likebuttons = false;
577                                 $shareable = false;
578
579                                 $body = prepare_body($item,true);
580
581
582                                 list($categories, $folders) = get_cats_and_terms($item);
583
584                                 $tmp_item = array(
585                                         'template' => $tpl,
586                                         'id' => (($preview) ? 'P0' : $item['item_id']),
587                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
588                                         'profile_url' => $profile_link,
589                                         'item_photo_menu' => item_photo_menu($item),
590                                         'name' => template_escape($profile_name),
591                                         'sparkle' => $sparkle,
592                                         'lock' => $lock,
593                                         'thumb' => $profile_avatar,
594                                         'title' => template_escape($item['title']),
595                                         'body' => template_escape($body),
596                                         'tags' => template_escape($tags),
597                                         'hashtags' => template_escape($hashtags),
598                                         'mentions' => template_escape($mentions),
599                                         'txt_cats' => t('Categories:'),
600                                         'txt_folders' => t('Filed under:'),
601                                         'has_cats' => ((count($categories)) ? 'true' : ''),
602                                         'has_folders' => ((count($folders)) ? 'true' : ''),
603                                         'categories' => $categories,
604                                         'folders' => $folders,
605                                         'text' => strip_tags(template_escape($body)),
606                                         'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
607                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
608                                         'location' => template_escape($location),
609                                         'indent' => '',
610                                         'owner_name' => template_escape($owner_name),
611                                         'owner_url' => $owner_url,
612                                         'owner_photo' => $owner_photo,
613                                         'plink' => get_plink($item),
614                                         'edpost' => false,
615                                         'isstarred' => $isstarred,
616                                         'star' => $star,
617                                         'drop' => $drop,
618                                         'vote' => $likebuttons,
619                                         'like' => '',
620                                         'dislike' => '',
621                                         'comment' => '',
622                                         'conv' => (($preview) ? '' : array('href'=> $a->get_baseurl($ssl_state) . '/display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
623                                         'previewing' => $previewing,
624                                         'wait' => t('Please wait'),
625                                         'thread_level' => 1,
626                                 );
627
628                                 $arr = array('item' => $item, 'output' => $tmp_item);
629                                 call_hooks('display_item', $arr);
630
631                                 $threads[$threadsid]['id'] = $item['item_id'];
632                                 $threads[$threadsid]['items'] = array($arr['output']);
633
634                         }
635
636                 }
637                 else
638                 {
639                         // Normal View
640                         $page_template = get_markup_template("threaded_conversation.tpl");
641
642                         require_once('object/Conversation.php');
643                         require_once('object/Item.php');
644
645                         $conv = new Conversation($mode, $preview);
646
647                         // get all the topmost parents
648                         // this shouldn't be needed, as we should have only them in our array
649                         // But for now, this array respects the old style, just in case
650
651                         $threads = array();
652                         foreach($items as $item) {
653
654                                 // Can we put this after the visibility check?
655                                 like_puller($a,$item,$alike,'like');
656                                 like_puller($a,$item,$dlike,'dislike');
657
658                                 // Only add what is visible
659                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
660                                         continue;
661                                 }
662                                 if(! visible_activity($item)) {
663                                         continue;
664                                 }
665
666                                 $item['pagedrop'] = $page_dropping;
667
668                                 if($item['id'] == $item['parent']) {
669                                         $item_object = new Item($item);
670                                         $conv->add_thread($item_object);
671                                 }
672                         }
673
674                         $threads = $conv->get_template_data($alike, $dlike);
675                         if(!$threads) {
676                                 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
677                                 $threads = array();
678                         }
679                 }
680         }
681
682         $o = replace_macros($page_template, array(
683                 '$baseurl' => $a->get_baseurl($ssl_state),
684                 '$live_update' => $live_update_div,
685                 '$remove' => t('remove'),
686                 '$mode' => $mode,
687                 '$user' => $a->user,
688                 '$threads' => $threads,
689                 '$dropping' => ($page_dropping && feature_enabled(local_user(),'multi_delete') ? t('Delete Selected Items') : False),
690         ));
691
692         return $o;
693 }}
694
695 function best_link_url($item,&$sparkle,$ssl_state = false) {
696
697         $a = get_app();
698
699         $best_url = '';
700         $sparkle  = false;
701
702         $clean_url = normalise_link($item['author-link']);
703
704         if((local_user()) && (local_user() == $item['uid'])) {
705                 if(isset($a->contacts) && x($a->contacts,$clean_url)) {
706                         if($a->contacts[$clean_url]['network'] === NETWORK_DFRN) {
707                                 $best_url = $a->get_baseurl($ssl_state) . '/redir/' . $a->contacts[$clean_url]['id'];
708                                 $sparkle = true;
709                         }
710                         else
711                                 $best_url = $a->contacts[$clean_url]['url'];
712                 }
713         }
714         if(! $best_url) {
715                 if(strlen($item['author-link']))
716                         $best_url = $item['author-link'];
717                 else
718                         $best_url = $item['url'];
719         }
720
721         return $best_url;
722 }
723
724
725 if(! function_exists('item_photo_menu')){
726 function item_photo_menu($item){
727         $a = get_app();
728
729         $ssl_state = false;
730
731         if(local_user()) {
732                 $ssl_state = true;
733                  if(! count($a->contacts))
734                         load_contact_links(local_user());
735         }
736         $sub_link="";
737         $poke_link="";
738         $contact_url="";
739         $pm_url="";
740         $status_link="";
741         $photos_link="";
742         $posts_link="";
743
744         if((local_user()) && local_user() == $item['uid'] && $item['parent'] == $item['id'] && (! $item['self'])) {
745                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
746         }
747
748         $sparkle = false;
749         $profile_link = best_link_url($item,$sparkle,$ssl_state);
750         if($profile_link === 'mailbox')
751                 $profile_link = '';
752
753         if($sparkle) {
754                 $cid = intval(basename($profile_link));
755                 $status_link = $profile_link . "?url=status";
756                 $photos_link = $profile_link . "?url=photos";
757                 $profile_link = $profile_link . "?url=profile";
758                 $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
759                 $zurl = '';
760         }
761         else {
762                 $profile_link = zrl($profile_link);
763                 if(local_user() && local_user() == $item['uid'] && link_compare($item['url'],$item['author-link'])) {
764                         $cid = $item['contact-id'];
765                 }
766                 else {
767                         $cid = 0;
768                 }
769         }
770         if(($cid) && (! $item['self'])) {
771                 $poke_link = $a->get_baseurl($ssl_state) . '/poke/?f=&c=' . $cid;
772                 $contact_url = $a->get_baseurl($ssl_state) . '/contacts/' . $cid;
773                 $posts_link = $a->get_baseurl($ssl_state) . '/network/?cid=' . $cid;
774
775                 $clean_url = normalise_link($item['author-link']);
776
777                 if((local_user()) && (local_user() == $item['uid'])) {
778                         if(isset($a->contacts) && x($a->contacts,$clean_url)) {
779                                 if($a->contacts[$clean_url]['network'] === NETWORK_DIASPORA) {
780                                         $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
781                                 }
782                         }
783                 }
784
785         }
786
787         $menu = Array(
788                 t("Follow Thread") => $sub_link,
789                 t("View Status") => $status_link,
790                 t("View Profile") => $profile_link,
791                 t("View Photos") => $photos_link,
792                 t("Network Posts") => $posts_link,
793                 t("Edit Contact") => $contact_url,
794                 t("Send PM") => $pm_url,
795                 t("Poke") => $poke_link
796         );
797
798
799         $args = array('item' => $item, 'menu' => $menu);
800
801         call_hooks('item_photo_menu', $args);
802
803         $menu = $args['menu'];
804
805         $o = "";
806         foreach($menu as $k=>$v){
807                 if(strpos($v,'javascript:') === 0) {
808                         $v = substr($v,11);
809                         $o .= "<li><a href=\"#\" onclick=\"$v\">$k</a></li>\n";
810                 }
811                 elseif ($v!="") $o .= "<li><a href=\"$v\">$k</a></li>\n";
812         }
813         return $o;
814 }}
815
816 if(! function_exists('like_puller')) {
817 function like_puller($a,$item,&$arr,$mode) {
818
819         $url = '';
820         $sparkle = '';
821         $verb = (($mode === 'like') ? ACTIVITY_LIKE : ACTIVITY_DISLIKE);
822
823         if((activity_match($item['verb'],$verb)) && ($item['id'] != $item['parent'])) {
824                 $url = $item['author-link'];
825                 if((local_user()) && (local_user() == $item['uid']) && ($item['network'] === 'dfrn') && (! $item['self']) && (link_compare($item['author-link'],$item['url']))) {
826                         $url = $a->get_baseurl(true) . '/redir/' . $item['contact-id'];
827                         $sparkle = ' class="sparkle" ';
828                 }
829                 else
830                         $url = zrl($url);
831
832                 if(! $item['thr-parent'])
833                         $item['thr-parent'] = $item['parent-uri'];
834
835                 if(! ((isset($arr[$item['thr-parent'] . '-l'])) && (is_array($arr[$item['thr-parent'] . '-l']))))
836                         $arr[$item['thr-parent'] . '-l'] = array();
837                 if(! isset($arr[$item['thr-parent']]))
838                         $arr[$item['thr-parent']] = 1;
839                 else
840                         $arr[$item['thr-parent']] ++;
841                 $arr[$item['thr-parent'] . '-l'][] = '<a href="'. $url . '"'. $sparkle .'>' . $item['author-name'] . '</a>';
842         }
843         return;
844 }}
845
846 // Format the like/dislike text for a profile item
847 // $cnt = number of people who like/dislike the item
848 // $arr = array of pre-linked names of likers/dislikers
849 // $type = one of 'like, 'dislike'
850 // $id  = item id
851 // returns formatted text
852
853 if(! function_exists('format_like')) {
854 function format_like($cnt,$arr,$type,$id) {
855         $o = '';
856         if($cnt == 1)
857                 $o .= (($type === 'like') ? sprintf( t('%s likes this.'), $arr[0]) : sprintf( t('%s doesn\'t like this.'), $arr[0])) . EOL ;
858         else {
859                 $spanatts = 'class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');"';
860                 $o .= (($type === 'like') ?
861                                         sprintf( t('<span  %1$s>%2$d people</span> like this.'), $spanatts, $cnt)
862                                          :
863                                         sprintf( t('<span  %1$s>%2$d people</span> don\'t like this.'), $spanatts, $cnt) );
864                 $o .= EOL ;
865                 $total = count($arr);
866                 if($total >= MAX_LIKERS)
867                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
868                 if($total < MAX_LIKERS) {
869                         $last = t('and') . ' ' . $arr[count($arr)-1];
870                         $arr2 = array_slice($arr, 0, -1);
871                         $str = implode(', ', $arr2) . ' ' . $last;
872                 }
873                 if($total >= MAX_LIKERS) {
874                         $str = implode(', ', $arr);
875                         $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
876                 }
877                 $str = (($type === 'like') ? sprintf( t('%s like this.'), $str) : sprintf( t('%s don\'t like this.'), $str));
878                 $o .= "\t" . '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
879         }
880         return $o;
881 }}
882
883
884 function status_editor($a,$x, $notes_cid = 0, $popup=false) {
885
886         $o = '';
887
888         $geotag = (($x['allow_location']) ? get_markup_template('jot_geotag.tpl') : '');
889
890 /*      $plaintext = false;
891         if( local_user() && (intval(get_pconfig(local_user(),'system','plaintext')) || !feature_enabled(local_user(),'richtext')) )
892                 $plaintext = true;*/
893         $plaintext = true;
894         if( local_user() && feature_enabled(local_user(),'richtext') )
895                 $plaintext = false;
896
897         $tpl = get_markup_template('jot-header.tpl');
898         $a->page['htmlhead'] .= replace_macros($tpl, array(
899                 '$newpost' => 'true',
900                 '$baseurl' => $a->get_baseurl(true),
901                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
902                 '$geotag' => $geotag,
903                 '$nickname' => $x['nickname'],
904                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
905                 '$linkurl' => t('Please enter a link URL:'),
906                 '$vidurl' => t("Please enter a video link/URL:"),
907                 '$audurl' => t("Please enter an audio link/URL:"),
908                 '$term' => t('Tag term:'),
909                 '$fileas' => t('Save to Folder:'),
910                 '$whereareu' => t('Where are you right now?'),
911                 '$delitems' => t('Delete item(s)?')
912         ));
913
914
915         $tpl = get_markup_template('jot-end.tpl');
916         $a->page['end'] .= replace_macros($tpl, array(
917                 '$newpost' => 'true',
918                 '$baseurl' => $a->get_baseurl(true),
919                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
920                 '$geotag' => $geotag,
921                 '$nickname' => $x['nickname'],
922                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
923                 '$linkurl' => t('Please enter a link URL:'),
924                 '$vidurl' => t("Please enter a video link/URL:"),
925                 '$audurl' => t("Please enter an audio link/URL:"),
926                 '$term' => t('Tag term:'),
927                 '$fileas' => t('Save to Folder:'),
928                 '$whereareu' => t('Where are you right now?')
929         ));
930
931
932         $tpl = get_markup_template("jot.tpl");
933
934         $jotplugins = '';
935         $jotnets = '';
936
937         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
938
939         $mail_enabled = false;
940         $pubmail_enabled = false;
941
942         if(($x['is_owner']) && (! $mail_disabled)) {
943                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
944                         intval(local_user())
945                 );
946                 if(count($r)) {
947                         $mail_enabled = true;
948                         if(intval($r[0]['pubmail']))
949                                 $pubmail_enabled = true;
950                 }
951         }
952
953         if($mail_enabled) {
954                 $selected = (($pubmail_enabled) ? ' checked="checked" ' : '');
955                 $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . t("Post to Email") . '</div>';
956         }
957
958         call_hooks('jot_tool', $jotplugins);
959         call_hooks('jot_networks', $jotnets);
960
961         if($notes_cid)
962                 $jotnets .= '<input type="hidden" name="contact_allow[]" value="' . $notes_cid .'" />';
963
964 //      $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
965
966         $o .= replace_macros($tpl,array(
967                 '$return_path' => $a->query_string,
968                 '$action' =>  $a->get_baseurl(true) . '/item',
969                 '$share' => (x($x,'button') ? $x['button'] : t('Share')),
970                 '$upload' => t('Upload photo'),
971                 '$shortupload' => t('upload photo'),
972                 '$attach' => t('Attach file'),
973                 '$shortattach' => t('attach file'),
974                 '$weblink' => t('Insert web link'),
975                 '$shortweblink' => t('web link'),
976                 '$video' => t('Insert video link'),
977                 '$shortvideo' => t('video link'),
978                 '$audio' => t('Insert audio link'),
979                 '$shortaudio' => t('audio link'),
980                 '$setloc' => t('Set your location'),
981                 '$shortsetloc' => t('set location'),
982                 '$noloc' => t('Clear browser location'),
983                 '$shortnoloc' => t('clear location'),
984                 '$title' => "",
985                 '$placeholdertitle' => t('Set title'),
986                 '$category' => "",
987                 '$placeholdercategory' => (feature_enabled(local_user(),'categories') ? t('Categories (comma-separated list)') : ''),
988                 '$wait' => t('Please wait'),
989                 '$permset' => t('Permission settings'),
990                 '$shortpermset' => t('permissions'),
991                 '$ptyp' => (($notes_cid) ? 'note' : 'wall'),
992                 '$content' => '',
993                 '$post_id' => '',
994                 '$baseurl' => $a->get_baseurl(true),
995                 '$defloc' => $x['default_location'],
996                 '$visitor' => $x['visitor'],
997                 '$pvisit' => (($notes_cid) ? 'none' : $x['visitor']),
998                 '$emailcc' => t('CC: email addresses'),
999                 '$public' => t('Public post'),
1000                 '$jotnets' => $jotnets,
1001                 '$emtitle' => t('Example: bob@example.com, mary@example.com'),
1002                 '$lockstate' => $x['lockstate'],
1003                 '$acl' => $x['acl'],
1004                 '$bang' => $x['bang'],
1005                 '$profile_uid' => $x['profile_uid'],
1006                 '$preview' => ((feature_enabled($x['profile_uid'],'preview')) ? t('Preview') : ''),
1007                 '$jotplugins' => $jotplugins,
1008                 '$sourceapp' => t($a->sourcename),
1009                 '$cancel' => t('Cancel'),
1010                 '$rand_num' => random_digits(12)
1011         ));
1012
1013
1014         if ($popup==true){
1015                 $o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
1016
1017         }
1018
1019         return $o;
1020 }
1021
1022
1023 function get_item_children($arr, $parent) {
1024         $children = array();
1025         $a = get_app();
1026         foreach($arr as $item) {
1027                 if($item['id'] != $item['parent']) {
1028                         if(get_config('system','thread_allow') && $a->theme_thread_allow) {
1029                                 // Fallback to parent-uri if thr-parent is not set
1030                                 $thr_parent = $item['thr-parent'];
1031                                 if($thr_parent == '')
1032                                         $thr_parent = $item['parent-uri'];
1033
1034                                 if($thr_parent == $parent['uri']) {
1035                                         $item['children'] = get_item_children($arr, $item);
1036                                         $children[] = $item;
1037                                 }
1038                         }
1039                         else if($item['parent'] == $parent['id']) {
1040                                 $children[] = $item;
1041                         }
1042                 }
1043         }
1044         return $children;
1045 }
1046
1047 function sort_item_children($items) {
1048         $result = $items;
1049         usort($result,'sort_thr_created_rev');
1050         foreach($result as $k => $i) {
1051                 if(count($result[$k]['children'])) {
1052                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1053                 }
1054         }
1055         return $result;
1056 }
1057
1058 function add_children_to_list($children, &$arr) {
1059         foreach($children as $y) {
1060                 $arr[] = $y;
1061                 if(count($y['children']))
1062                         add_children_to_list($y['children'], $arr);
1063         }
1064 }
1065
1066 function conv_sort($arr,$order) {
1067
1068         if((!(is_array($arr) && count($arr))))
1069                 return array();
1070
1071         $parents = array();
1072         $children = array();
1073
1074         foreach($arr as $x)
1075                 if($x['id'] == $x['parent'])
1076                                 $parents[] = $x;
1077
1078         if(stristr($order,'created'))
1079                 usort($parents,'sort_thr_created');
1080         elseif(stristr($order,'commented'))
1081                 usort($parents,'sort_thr_commented');
1082
1083         if(count($parents))
1084                 foreach($parents as $i=>$_x)
1085                         $parents[$i]['children'] = get_item_children($arr, $_x);
1086
1087         /*foreach($arr as $x) {
1088                 if($x['id'] != $x['parent']) {
1089                         $p = find_thread_parent_index($parents,$x);
1090                         if($p !== false)
1091                                 $parents[$p]['children'][] = $x;
1092                 }
1093         }*/
1094         if(count($parents)) {
1095                 foreach($parents as $k => $v) {
1096                         if(count($parents[$k]['children'])) {
1097                                 $parents[$k]['children'] = sort_item_children($parents[$k]['children']);
1098                                 /*$y = $parents[$k]['children'];
1099                                 usort($y,'sort_thr_created_rev');
1100                                 $parents[$k]['children'] = $y;*/
1101                         }
1102                 }
1103         }
1104
1105         $ret = array();
1106         if(count($parents)) {
1107                 foreach($parents as $x) {
1108                         $ret[] = $x;
1109                         if(count($x['children']))
1110                                 add_children_to_list($x['children'], $ret);
1111                                 /*foreach($x['children'] as $y)
1112                                         $ret[] = $y;*/
1113                 }
1114         }
1115
1116         return $ret;
1117 }
1118
1119
1120 function sort_thr_created($a,$b) {
1121         return strcmp($b['created'],$a['created']);
1122 }
1123
1124 function sort_thr_created_rev($a,$b) {
1125         return strcmp($a['created'],$b['created']);
1126 }
1127
1128 function sort_thr_commented($a,$b) {
1129         return strcmp($b['commented'],$a['commented']);
1130 }
1131
1132 function find_thread_parent_index($arr,$x) {
1133         foreach($arr as $k => $v)
1134                 if($v['id'] == $x['parent'])
1135                         return $k;
1136         return false;
1137 }
1138
1139 function render_location_google($item) {
1140         $location = (($item['location']) ? '<a target="map" title="' . $item['location'] . '" href="http://maps.google.com/?q=' . urlencode($item['location']) . '">' . $item['location'] . '</a>' : '');
1141         $coord = (($item['coord']) ? '<a target="map" title="' . $item['coord'] . '" href="http://maps.google.com/?q=' . urlencode($item['coord']) . '">' . $item['coord'] . '</a>' : '');
1142         if($coord) {
1143                 if($location)
1144                         $location .= '<br /><span class="smalltext">(' . $coord . ')</span>';
1145                 else
1146                         $location = '<span class="smalltext">' . $coord . '</span>';
1147         }
1148         return $location;
1149 }