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