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