]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
4fea52c9c7a556a1733f4071b6dc4fcbcd726309
[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);
26                         $cnt++;
27
28                         $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $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         $newbody = $body;
52
53         for($i = 0; $i < count($images); $i++) {
54                 $search = '/\[url\=(.*?)\]\[!#saved_image' . $i . '#!\]\[\/url\]' . '/is';
55                 $replace = '[url=' . z_path() . '/redir/' . $cid 
56                            . '?f=1&url=' . '$1' . '][!#saved_image' . $i . '#!][/url]' ;
57
58                 $newbody = preg_replace($search, $replace, $newbody);
59         }
60
61         $cnt = 0;
62         foreach($images as $image) {
63                 // We're depending on the property of 'foreach' (specified on the PHP website) that
64                 // it loops over the array starting from the first element and going sequentially
65                 // to the last element
66                 $newbody = str_replace('[$#saved_image' . $cnt . '#$]', '[img]' . $image . '[/img]', $newbody);
67                 $cnt++;
68         }
69
70         return $newbody;
71 }}
72
73
74
75 /**
76  * Render actions localized
77  */
78 function localize_item(&$item){
79
80         $extracted = item_extract_images($item['body']);
81         if($extracted['images'])
82                 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
83
84         $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
85         if ($item['verb']=== ACTIVITY_LIKE || $item['verb']=== ACTIVITY_DISLIKE){
86
87                 $r = q("SELECT * from `item`,`contact` WHERE 
88                                 `item`.`contact-id`=`contact`.`id` AND `item`.`uri`='%s';",
89                                  dbesc($item['parent-uri']));
90                 if(count($r)==0) return;
91                 $obj=$r[0];
92                 
93                 $author  = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
94                 $objauthor =  '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]';
95                 
96                 switch($obj['verb']){
97                         case ACTIVITY_POST:
98                                 switch ($obj['object-type']){
99                                         case ACTIVITY_OBJ_EVENT:
100                                                 $post_type = t('event');
101                                                 break;
102                                         default:
103                                                 $post_type = t('status');
104                                 }
105                                 break;
106                         default:
107                                 if($obj['resource-id']){
108                                         $post_type = t('photo');
109                                         $m=array();     preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
110                                         $rr['plink'] = $m[1];
111                                 } else {
112                                         $post_type = t('status');
113                                 }
114                 }
115         
116                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
117                 
118                 switch($item['verb']){
119                         case ACTIVITY_LIKE :
120                                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
121                                 break;
122                         case ACTIVITY_DISLIKE:
123                                 $bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s');
124                                 break;
125                 }
126                 $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
127                         
128         }
129         if ($item['verb']=== ACTIVITY_FRIEND){
130
131                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
132
133                 $Aname = $item['author-name'];
134                 $Alink = $item['author-link'];
135                 
136                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
137                 
138                 $obj = parse_xml_string($xmlhead.$item['object']);
139                 $links = parse_xml_string($xmlhead."<links>".unxmlify($obj->link)."</links>");
140                 
141                 $Bname = $obj->title;
142                 $Blink = ""; $Bphoto = "";
143                 foreach ($links->link as $l){
144                         $atts = $l->attributes();
145                         switch($atts['rel']){
146                                 case "alternate": $Blink = $atts['href'];
147                                 case "photo": $Bphoto = $atts['href'];
148                         }
149                         
150                 }
151                 
152                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
153                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
154                 if ($Bphoto!="") $Bphoto = '[url=' . zrl($Blink) . '][img]' . $Bphoto . '[/img][/url]';
155
156                 $item['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
157
158         }
159     if ($item['verb']===ACTIVITY_TAG){
160                 $r = q("SELECT * from `item`,`contact` WHERE 
161                 `item`.`contact-id`=`contact`.`id` AND `item`.`uri`='%s';",
162                  dbesc($item['parent-uri']));
163                 if(count($r)==0) return;
164                 $obj=$r[0];
165                 
166                 $author  = '[url=' . zrl($item['author-link']) . ']' . $item['author-name'] . '[/url]';
167                 $objauthor =  '[url=' . zrl($obj['author-link']) . ']' . $obj['author-name'] . '[/url]';
168                 
169                 switch($obj['verb']){
170                         case ACTIVITY_POST:
171                                 switch ($obj['object-type']){
172                                         case ACTIVITY_OBJ_EVENT:
173                                                 $post_type = t('event');
174                                                 break;
175                                         default:
176                                                 $post_type = t('status');
177                                 }
178                                 break;
179                         default:
180                                 if($obj['resource-id']){
181                                         $post_type = t('photo');
182                                         $m=array();     preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
183                                         $rr['plink'] = $m[1];
184                                 } else {
185                                         $post_type = t('status');
186                                 }
187                 }
188                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
189                 
190                 $parsedobj = parse_xml_string($xmlhead.$item['object']);
191                 
192                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
193                 $item['body'] = sprintf( t('%1$s tagged %2$s\'s %3$s with %4$s'), $author, $objauthor, $plink, $tag );
194                 
195         }
196         if ($item['verb']=== ACTIVITY_FAVORITE){
197
198                 if ($item['object-type']== "")
199                         return;
200
201                 $Aname = $item['author-name'];
202                 $Alink = $item['author-link'];
203                 
204                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
205                 
206                 $obj = parse_xml_string($xmlhead.$item['object']);
207                 if(strlen($obj->id)) {
208                         $r = q("select * from item where uri = '%s' and uid = %d limit 1",
209                                         dbesc($obj->id),
210                                         intval($item['uid'])
211                         );
212                         if(count($r) && $r[0]['plink']) {
213                                 $target = $r[0];
214                                 $Bname = $target['author-name'];
215                                 $Blink = $target['author-link'];
216                                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
217                                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
218                                 $P = '[url=' . $target['plink'] . ']' . t('post/item') . '[/url]';
219                                 $item['body'] = sprintf( t('%1$s marked %2$s\'s %3$s as favorite'), $A, $B, $P)."\n";
220
221                         }
222                 }
223         }
224         $matches = null;
225         if(preg_match_all('/@\[url=(.*?)\]/is',$item['body'],$matches,PREG_SET_ORDER)) {
226                 foreach($matches as $mtch) {
227                         if(! strpos($mtch[1],'zrl='))
228                                 $item['body'] = str_replace($mtch[0],'@[url=' . zrl($mtch[1]). ']',$item['body']);
229                 }
230         }
231         // add zrl's to public images
232         if(preg_match_all('/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is',$item['body'],$matches,PREG_SET_ORDER)) {
233                 foreach($matches as $mtch) {
234                                 $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']);
235                 }
236         }
237
238
239 }
240
241 /**
242  * "Render" a conversation or list of items for HTML display.
243  * There are two major forms of display:
244  *      - Sequential or unthreaded ("New Item View" or search results)
245  *      - conversation view
246  * The $mode parameter decides between the various renderings and also
247  * figures out how to determine page owner and other contextual items 
248  * that are based on unique features of the calling module.
249  *
250  */
251
252 if(!function_exists('conversation')) {
253 function conversation(&$a, $items, $mode, $update, $preview = false) {
254
255
256         require_once('bbcode.php');
257
258         $ssl_state = ((local_user()) ? true : false);
259
260         $profile_owner = 0;
261         $page_writeable      = false;
262
263         $previewing = (($preview) ? ' preview ' : '');
264
265         if($mode === 'network') {
266                 $profile_owner = local_user();
267                 $page_writeable = true;
268         }
269
270         if($mode === 'profile') {
271                 $profile_owner = $a->profile['profile_uid'];
272                 $page_writeable = can_write_wall($a,$profile_owner);
273         }
274
275         if($mode === 'notes') {
276                 $profile_owner = local_user();
277                 $page_writeable = true;
278         }
279
280         if($mode === 'display') {
281                 $profile_owner = $a->profile['uid'];
282                 $page_writeable = can_write_wall($a,$profile_owner);
283         }
284
285         if($mode === 'community') {
286                 $profile_owner = 0;
287                 $page_writeable = false;
288         }
289
290         if($update)
291                 $return_url = $_SESSION['return_url'];
292         else
293                 $return_url = $_SESSION['return_url'] = $a->query_string;
294
295         load_contact_links(local_user());
296
297         $cb = array('items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview);
298         call_hooks('conversation_start',$cb);
299
300         $items = $cb['items'];
301
302         $cmnt_tpl    = get_markup_template('comment_item.tpl');
303         $tpl         = 'wall_item.tpl';
304         $wallwall    = 'wallwall_item.tpl';
305         $hide_comments_tpl = get_markup_template('hide_comments.tpl');
306
307         $alike = array();
308         $dlike = array();
309         
310         
311         // array with html for each thread (parent+comments)
312         $threads = array();
313         $threadsid = -1;
314         
315         if($items && count($items)) {
316
317                 if($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
318
319                         // "New Item View" on network page or search page results 
320                         // - just loop through the items and format them minimally for display
321
322                         //$tpl = get_markup_template('search_item.tpl');
323                         $tpl = 'search_item.tpl';
324
325                         foreach($items as $item) {
326                                 $threadsid++;
327
328                                 $comment     = '';
329                                 $owner_url   = '';
330                                 $owner_photo = '';
331                                 $owner_name  = '';
332                                 $sparkle     = '';
333
334                                 if($mode === 'search' || $mode === 'community') {
335                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) 
336                                                 && ($item['id'] != $item['parent']))
337                                                 continue;
338                                         $nickname = $item['nickname'];
339                                 }
340                                 else
341                                         $nickname = $a->user['nickname'];
342                                 
343                                 // prevent private email from leaking.
344                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
345                                                 continue;
346                         
347                                 $profile_name   = ((strlen($item['author-name']))   ? $item['author-name']   : $item['name']);
348                                 if($item['author-link'] && (! $item['author-name']))
349                                         $profile_name = $item['author-link'];
350
351
352
353                                 $sp = false;
354                                 $profile_link = best_link_url($item,$sp);
355                                 if($profile_link === 'mailbox')
356                                         $profile_link = '';
357                                 if($sp)
358                                         $sparkle = ' sparkle';
359                                 else
360                                         $profile_link = zrl($profile_link);                                     
361
362                                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
363                                 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
364                                         $profile_avatar = $a->contacts[$normalised]['thumb'];
365                                 else
366                                         $profile_avatar = ((strlen($item['author-avatar'])) ? $a->get_cached_avatar_image($item['author-avatar']) : $item['thumb']);
367
368                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
369                                 call_hooks('render_location',$locate);
370
371                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
372
373                                 localize_item($item);
374                                 if($mode === 'network-new')
375                                         $dropping = true;
376                                 else
377                                         $dropping = false;
378
379
380                                 $drop = array(
381                                         'dropping' => $dropping,
382                                         'select' => t('Select'), 
383                                         'delete' => t('Delete'),
384                                 );
385
386                                 $star = false;
387                                 $isstarred = "unstarred";
388                                 
389                                 $lock = false;
390                                 $likebuttons = false;
391                                 $shareable = false;
392
393                                 $body = prepare_body($item,true);
394                                 
395                                 //$tmp_item = replace_macros($tpl,array(
396                                 $tmp_item = array(
397                                         'template' => $tpl,
398                                         'id' => (($preview) ? 'P0' : $item['item_id']),
399                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
400                                         'profile_url' => $profile_link,
401                                         'item_photo_menu' => item_photo_menu($item),
402                                         'name' => template_escape($profile_name),
403                                         'sparkle' => $sparkle,
404                                         'lock' => $lock,
405                                         'thumb' => $profile_avatar,
406                                         'title' => template_escape($item['title']),
407                                         'body' => template_escape($body),
408                                         'text' => strip_tags(template_escape($body)),
409                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
410                                         'location' => template_escape($location),
411                                         'indent' => '',
412                                         'owner_name' => template_escape($owner_name),
413                                         'owner_url' => $owner_url,
414                                         'owner_photo' => $owner_photo,
415                                         'plink' => get_plink($item),
416                                         'edpost' => false,
417                                         'isstarred' => $isstarred,
418                                         'star' => $star,
419                                         'drop' => $drop,
420                                         'vote' => $likebuttons,
421                                         'like' => '',
422                                         'dislike' => '',
423                                         'comment' => '',
424                                         'conv' => (($preview) ? '' : array('href'=> $a->get_baseurl($ssl_state) . '/display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
425                                         'previewing' => $previewing,
426                                         'wait' => t('Please wait'),
427                                 );
428
429                                 $arr = array('item' => $item, 'output' => $tmp_item);
430                                 call_hooks('display_item', $arr);
431
432                                 $threads[$threadsid]['id'] = $item['item_id'];
433                                 $threads[$threadsid]['items'] = array($arr['output']);
434
435                         }
436
437                 }
438                 else
439                 {
440                         // Normal View
441
442
443                         // Figure out how many comments each parent has
444                         // (Comments all have gravity of 6)
445                         // Store the result in the $comments array
446
447                         $comments = array();
448                         foreach($items as $item) {
449                                 if((intval($item['gravity']) == 6) && ($item['id'] != $item['parent'])) {
450                                         if(! x($comments,$item['parent']))
451                                                 $comments[$item['parent']] = 1;
452                                         else
453                                                 $comments[$item['parent']] += 1;
454                                 } elseif(! x($comments,$item['parent'])) 
455                                         $comments[$item['parent']] = 0; // avoid notices later on
456                         }
457
458                         // map all the like/dislike activities for each parent item 
459                         // Store these in the $alike and $dlike arrays
460
461                         foreach($items as $item) {
462                                 like_puller($a,$item,$alike,'like');
463                                 like_puller($a,$item,$dlike,'dislike');
464                         }
465
466                         $comments_collapsed = false;
467                         $comments_seen = 0;
468                         $comment_lastcollapsed = false;
469                         $comment_firstcollapsed = false;
470                         $blowhard = 0;
471                         $blowhard_count = 0;
472
473
474                         foreach($items as $item) {
475
476                                 $comment = '';
477                                 $template = $tpl;
478                                 $commentww = '';
479                                 $sparkle = '';
480                                 $owner_url = $owner_photo = $owner_name = '';
481
482                                 // We've already parsed out like/dislike for special treatment. We can ignore them now
483
484                                 if(((activity_match($item['verb'],ACTIVITY_LIKE)) 
485                                         || (activity_match($item['verb'],ACTIVITY_DISLIKE))) 
486                                         && ($item['id'] != $item['parent']))
487                                         continue;
488
489                                 $toplevelpost = (($item['id'] == $item['parent']) ? true : false);
490
491
492                                 // Take care of author collapsing and comment collapsing
493                                 // (author collapsing is currently disabled)
494                                 // If a single author has more than 3 consecutive top-level posts, squash the remaining ones.
495                                 // If there are more than two comments, squash all but the last 2.
496                         
497                                 if($toplevelpost) {
498
499                                         $item_writeable = (($item['writable'] || $item['self']) ? true : false);
500
501                                         $comments_seen = 0;
502                                         $comments_collapsed = false;
503                                         $comment_lastcollapsed  = false;
504                                         $comment_firstcollapsed = false;
505                                         
506                                         $threadsid++;
507                                         $threads[$threadsid]['id'] = $item['item_id'];
508                                         $threads[$threadsid]['private'] = $item['private'];
509                                         $threads[$threadsid]['items'] = array();
510
511                                 }
512                                 else {
513
514                                         // prevent private email reply to public conversation from leaking.
515                                         if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
516                                                         continue;
517
518                                         $comments_seen ++;
519                                         $comment_lastcollapsed  = false;
520                                         $comment_firstcollapsed = false;
521                                 }       
522
523                                 $override_comment_box = ((($page_writeable) && ($item_writeable)) ? true : false);
524                                 $show_comment_box = ((($page_writeable) && ($item_writeable) && ($comments_seen == $comments[$item['parent']])) ? true : false);
525
526
527                                 if(($comments[$item['parent']] > 2) && ($comments_seen <= ($comments[$item['parent']] - 2)) && ($item['gravity'] == 6)) {
528
529                                         if (!$comments_collapsed){
530                                                 $threads[$threadsid]['num_comments'] = sprintf( tt('%d comment','%d comments',$comments[$item['parent']]),$comments[$item['parent']] );
531                                                 $threads[$threadsid]['hide_text'] = t('show more');
532                                                 $comments_collapsed = true;
533                                                 $comment_firstcollapsed = true;
534                                         }
535                                 }
536                                 if(($comments[$item['parent']] > 2) && ($comments_seen == ($comments[$item['parent']] - 1))) {
537
538                                         $comment_lastcollapsed = true;
539                                 }
540
541                                 $redirect_url = $a->get_baseurl($ssl_state) . '/redir/' . $item['cid'] ;
542
543                                 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid']) 
544                                         || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
545                                         ? t('Private Message')
546                                         : false);
547
548
549                                 // Top-level wall post not written by the wall owner (wall-to-wall)
550                                 // First figure out who owns it. 
551
552                                 $osparkle = '';
553
554                                 if(($toplevelpost) && (! $item['self']) && ($mode !== 'profile')) {
555
556                                         if($item['wall']) {
557
558                                                 // On the network page, I am the owner. On the display page it will be the profile owner.
559                                                 // This will have been stored in $a->page_contact by our calling page.
560                                                 // Put this person as the wall owner of the wall-to-wall notice.
561
562                                                 $owner_url = zrl($a->page_contact['url']);
563                                                 $owner_photo = $a->page_contact['thumb'];
564                                                 $owner_name = $a->page_contact['name'];
565                                                 $template = $wallwall;
566                                                 $commentww = 'ww';      
567                                         }
568
569                                         if((! $item['wall']) && $item['owner-link']) {
570
571                                                 $owner_linkmatch = (($item['owner-link']) && link_compare($item['owner-link'],$item['author-link']));
572                                                 $alias_linkmatch = (($item['alias']) && link_compare($item['alias'],$item['author-link']));
573                                                 $owner_namematch = (($item['owner-name']) && $item['owner-name'] == $item['author-name']);
574                                                 if((! $owner_linkmatch) && (! $alias_linkmatch) && (! $owner_namematch)) {
575
576                                                         // The author url doesn't match the owner (typically the contact)
577                                                         // and also doesn't match the contact alias. 
578                                                         // The name match is a hack to catch several weird cases where URLs are 
579                                                         // all over the park. It can be tricked, but this prevents you from
580                                                         // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
581                                                         // well that it's the same Bob Smith. 
582
583                                                         // But it could be somebody else with the same name. It just isn't highly likely. 
584                                                         
585
586                                                         $owner_url = $item['owner-link'];
587                                                         $owner_photo = $item['owner-avatar'];
588                                                         $owner_name = $item['owner-name'];
589                                                         $template = $wallwall;
590                                                         $commentww = 'ww';
591                                                         // If it is our contact, use a friendly redirect link
592                                                         if((link_compare($item['owner-link'],$item['url'])) 
593                                                                 && ($item['network'] === NETWORK_DFRN)) {
594                                                                 $owner_url = $redirect_url;
595                                                                 $osparkle = ' sparkle';
596                                                         }
597                                                         else
598                                                                 $owner_url = zrl($owner_url);
599                                                 }
600                                         }
601                                 }
602
603                                 $likebuttons = '';
604                                 $shareable = ((($profile_owner == local_user()) && ($item['private'] != 1)) ? true : false); 
605
606                                 if($page_writeable) {
607 /*                                      if($toplevelpost) {  */
608                                                 $likebuttons = array(
609                                                         'like' => array( t("I like this \x28toggle\x29"), t("like")),
610                                                         'dislike' => array( t("I don't like this \x28toggle\x29"), t("dislike")),
611                                                 );
612                                                 if ($shareable) $likebuttons['share'] = array( t('Share this'), t('share'));
613 /*                                      } */
614
615                                         $qc = $qcomment =  null;
616
617                                         if(in_array('qcomment',$a->plugins)) {
618                                                 $qc = ((local_user()) ? get_pconfig(local_user(),'qcomment','words') : null);
619                                                 $qcomment = (($qc) ? explode("\n",$qc) : null);
620                                         }
621
622                                         if(($show_comment_box) || (($show_comment_box == false) && ($override_comment_box == false) && ($item['last-child']))) {
623                                                 $comment = replace_macros($cmnt_tpl,array(
624                                                         '$return_path' => '', 
625                                                         '$jsreload' => (($mode === 'display') ? $_SESSION['return_url'] : ''),
626                                                         '$type' => (($mode === 'profile') ? 'wall-comment' : 'net-comment'),
627                                                         '$id' => $item['item_id'],
628                                                         '$parent' => $item['parent'],
629                                                         '$qcomment' => $qcomment,
630                                                         '$profile_uid' =>  $profile_owner,
631                                                         '$mylink' => $a->contact['url'],
632                                                         '$mytitle' => t('This is you'),
633                                                         '$myphoto' => $a->contact['thumb'],
634                                                         '$comment' => t('Comment'),
635                                                         '$submit' => t('Submit'),
636                                                         '$edbold' => t('Bold'),
637                                                         '$editalic' => t('Italic'),
638                                                         '$eduline' => t('Underline'),
639                                                         '$edquote' => t('Quote'),
640                                                         '$edcode' => t('Code'),
641                                                         '$edimg' => t('Image'),
642                                                         '$edurl' => t('Link'),
643                                                         '$edvideo' => t('Video'),
644                                                         '$preview' => t('Preview'),
645                                                         '$ww' => (($mode === 'network') ? $commentww : '')
646                                                 ));
647                                         }
648                                 }
649
650                                 if(local_user() && link_compare($a->contact['url'],$item['author-link']))
651                                         $edpost = array($a->get_baseurl($ssl_state)."/editpost/".$item['id'], t("Edit"));
652                                 else
653                                         $edpost = false;
654
655                                 $drop = '';
656                                 $dropping = false;
657
658                                 if((intval($item['contact-id']) && $item['contact-id'] == remote_user()) || ($item['uid'] == local_user()))
659                                         $dropping = true;
660
661                                 $drop = array(
662                                         'dropping' => $dropping,
663                                         'select' => t('Select'), 
664                                         'delete' => t('Delete'),
665                                 );
666
667                                 $star = false;
668                                 $filer = false;
669
670                                 $isstarred = "unstarred";
671                                 if ($profile_owner == local_user()) {
672                                         if($toplevelpost) {
673                                                 $isstarred = (($item['starred']) ? "starred" : "unstarred");
674
675                                                 $star = array(
676                                                         'do' => t("add star"),
677                                                         'undo' => t("remove star"),
678                                                         'toggle' => t("toggle star status"),
679                                                         'classdo' => (($item['starred']) ? "hidden" : ""),
680                                                         'classundo' => (($item['starred']) ? "" : "hidden"),
681                                                         'starred' =>  t('starred'),
682                                                         'tagger' => t("add tag"),
683                                                         'classtagger' => "",
684                                                 );
685                                         }
686                                         $filer = t("save to folder");
687                                 }
688
689
690                                 $photo = $item['photo'];
691                                 $thumb = $item['thumb'];
692
693                                 // Post was remotely authored.
694
695                                 $diff_author    = ((link_compare($item['url'],$item['author-link'])) ? false : true);
696
697                                 $profile_name   = (((strlen($item['author-name']))   && $diff_author) ? $item['author-name']   : $item['name']);
698
699                                 if($item['author-link'] && (! $item['author-name']))
700                                         $profile_name = $item['author-link'];
701
702                                 $sp = false;
703                                 $profile_link = best_link_url($item,$sp);
704                                 if($profile_link === 'mailbox')
705                                         $profile_link = '';
706                                 if($sp)
707                                         $sparkle = ' sparkle';
708                                 else
709                                         $profile_link = zrl($profile_link);                                     
710
711                                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
712                                 if(($normalised != 'mailbox') && (x($a->contacts,$normalised)))
713                                         $profile_avatar = $a->contacts[$normalised]['thumb'];
714                                 else
715                                         $profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $a->get_cached_avatar_image($thumb));
716
717                                 $like    = ((x($alike,$item['uri'])) ? format_like($alike[$item['uri']],$alike[$item['uri'] . '-l'],'like',$item['uri']) : '');
718                                 $dislike = ((x($dlike,$item['uri'])) ? format_like($dlike[$item['uri']],$dlike[$item['uri'] . '-l'],'dislike',$item['uri']) : '');
719
720                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
721                                 call_hooks('render_location',$locate);
722
723                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
724
725                                 $indent = (($toplevelpost) ? '' : ' comment');
726
727                                 if(strcmp(datetime_convert('UTC','UTC',$item['created']),datetime_convert('UTC','UTC','now - 12 hours')) > 0)
728                                         $indent .= ' shiny'; 
729
730                                 // 
731                                 localize_item($item);
732
733
734                                 $tags=array();
735                                 foreach(explode(',',$item['tag']) as $tag){
736                                         $tag = trim($tag);
737                                         if ($tag!="") $tags[] = bbcode($tag);
738                                 }
739
740                                 // Build the HTML
741
742                                 $body = prepare_body($item,true);
743                                 //$tmp_item = replace_macros($template,
744                                 $tmp_item = array(
745                                         // collapse comments in template. I don't like this much...
746                                         'comment_firstcollapsed' => $comment_firstcollapsed,
747                                         'comment_lastcollapsed' => $comment_lastcollapsed,
748                                         // template to use to render item (wall, walltowall, search)
749                                         'template' => $template,
750                                         
751                                         'type' => implode("",array_slice(explode("/",$item['verb']),-1)),
752                                         'tags' => $tags,
753                                         'body' => template_escape($body),
754                                         'text' => strip_tags(template_escape($body)),
755                                         'id' => $item['item_id'],
756                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
757                                         'olinktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['owner-link'])) ? $item['owner-link'] : $item['url'])),
758                                         'to' => t('to'),
759                                         'wall' => t('Wall-to-Wall'),
760                                         'vwall' => t('via Wall-To-Wall:'),
761                                         'profile_url' => $profile_link,
762                                         'item_photo_menu' => item_photo_menu($item),
763                                         'name' => template_escape($profile_name),
764                                         'thumb' => $profile_avatar,
765                                         'osparkle' => $osparkle,
766                                         'sparkle' => $sparkle,
767                                         'title' => template_escape($item['title']),
768                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
769                                         'lock' => $lock,
770                                         'location' => template_escape($location),
771                                         'indent' => $indent,
772                                         'owner_url' => $owner_url,
773                                         'owner_photo' => $owner_photo,
774                                         'owner_name' => template_escape($owner_name),
775                                         'plink' => get_plink($item),
776                                         'edpost' => $edpost,
777                                         'isstarred' => $isstarred,
778                                         'star' => $star,
779                                         'filer' => $filer,
780                                         'drop' => $drop,
781                                         'vote' => $likebuttons,
782                                         'like' => $like,
783                                         'dislike' => $dislike,
784                                         'comment' => $comment,
785                                         'previewing' => $previewing,
786                                         'wait' => t('Please wait'),
787
788                                 );
789
790
791                                 $arr = array('item' => $item, 'output' => $tmp_item);
792                                 call_hooks('display_item', $arr);
793
794                                 $threads[$threadsid]['items'][] = $arr['output'];
795                         }
796                 }
797         }
798
799         $page_template = get_markup_template("conversation.tpl");
800         $o = replace_macros($page_template, array(
801                 '$baseurl' => $a->get_baseurl($ssl_state),
802                 '$mode' => $mode,
803                 '$user' => $a->user,
804                 '$threads' => $threads,
805                 '$dropping' => ($dropping?t('Delete Selected Items'):False),
806         ));
807
808         return $o;
809 }}
810
811 function best_link_url($item,&$sparkle,$ssl_state = false) {
812
813         $a = get_app();
814
815         $best_url = '';
816         $sparkle  = false;
817
818         $clean_url = normalise_link($item['author-link']);
819
820         if((local_user()) && (local_user() == $item['uid'])) {
821                 if(isset($a->contacts) && x($a->contacts,$clean_url)) {
822                         if($a->contacts[$clean_url]['network'] === NETWORK_DFRN) {
823                                 $best_url = $a->get_baseurl($ssl_state) . '/redir/' . $a->contacts[$clean_url]['id'];
824                                 $sparkle = true;
825                         }
826                         else
827                                 $best_url = $a->contacts[$clean_url]['url'];
828                 }
829         }
830         if(! $best_url) {
831                 if(strlen($item['author-link']))
832                         $best_url = $item['author-link'];
833                 else
834                         $best_url = $item['url'];
835         }
836
837         return $best_url;
838 }
839
840
841 if(! function_exists('item_photo_menu')){
842 function item_photo_menu($item){
843         $a = get_app();
844
845         $ssl_state = false;
846
847         if(local_user()) {
848                 $ssl_state = true;
849                  if(! count($a->contacts))
850                         load_contact_links(local_user());
851         }
852         $contact_url="";
853         $pm_url="";
854         $status_link="";
855         $photos_link="";
856         $posts_link="";
857
858         $sparkle = false;
859     $profile_link = best_link_url($item,$sparkle,$ssl_state);
860         if($profile_link === 'mailbox')
861                 $profile_link = '';
862
863         if($sparkle) {
864                 $cid = intval(basename($profile_link));
865                 $status_link = $profile_link . "?url=status";
866                 $photos_link = $profile_link . "?url=photos";
867                 $profile_link = $profile_link . "?url=profile";
868                 $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
869                 $zurl = '';
870         }
871         else {
872                 $profile_link = zrl($profile_link);
873                 if(local_user() && local_user() == $item['uid'] && link_compare($item['url'],$item['author-link'])) {
874                         $cid = $item['contact-id'];
875                 }               
876                 else {
877                         $cid = 0;
878                 }
879         }
880         if(($cid) && (! $item['self'])) {
881                 $contact_url = $a->get_baseurl($ssl_state) . '/contacts/' . $cid;
882                 $posts_link = $a->get_baseurl($ssl_state) . '/network/?cid=' . $cid;
883
884                 $clean_url = normalise_link($item['author-link']);
885
886                 if((local_user()) && (local_user() == $item['uid'])) {
887                         if(isset($a->contacts) && x($a->contacts,$clean_url)) {
888                                 if($a->contacts[$clean_url]['network'] === NETWORK_DIASPORA) {
889                                         $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
890                                 }
891                         }
892                 }
893
894         }
895
896         $menu = Array(
897                 t("View Status") => $status_link,
898                 t("View Profile") => $profile_link,
899                 t("View Photos") => $photos_link,
900                 t("Network Posts") => $posts_link, 
901                 t("Edit Contact") => $contact_url,
902                 t("Send PM") => $pm_url,
903         );
904         
905         
906         $args = array('item' => $item, 'menu' => $menu);
907         
908         call_hooks('item_photo_menu', $args);
909
910         $menu = $args['menu'];  
911
912         $o = "";
913         foreach($menu as $k=>$v){
914                 if ($v!="") $o .= "<li><a href='$v'>$k</a></li>\n";
915         }
916         return $o;
917 }}
918
919 if(! function_exists('like_puller')) {
920 function like_puller($a,$item,&$arr,$mode) {
921
922         $url = '';
923         $sparkle = '';
924         $verb = (($mode === 'like') ? ACTIVITY_LIKE : ACTIVITY_DISLIKE);
925
926         if((activity_match($item['verb'],$verb)) && ($item['id'] != $item['parent'])) {
927                 $url = $item['author-link'];
928                 if((local_user()) && (local_user() == $item['uid']) && ($item['network'] === 'dfrn') && (! $item['self']) && (link_compare($item['author-link'],$item['url']))) {
929                         $url = $a->get_baseurl(true) . '/redir/' . $item['contact-id'];
930                         $sparkle = ' class="sparkle" ';
931                 }
932                 else
933                         $url = zrl($url);
934
935                 if(! $item['thr-parent'])
936                         $item['thr-parent'] = $item['parent-uri'];
937
938                 if(! ((isset($arr[$item['thr-parent'] . '-l'])) && (is_array($arr[$item['thr-parent'] . '-l']))))
939                         $arr[$item['thr-parent'] . '-l'] = array();
940                 if(! isset($arr[$item['thr-parent']]))
941                         $arr[$item['thr-parent']] = 1;
942                 else    
943                         $arr[$item['thr-parent']] ++;
944                 $arr[$item['thr-parent'] . '-l'][] = '<a href="'. $url . '"'. $sparkle .'>' . $item['author-name'] . '</a>';
945         }
946         return;
947 }}
948
949 // Format the like/dislike text for a profile item
950 // $cnt = number of people who like/dislike the item
951 // $arr = array of pre-linked names of likers/dislikers
952 // $type = one of 'like, 'dislike'
953 // $id  = item id
954 // returns formatted text
955
956 if(! function_exists('format_like')) {
957 function format_like($cnt,$arr,$type,$id) {
958         $o = '';
959         if($cnt == 1)
960                 $o .= (($type === 'like') ? sprintf( t('%s likes this.'), $arr[0]) : sprintf( t('%s doesn\'t like this.'), $arr[0])) . EOL ;
961         else {
962                 $spanatts = 'class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');"';
963                 $o .= (($type === 'like') ? 
964                                         sprintf( t('<span  %1$s>%2$d people</span> like this.'), $spanatts, $cnt)
965                                          : 
966                                         sprintf( t('<span  %1$s>%2$d people</span> don\'t like this.'), $spanatts, $cnt) ); 
967                 $o .= EOL ;
968                 $total = count($arr);
969                 if($total >= MAX_LIKERS)
970                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
971                 if($total < MAX_LIKERS)
972                         $arr[count($arr)-1] = t('and') . ' ' . $arr[count($arr)-1];
973                 $str = implode(', ', $arr);
974                 if($total >= MAX_LIKERS)
975                         $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
976                 $str = (($type === 'like') ? sprintf( t('%s like this.'), $str) : sprintf( t('%s don\'t like this.'), $str));
977                 $o .= "\t" . '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
978         }
979         return $o;
980 }}
981
982
983 function status_editor($a,$x, $notes_cid = 0, $popup=false) {
984
985         $o = '';
986                 
987         $geotag = (($x['allow_location']) ? get_markup_template('jot_geotag.tpl') : '');
988
989         $plaintext = false;
990         if(local_user() && intval(get_pconfig(local_user(),'system','plaintext')))
991                 $plaintext = true;
992
993         $tpl = get_markup_template('jot-header.tpl');
994         
995         $a->page['htmlhead'] .= replace_macros($tpl, array(
996                 '$newpost' => 'true',
997                 '$baseurl' => $a->get_baseurl(true),
998                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
999                 '$geotag' => $geotag,
1000                 '$nickname' => $x['nickname'],
1001                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
1002                 '$linkurl' => t('Please enter a link URL:'),
1003                 '$vidurl' => t("Please enter a video link/URL:"),
1004                 '$audurl' => t("Please enter an audio link/URL:"),
1005                 '$term' => t('Tag term:'),
1006                 '$fileas' => t('Save to Folder:'),
1007                 '$whereareu' => t('Where are you right now?')
1008         ));
1009
1010
1011         $tpl = get_markup_template("jot.tpl");
1012                 
1013         $jotplugins = '';
1014         $jotnets = '';
1015
1016         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
1017
1018         $mail_enabled = false;
1019         $pubmail_enabled = false;
1020
1021         if(($x['is_owner']) && (! $mail_disabled)) {
1022                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
1023                         intval(local_user())
1024                 );
1025                 if(count($r)) {
1026                         $mail_enabled = true;
1027                         if(intval($r[0]['pubmail']))
1028                                 $pubmail_enabled = true;
1029                 }
1030         }
1031
1032         if($mail_enabled) {
1033                 $selected = (($pubmail_enabled) ? ' checked="checked" ' : '');
1034                 $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . t("Post to Email") . '</div>';
1035         }
1036
1037         call_hooks('jot_tool', $jotplugins);
1038         call_hooks('jot_networks', $jotnets);
1039
1040         if($notes_cid)
1041                 $jotnets .= '<input type="hidden" name="contact_allow[]" value="' . $notes_cid .'" />';
1042
1043         $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));        
1044
1045         $o .= replace_macros($tpl,array(
1046                 '$return_path' => $a->query_string,
1047                 '$action' =>  $a->get_baseurl(true) . '/item',
1048                 '$share' => (x($x,'button') ? $x['button'] : t('Share')),
1049                 '$upload' => t('Upload photo'),
1050                 '$shortupload' => t('upload photo'),
1051                 '$attach' => t('Attach file'),
1052                 '$shortattach' => t('attach file'),
1053                 '$weblink' => t('Insert web link'),
1054                 '$shortweblink' => t('web link'),
1055                 '$video' => t('Insert video link'),
1056                 '$shortvideo' => t('video link'),
1057                 '$audio' => t('Insert audio link'),
1058                 '$shortaudio' => t('audio link'),
1059                 '$setloc' => t('Set your location'),
1060                 '$shortsetloc' => t('set location'),
1061                 '$noloc' => t('Clear browser location'),
1062                 '$shortnoloc' => t('clear location'),
1063                 '$title' => "",
1064                 '$placeholdertitle' => t('Set title'),
1065                 '$category' => "",
1066                 '$placeholdercategory' => t('Categories (comma-separated list)'),
1067                 '$wait' => t('Please wait'),
1068                 '$permset' => t('Permission settings'),
1069                 '$shortpermset' => t('permissions'),
1070                 '$ptyp' => (($notes_cid) ? 'note' : 'wall'),
1071                 '$content' => '',
1072                 '$post_id' => '',
1073                 '$baseurl' => $a->get_baseurl(true),
1074                 '$defloc' => $x['default_location'],
1075                 '$visitor' => $x['visitor'],
1076                 '$pvisit' => (($notes_cid) ? 'none' : $x['visitor']),
1077                 '$emailcc' => t('CC: email addresses'),
1078                 '$public' => t('Public post'),
1079                 '$jotnets' => $jotnets,
1080                 '$emtitle' => t('Example: bob@example.com, mary@example.com'),
1081                 '$lockstate' => $x['lockstate'],
1082                 '$acl' => $x['acl'],
1083                 '$bang' => $x['bang'],
1084                 '$profile_uid' => $x['profile_uid'],
1085                 '$preview' => t('Preview'),
1086         ));
1087
1088
1089         if ($popup==true){
1090                 $o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
1091                 
1092         }
1093
1094         return $o;
1095 }
1096
1097
1098 function conv_sort($arr,$order) {
1099
1100         if((!(is_array($arr) && count($arr))))
1101                 return array();
1102
1103         $parents = array();
1104
1105         foreach($arr as $x)
1106                 if($x['id'] == $x['parent'])
1107                                 $parents[] = $x;
1108
1109         if(stristr($order,'created'))
1110                 usort($parents,'sort_thr_created');
1111         elseif(stristr($order,'commented'))
1112                 usort($parents,'sort_thr_commented');
1113
1114         if(count($parents))
1115                 foreach($parents as $i=>$_x) 
1116                         $parents[$i]['children'] = array();
1117
1118         foreach($arr as $x) {
1119                 if($x['id'] != $x['parent']) {
1120                         $p = find_thread_parent_index($parents,$x);
1121                         if($p !== false)
1122                                 $parents[$p]['children'][] = $x;
1123                 }
1124         }
1125         if(count($parents)) {
1126                 foreach($parents as $k => $v) {
1127                         if(count($parents[$k]['children'])) {
1128                                 $y = $parents[$k]['children'];
1129                                 usort($y,'sort_thr_created_rev');
1130                                 $parents[$k]['children'] = $y;
1131                         }
1132                 }       
1133         }
1134
1135         $ret = array();
1136         if(count($parents)) {
1137                 foreach($parents as $x) {
1138                         $ret[] = $x;
1139                         if(count($x['children']))
1140                                 foreach($x['children'] as $y)
1141                                         $ret[] = $y;
1142                 }
1143         }
1144
1145         return $ret;
1146 }
1147
1148
1149 function sort_thr_created($a,$b) {
1150         return strcmp($b['created'],$a['created']);
1151 }
1152
1153 function sort_thr_created_rev($a,$b) {
1154         return strcmp($a['created'],$b['created']);
1155 }
1156
1157 function sort_thr_commented($a,$b) {
1158         return strcmp($b['commented'],$a['commented']);
1159 }
1160
1161 function find_thread_parent_index($arr,$x) {
1162         foreach($arr as $k => $v)
1163                 if($v['id'] == $x['parent'])
1164                         return $k;
1165         return false;
1166 }
1167
1168 function render_location_google($item) {
1169         $location = (($item['location']) ? '<a target="map" title="' . $item['location'] . '" href="http://maps.google.com/?q=' . urlencode($item['location']) . '">' . $item['location'] . '</a>' : '');
1170         $coord = (($item['coord']) ? '<a target="map" title="' . $item['coord'] . '" href="http://maps.google.com/?q=' . urlencode($item['coord']) . '">' . $item['coord'] . '</a>' : '');
1171         if($coord) {
1172                 if($location)
1173                         $location .= '<br /><span class="smalltext">(' . $coord . ')</span>';
1174                 else
1175                         $location = '<span class="smalltext">' . $coord . '</span>';
1176         }
1177         return $location;
1178 }