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