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