File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.278: download - view: text, annotated - select for diffs
Wed Nov 4 17:45:49 2009 UTC (14 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Accommodate Communities.
 - role names when filtering post by role type from &Apache::lonnet::plaintext()
 - (C)course -> (C)community
   (S)student -> (M)member

    1: # The LearningOnline Network
    2: # Feedback
    3: #
    4: # $Id: lonfeedback.pm,v 1.278 2009/11/04 17:45:49 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonfeedback;
   31: 
   32: use strict;
   33: use Apache::Constants qw(:common);
   34: use Apache::lonmsg();
   35: use Apache::loncommon();
   36: use Apache::lontexconvert();
   37: use Apache::lonlocal; # must not have ()
   38: use Apache::lonnet;
   39: use Apache::lonhtmlcommon();
   40: use Apache::lonnavmaps;
   41: use Apache::lonenc();
   42: use Apache::lonrss();
   43: use HTML::LCParser();
   44: use Apache::lonspeller();
   45: use Apache::longroup;
   46: use Cwd;
   47: use LONCAPA;
   48: 
   49: sub discussion_open {
   50:     my ($status,$symb)=@_;
   51:     if ($env{'request.role.adv'}) { return 1; }
   52:     if (defined($status) &&
   53: 	!($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER'
   54: 	  || $status eq 'OPEN')) {
   55: 	return 0;
   56:     }
   57:     my $close=&Apache::lonnet::EXT('resource.0.discussend',$symb);
   58:     if (defined($close) && $close ne '' && $close < time) {
   59: 	return 0;
   60:     }
   61:     return 1;
   62: }
   63: 
   64: sub discussion_visible {
   65:     my ($status)=@_;
   66:     if (not &discussion_open($status)) {
   67: 	my $hidden=&Apache::lonnet::EXT('resource.0.discusshide');
   68: 	if (lc($hidden) eq 'yes' or $hidden eq '' or !defined($hidden))  {
   69: 	    if (!$env{'request.role.adv'}) { return 0; }
   70: 	}
   71:     }
   72:     return 1;
   73: }
   74: 
   75: sub list_discussion {
   76:     my ($mode,$status,$ressymb,$imsextras,$group)=@_;
   77:     unless ($ressymb) { $ressymb=&Apache::lonnet::symbread(); }
   78:     unless ($ressymb) { return ''; }
   79:     $ressymb=&wrap_symb($ressymb);
   80:     my $outputtarget=$env{'form.grade_target'};
   81:     if (defined($env{'form.export'})) {
   82: 	if($env{'form.export'}) {
   83:             $outputtarget = 'export';
   84:         }
   85:     }
   86:     if (defined($imsextras)) {
   87:         if ($$imsextras{'caller'} eq 'imsexport') {
   88:             $outputtarget = 'export';
   89:         }
   90:     }
   91:     if (not &discussion_visible($status)) {
   92:         if ($mode ne 'board') {
   93:             &Apache::lonenc::check_encrypt(\$ressymb); 
   94:             return '<br /><div class="LC_feedback_link">'.&send_message_link($ressymb)."</div>";
   95:         }
   96:     }
   97:     if ($group ne '' && $mode eq 'board') {
   98:         if (&check_group_priv($group,'vgb') ne 'ok') {
   99:             return '';
  100:         }
  101:     }
  102: 
  103:     my ($blocked,$blocktext) = 
  104:         &Apache::loncommon::blocking_status('boards');
  105:     if ($blocked) {
  106:         $blocktext = '<br /><div class="LC_feedback_link"><span class="LC_feedback_link">'.$blocktext."</span>";
  107:         &Apache::lonenc::check_encrypt(\$ressymb);
  108:         if ($mode ne 'board') {
  109:             $blocktext.=&send_message_link($ressymb).'</div>';
  110:         }else{
  111:             $blocktext.="</div>";
  112:         }
  113:         return $blocktext; 
  114:     }
  115: 
  116:     my @bgcols = ("LC_disc_old_item","LC_disc_new_item");
  117:     my $discussiononly=0;
  118:     if ($mode eq 'board') { $discussiononly=1; }
  119:     unless ($env{'request.course.id'}) { return ''; }
  120:     my $crs='/'.$env{'request.course.id'};
  121:     my $cid=$env{'request.course.id'};
  122:     if ($env{'request.course.sec'}) {
  123: 	$crs.='_'.$env{'request.course.sec'};
  124:     }
  125:     $crs=~s/\_/\//g;
  126:     my $encsymb=&Apache::lonenc::check_encrypt($ressymb);
  127:     my $viewgrades=(&Apache::lonnet::allowed('vgr',$crs)
  128: 		  && ($ressymb=~/\.(problem|exam|quiz|assess|survey|form|task)$/));
  129:     
  130:     my %usernamesort = ();
  131:     my %namesort =();
  132:     my %subjectsort = ();
  133: 
  134: # Get discussion display settings for this discussion
  135:     my $lastkey = $ressymb.'_lastread';
  136:     my $showkey = $ressymb.'_showonlyunread';
  137:     my $markkey = $ressymb.'_showonlyunmark',
  138:     my $visitkey = $ressymb.'_visit';
  139:     my $ondispkey = $ressymb.'_markondisp';
  140:     my $userpickkey = $ressymb.'_userpick';
  141:     my $toggkey = $ressymb.'_readtoggle';
  142:     my $readkey = $ressymb.'_read';
  143:     $ressymb=$encsymb;
  144:     my %dischash = &Apache::lonnet::get('nohist_'.$cid.'_discuss',[$lastkey,$showkey,$markkey,$visitkey,$ondispkey,$userpickkey,$toggkey,$readkey],$env{'user.domain'},$env{'user.name'});
  145:     my %discinfo = ();
  146:     my $showonlyunread = 0;
  147:     my $showunmark = 0; 
  148:     my $markondisp = 0;
  149:     my $prevread = 0;
  150:     my $previous = 0;
  151:     my $visit = 0;
  152:     my $newpostsflag = 0;
  153:     my @posters = split(/\&/,$dischash{$userpickkey});
  154: 
  155: # Retain identification of "NEW" posts identified in last display, if continuing 'previous' browsing of posts.
  156:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['previous','sortposts','rolefilter','statusfilter','sectionpick','grouppick','totposters']);
  157:     my $sortposts = $env{'form.sortposts'};
  158:     my $statusfilter = $env{'form.statusfilter'};
  159:     my @sectionpick = split(/,/,$env{'form.sectionpick'});
  160:     my @grouppick   = split(/,/,$env{'form.grouppick'});
  161:     my @rolefilter  = split(/,/,$env{'form.rolefilter'});
  162: 
  163:     my $totposters = $env{'form.totposters'};
  164:     $previous = $env{'form.previous'};
  165:     if ($previous > 0) {
  166:         $prevread = $previous;
  167:     } elsif (defined($dischash{$lastkey})) {
  168:         unless ($dischash{$lastkey} eq '') {
  169:             $prevread = $dischash{$lastkey};
  170:         }
  171:     }
  172: 
  173:     my $cdom = $env{'course.'.$cid.'.domain'};
  174:     my $cnum = $env{'course.'.$cid.'.num'};
  175:     my $crstype = &Apache::loncommon::course_type();
  176: 
  177: # Get information about students and non-students in course for filtering display of posts
  178:     my %roleshash = ();
  179:     my %roleinfo = ();
  180:     my ($classgroups,$studentgroups);
  181:     if ($env{'form.rolefilter'}) {
  182:         %roleshash = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
  183:         foreach my $rolekey (keys(%roleshash)) {
  184:             my ($role,$uname,$udom,$sec) = split(/:/,$rolekey);
  185:             if ($role =~ /^cr/) {
  186:                 $role = 'cr';
  187:             }
  188:             my ($end,$start) = split(/:/,$roleshash{$rolekey});
  189:             my $now = time;
  190:             my $status = 'Active';
  191:             if (($now < $start) || ($end > 0 && $now > $end)) {
  192:                 $status = 'Expired';
  193:             }
  194:             if ($uname && $udom) { 
  195:                 push(@{$roleinfo{$uname.':'.$udom}}, $role.':'.$sec.':'.$status);
  196:             }
  197:         }
  198:         my ($classlist,$keylist) =
  199:                          &Apache::loncoursedata::get_classlist($cdom,$cnum);
  200:         my $sec_index = &Apache::loncoursedata::CL_SECTION();
  201:         my $status_index = &Apache::loncoursedata::CL_STATUS();
  202:         while (my ($student,$data) = each %$classlist) {
  203:             my ($section,$status) = ($data->[$sec_index],
  204:                                  $data->[$status_index]);
  205:             push(@{$roleinfo{$student}}, 'st:'.$section.':'.$status);
  206:         }
  207: 	($classgroups,$studentgroups) = 
  208: 	    &Apache::loncoursedata::get_group_memberships($classlist,$keylist,
  209: 							  $cdom,$cnum);
  210:     }
  211: 
  212: # Get discussion display default settings for user
  213:     if ($env{'environment.discdisplay'} eq 'unread') {
  214:         $showonlyunread = 1;
  215:     }
  216:     if ($env{'environment.discmarkread'} eq 'ondisp') {
  217:         $markondisp = 1;
  218:     }
  219: 
  220: # Override user's default if user specified display setting for this discussion
  221:     if (defined($dischash{$ondispkey})) {
  222:         unless ($dischash{$ondispkey} eq '') {
  223:             $markondisp = $dischash{$ondispkey};
  224:         }
  225:     }
  226:     if ($markondisp) {
  227:         $discinfo{$lastkey} = time;
  228:     }
  229: 
  230:     if (defined($dischash{$showkey})) {
  231:         unless ($dischash{$showkey} eq '') {
  232:             $showonlyunread = $dischash{$showkey};
  233:         }
  234:     }
  235: 
  236:     if (defined($dischash{$markkey})) {
  237:         unless ($dischash{$markkey} eq '') {
  238:             $showunmark = $dischash{$markkey};
  239:         }
  240:     }
  241: 
  242:     if (defined($dischash{$visitkey})) {
  243:         unless ($dischash{$visitkey} eq '') {
  244:             $visit = $dischash{$visitkey};
  245:         }
  246:     }
  247:     $visit ++;
  248: 
  249:     my $seeid;
  250:     if (($group ne '') && ($mode eq 'board') && 
  251:         ($ressymb =~ m|^bulletin___\d+___adm/wrapper/adm/\Q$cdom\E/\Q$cnum\E/\d+/bulletinboard$|)) {
  252:         if (&check_group_priv($group,'dgp') eq 'ok') {
  253:             $seeid = 1;
  254:         }
  255:     } else {
  256:         $seeid=&Apache::lonnet::allowed('rin',$crs);
  257:     }
  258:     my @discussionitems=();
  259:     my %shown = ();
  260:     my @posteridentity=();
  261: 
  262:     my $current=0;
  263:     my $visible=0;
  264:     my @depth=();
  265:     my @replies = ();
  266:     my %alldiscussion=();
  267:     my %imsitems=();
  268:     my %imsfiles=();
  269:     my %notshown = ();
  270:     my %newitem = ();
  271:     my $maxdepth=0;
  272:     my %anonhash=();
  273:     my $anoncnt=0;
  274:     my $target='';
  275:     unless ($env{'browser.interface'} eq 'textual' ||
  276: 	    $env{'environment.remote'} eq 'off' ) {
  277: 	$target='target="LONcom"';
  278:     }
  279: 
  280:     my $now = time;
  281:     $discinfo{$visitkey} = $visit;
  282: 
  283:     &Apache::lonnet::put('nohist_'.$cid.'_discuss',\%discinfo,$env{'user.domain'},$env{'user.name'});
  284:     &build_posting_display(\%usernamesort,\%subjectsort,\%namesort,\%notshown,\%newitem,\%dischash,\%shown,\%alldiscussion,\%imsitems,\%imsfiles,\%roleinfo,\@discussionitems,\@replies,\@depth,\@posters,\$maxdepth,\$visible,\$newpostsflag,\$current,$status,$viewgrades,$seeid,$prevread,$sortposts,$encsymb,$target,$readkey,$showunmark,$showonlyunread,$totposters,\@rolefilter,\@sectionpick,\@grouppick,$classgroups,$statusfilter,$toggkey,$outputtarget,\%anonhash,$anoncnt,$group);
  285: 
  286:     my $discussion='';
  287:     my $manifestfile;
  288:     my $manifestok=0;
  289:     my $tempexport;
  290:     my $imsresources;
  291:     my $copyresult;
  292: 
  293:     my $function = &Apache::loncommon::get_users_function();
  294:     my $color = &Apache::loncommon::designparm($function.'.tabbg',
  295:                                                     $env{'user.domain'});
  296:     my %lt = &Apache::lonlocal::texthash(
  297:         'cuse' => 'Current discussion settings',
  298:         'allposts' => 'All posts',
  299:         'unread' => 'New posts only',
  300:         'unmark' => 'Unread only',
  301:         'ondisp' => 'Once displayed',
  302:         'onmark' => 'Once marked not NEW',
  303:         'toggoff' => 'Off',
  304:         'toggon' => 'On',
  305:         'disa' => 'Posts to be displayed',
  306:         'npce' => 'Posts cease to be marked "NEW"',
  307:         'epcb' => 'Each post can be toggled read/unread', 
  308:         'chgt' => 'Change',
  309:         'disp' => 'Display',
  310:         'nolo' => 'Not new',
  311:         'togg' => 'Toggle read/unread',
  312:         'aner' => 'An error occurred opening the manifest file.',
  313:         'difo' => 'Discussion for',
  314:         'aerr' => 'An error occurred opening the export file for posting',
  315:         'aysu' => 'Are you sure you want to delete this post?',
  316:         'dpwn' => 'Deleted posts will no longer be visible to you and other students',
  317:         'bwco' => 'but will continue to be visible to your instructor',
  318:         'depo' => 'Deleted posts will no longer be visible to you or anyone else.',
  319:     );
  320: 
  321:     my $currdisp = $lt{'allposts'};
  322:     my $currmark = $lt{'onmark'};
  323:     my $currtogg = $lt{'toggoff'};
  324:     my $dispchange = $lt{'unread'};
  325:     my $markchange = $lt{'ondisp'};
  326:     my $toggchange = $lt{'toggon'};
  327:     my $chglink = '/adm/feedback?modifydisp='.$ressymb;
  328:     my $displinkA = 'onlyunread';
  329:     my $displinkB = 'onlyunmark';
  330:     my $marklink = 'markondisp';
  331:     my $togglink = 'toggon';
  332: 
  333:     if ($markondisp) {
  334:         $currmark = $lt{'ondisp'};
  335:         $markchange = $lt{'onmark'};
  336:         $marklink = 'markonread';
  337:     }
  338: 
  339:     if ($showonlyunread) {
  340:         $currdisp = $lt{'unread'};
  341:         $dispchange = $lt{'allposts'};
  342:         $displinkA = 'allposts';
  343:     }
  344: 
  345:     if ($showunmark) {
  346:         $currdisp = $lt{'unmark'};
  347:         $dispchange = $lt{'unmark'};
  348:         $displinkA='allposts';
  349:         $displinkB='onlyunread';
  350:         $showonlyunread = 0;
  351:     }
  352: 
  353:     if ($dischash{$toggkey}) {
  354:         $currtogg = $lt{'toggon'};
  355:         $toggchange = $lt{'toggoff'};
  356:         $togglink = 'toggoff';
  357:     } 
  358:    
  359:     $chglink .= '&changes='.$displinkA.'_'.$displinkB.'_'.$marklink.'_'.$togglink;
  360: 
  361:     if ($newpostsflag) {
  362:         $chglink .= '&previous='.$prevread;
  363:     }
  364:     $chglink.=&group_args($group);
  365: 
  366:     if ($visible) {
  367: # Print the discusssion
  368:         if ($outputtarget eq 'tex') {
  369:             $discussion.='<tex>{\tiny \vskip 0 mm\noindent\makebox[2 cm][b]{\hrulefill}'.
  370:                          '\textbf{DISCUSSIONS}\makebox[2 cm][b]{\hrulefill}'.
  371:                          '\vskip 0 mm\noindent\textbf{'.$lt{'cuse'}.'}:\vskip 0 mm'.
  372:                          '\noindent\textbf{'.$lt{'disa'}.'}: \textit{'.$currdisp.'}\vskip 0 mm'.
  373:                          '\noindent\textbf{'.$lt{'npce'}.'}: \textit{'.$currmark.'}}</tex>';
  374:         } elsif ($outputtarget eq 'export') {
  375: # Create temporary directory if this is an export
  376:             my $now = time;
  377:             if ((defined($imsextras)) && ($$imsextras{'caller'} eq 'imsexport')) {
  378:                 $tempexport = $$imsextras{'tempexport'};
  379:                 if (!-e $tempexport) {
  380:                     mkdir($tempexport,0700);
  381:                 }
  382:                 $tempexport .= '/'.$$imsextras{'count'};
  383:                 if (!-e $tempexport) {
  384:                     mkdir($tempexport,0700);
  385:                 }
  386:             } else {
  387:                 $tempexport = $Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/ims_exports';
  388:                 if (!-e $tempexport) {
  389:                     mkdir($tempexport,0700);
  390:                 }
  391:                 $tempexport .= '/'.$now;
  392:                 if (!-e $tempexport) {
  393:                     mkdir($tempexport,0700);
  394:                 }
  395:                 $tempexport .= '/'.$env{'user.domain'}.'_'.$env{'user.name'};
  396:             }
  397:             if (!-e $tempexport) {
  398:                 mkdir($tempexport,0700);
  399:             }
  400: # open manifest file
  401:             my $manifest = '/imsmanifest.xml';
  402:             my $manifestfilename = $tempexport.$manifest;
  403:             if ($manifestfile = Apache::File->new('>'.$manifestfilename)) {
  404:                 $manifestok=1;
  405:                 print $manifestfile qq|
  406: <?xml version="1.0" encoding="UTF-8"?>
  407: <manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1" xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2" 
  408: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  409: identifier="MANIFEST-$ressymb" xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1 
  410: imscp_v1p1.xsd http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd">
  411:   <organizations default="$ressymb">
  412:     <organization identifier="$ressymb">
  413:       <title>$lt{'difo'} $ressymb</title>\n|;
  414:             } else {
  415:                 $discussion .= $lt{'aner'}.'<br />';
  416:             }
  417: 	} else {
  418:             my $colspan=$maxdepth+1;
  419:             $discussion.= qq|
  420: <script>
  421:    function verifydelete (caller,symb,idx,newflag,previous,groupparm) {
  422:        var symbparm = symb+':::'+idx
  423:        var prevparm = ""
  424:        if (newflag == 1) {
  425:            prevparm = "&previous="+previous
  426:        }
  427:        if (caller == 'studentdelete') {
  428:            if (confirm("$lt{'aysu'}\\n$lt{'dpwn'},\\n$lt{'bwco'}")) {
  429:                document.location.href = "/adm/feedback?hide="+symbparm+prevparm+groupparm
  430:            }
  431:        } else {
  432:            if (caller == 'seeiddelete') {
  433:                if (confirm("$lt{'aysu'}\\n$lt{'depo'}")) {
  434:                    document.location.href = "/adm/feedback?deldisc="+symbparm+prevparm+groupparm
  435:                }
  436:            }
  437:        }
  438:    }
  439: </script>
  440:             |;
  441: 	    $discussion.='<form name="readchoices" method="post" action="/adm/feedback?chgreads='.$ressymb.'" >'.
  442:                          "\n".'<table class="LC_discussion">';
  443:             $discussion .= &action_links_bar($colspan,$ressymb,$visible,
  444:                                              $newpostsflag,$group,
  445:                                              $prevread,$markondisp);
  446:             my $escsymb=&escape($ressymb);
  447:             my $numhidden = keys(%notshown);
  448:             if ($numhidden > 0) {
  449:                 my $colspan = $maxdepth+1;
  450:                 $discussion.="\n".'<tr><td bgcolor="#CCCCCC" colspan="'.$colspan.'">'.
  451:                          '<a href="/adm/feedback?allposts=1&amp;symb='.$escsymb;
  452:                 if ($newpostsflag) {
  453:                     $discussion .= '&previous='.$prevread;
  454:                 }
  455: 		$discussion .= &group_args($group);
  456:                 $discussion .= '">'.&mt('Show all posts').'</a> '.&mt('to display').' '.
  457:                          $numhidden.' ';
  458:                 if ($showunmark) {
  459:                     $discussion .= &mt('posts previously marked read');
  460:                 } else {
  461:                     $discussion .= &mt('previously viewed posts');
  462:                 }
  463:                 $discussion .= '<br/></td></tr>';
  464:             }
  465:         }
  466: 
  467: # Choose sort mechanism
  468:         my @showposts = ();
  469:         if ($sortposts eq 'descdate') {
  470:             @showposts = (sort { $b <=> $a } keys(%alldiscussion));
  471:         } elsif ($sortposts eq 'thread') {
  472:             @showposts = (sort { $a <=> $b } keys(%alldiscussion));
  473:         } elsif ($sortposts eq 'subject') {
  474:             foreach my $key (sort(keys(%subjectsort))) {
  475:                 push(@showposts, @{$subjectsort{$key}});
  476:             }
  477:         } elsif ($sortposts eq 'username') {
  478:             foreach my $domain (sort(keys(%usernamesort))) {
  479:                 foreach my $key (sort(keys(%{$usernamesort{$domain}}))) {
  480:                     push(@showposts, @{$usernamesort{$domain}{$key}});
  481:                 }
  482:             }
  483:         } elsif ($sortposts eq 'lastfirst') {
  484:             foreach my $last (sort(keys(%namesort))) {
  485:                  foreach my $key (sort(keys(%{$namesort{$last}}))) {
  486:                      push(@showposts, @{$namesort{$last}{$key}});
  487:                  }
  488:             }
  489:         } else {
  490:             @showposts =  (sort { $a <=> $b } keys(%alldiscussion));
  491:         }
  492:         my $currdepth = 0;
  493:         my $firstidx = $alldiscussion{$showposts[0]};
  494:         foreach my $post (@showposts) {
  495:             unless (($sortposts eq 'thread') || (($sortposts eq '') && ($env{'environment.threadeddiscussion'})) || ($outputtarget eq 'export')) {
  496:                 $alldiscussion{$post} = $post;
  497:             }
  498:             unless ( ($notshown{$alldiscussion{$post}} eq '1') || ($shown{$alldiscussion{$post}} == 0) ) {
  499:                 if ($outputtarget ne 'tex' && $outputtarget ne 'export') {
  500: 		    $discussion.="\n<tr>";
  501: 		}
  502: 	        my $thisdepth=$depth[$alldiscussion{$post}];
  503:                 if ($outputtarget ne 'tex' && $outputtarget ne 'export') {
  504: 		    for (1..$thisdepth) {
  505: 			$discussion.='<td>&nbsp;&nbsp;&nbsp;</td>';
  506: 		    }
  507: 		}
  508: 	        my $colspan=$maxdepth-$thisdepth+1;
  509:                 if ($outputtarget eq 'tex') {
  510: 		    #cleanup block
  511: 		    $discussionitems[$alldiscussion{$post}]=~s/<table([^>]*)>/<table TeXwidth="90 mm">/;
  512: 		    $discussionitems[$alldiscussion{$post}]=~s/<tr([^>]*)><td([^>]*)>/<tr><td TeXwidth="20 mm" align="left">/;
  513:                     my $threadinsert='';
  514:                     if ($thisdepth > 0) {
  515: 			$threadinsert='<br /><strong>Reply: '.$thisdepth.'</strong>';
  516: 		    }
  517: 		    $discussionitems[$alldiscussion{$post}]=~s/<\/td><td([^>]*)>/$threadinsert<\/td><td TeXwidth="65 mm" align="left">/;
  518: 		    $discussionitems[$alldiscussion{$post}]=~s/<a([^>]+)>(Edit|Hide|Delete|Reply|Submissions)<\/a>//g;
  519:                     $discussionitems[$alldiscussion{$post}]=~s/(<b>|<\/b>|<\/a>|<a([^>]+)>)//g;
  520: 
  521: 		    $discussionitems[$alldiscussion{$post}]='<tex>\vskip 0 mm\noindent\makebox[2 cm][b]{\hrulefill}</tex>'.$discussionitems[$alldiscussion{$post}];
  522: 		    $discussion.=$discussionitems[$alldiscussion{$post}];
  523: 		} elsif ($outputtarget eq 'export') {
  524:                     my $postfilename = $alldiscussion{$post}.'-'.$imsitems{$alldiscussion{$post}}{'timestamp'}.'.html';
  525:                     if ($manifestok) {
  526:                         if (($depth[$alldiscussion{$post}] <= $currdepth) && ($alldiscussion{$post} != $firstidx)) {
  527:                             print $manifestfile '  </item>'."\n";
  528:                         }
  529:                         $currdepth = $depth[$alldiscussion{$post}];
  530:                         print $manifestfile "\n". 
  531:       '<item identifier="ITEM-'.$ressymb.'-'.$alldiscussion{$post}.'" isvisible="'.
  532:         $imsitems{$alldiscussion{$post}}{'isvisible'}.'" identifieref="RES-'.$ressymb.'-'.$alldiscussion{$post}.'">'.
  533:         '<title>'.$imsitems{$alldiscussion{$post}}{'title'}.'</title>';
  534:                         $imsresources .= "\n".
  535:     '<resource identifier="RES-'.$ressymb.'-'.$alldiscussion{$post}.'" type="webcontent" href="'.$postfilename.'">'."\n".
  536:       '<file href="'.$postfilename.'">'."\n".
  537:       $imsfiles{$alldiscussion{$post}}{$imsitems{$alldiscussion{$post}}{'currversion'}}."\n".
  538:     '</resource>';
  539:                     }
  540:                     my $postingfile;
  541:                     my $postingfilename = $tempexport.'/'.$postfilename;
  542:                     if ($postingfile = Apache::File->new('>'.$postingfilename)) {
  543:                         print $postingfile '<html><head><title>Discussion Post</title></head><body>'.
  544:                                            $imsitems{$alldiscussion{$post}}{'title'}.' '.
  545:                                            $imsitems{$alldiscussion{$post}}{'sender'}.
  546:                                            $imsitems{$alldiscussion{$post}}{'timestamp'}.'<br /><br />'.
  547:                                            $imsitems{$alldiscussion{$post}}{'message'}.'<br />'.
  548:                                            $imsitems{$alldiscussion{$post}}{'attach'}.'</body></html>'."\n"; 
  549:                         close($postingfile);
  550:                     } else {
  551:                         $discussion .= $lt{'aerr'}.' '.$alldiscussion{$post}.'<br />';
  552:                     }
  553:                     $copyresult.=&replicate_attachments($imsitems{$alldiscussion{$post}}{'allattachments'},$tempexport);
  554:                 } else {
  555:                     $discussion.='<td class="'.$bgcols[$newitem{$alldiscussion{$post}}].
  556:                        '" colspan="'.$colspan.'">'. $discussionitems[$alldiscussion{$post}].
  557:                        '</td></tr>';
  558:                 }
  559: 	    }
  560:         }
  561: 	unless ($outputtarget eq 'tex' || $outputtarget eq 'export') {
  562:             my $colspan=$maxdepth+1;
  563:             $discussion .= <<END;
  564:             <tr bgcolor="#FFFFFF">
  565:              <td colspan="$colspan" class="LC_disc_action_links_bar">
  566:               <table class="LC_disc_action_table">
  567:                <tr>
  568:                 <td align="left">
  569:                  <table border="0" cellpadding="0" cellspacing="4">
  570:                   <tr>
  571:                    <td>
  572:                     <font size="-1"><b>$lt{'cuse'}</b>:</td>
  573:                    <td>&nbsp;</td>
  574:                    <td><font size="-1">
  575: END
  576:             if ($newpostsflag) {
  577:                 $discussion .= 
  578:                    '1.&nbsp;'.$lt{'disp'}.'&nbsp;-&nbsp;<i>'.$currdisp.'</i>&nbsp;&nbsp;2.&nbsp;'.$lt{'nolo'}.'&nbsp;-&nbsp;<i>'.$currmark.'</i>';
  579:                 if ($dischash{$toggkey}) {
  580:                    $discussion .= '&nbsp;&nbsp;3.&nbsp;'.$lt{'togg'}.'&nbsp;-&nbsp;<i>'.$currtogg.'</i>';
  581:                 }
  582:             } else {
  583:                 if ($dischash{$toggkey}) {
  584:                    $discussion .= '1.&nbsp;'.$lt{'disp'}.'&nbsp;-&nbsp;<i>'.$currdisp.'</i>&nbsp;2.&nbsp;'.$lt{'togg'}.'&nbsp;-&nbsp;<i>'.$currtogg.'</i>';
  585:                 } else {
  586:                     $discussion .=
  587:                          $lt{'disp'}.'&nbsp;-&nbsp;<i>'.$currdisp.'</i>';
  588:                 }
  589:             }
  590:             $discussion .= <<END;
  591:                    </font></td>
  592:                    <td>&nbsp;</td>
  593:                    <td align="left">
  594:                     <font size="-1"><b><a href="$chglink">$lt{'chgt'}</a>?</font></b>
  595:                    </td>
  596:                   </tr>
  597:                  </table>
  598:                 </td>
  599: END
  600:             if ($sortposts) {
  601:                 my %sort_types = ();
  602:                 my %role_types = ();
  603:                 my %status_types = ();
  604:                 &sort_filter_names(\%sort_types,\%role_types,\%status_types,$crstype);
  605: 
  606:                 $discussion .= '<td><font size="-1"><b>'.&mt('Sorted by').'</b>: '.$sort_types{$sortposts}.'<br />';
  607:                 if (defined($env{'form.totposters'})) {
  608:                     $discussion .= &mt('Posts by').':';
  609:                     if ($totposters > 0) {
  610:                         foreach my $poster (@posters) {
  611:                             $discussion .= ' '.$poster.',';
  612:                         }
  613:                         $discussion =~ s/,$//;
  614:                     } else {
  615:                         $discussion .= &mt('None selected');
  616:                     }
  617:                 } else {
  618:                     my $filterchoice ='';
  619:                     if (@sectionpick > 0) {
  620:                         $filterchoice = '<i>'.&mt('sections').'</i>-&nbsp;'.$env{'form.sectionpick'};
  621:                         $filterchoice .= '&nbsp;&nbsp;&nbsp; ';
  622:                     }
  623:                     if (@grouppick > 0) {
  624:                         $filterchoice = '<i>'.&mt('groups').'</i>-&nbsp;'.$env{'form.grouppick'};
  625:                         $filterchoice .= '&nbsp;&nbsp;&nbsp; ';
  626:                     }
  627:                     if (@rolefilter > 0) {
  628:                         $filterchoice .= '<i>'.&mt('roles').'</i>-';
  629:                         foreach my $role (@rolefilter) {
  630:                             $filterchoice .= '&nbsp;'.$role_types{$role}.',';
  631:                         }
  632:                         $filterchoice =~ s/,$//;
  633:                         $filterchoice .= '<br />'.('&nbsp;' x8);
  634:                     }
  635:                     if ($statusfilter) {
  636:                         $filterchoice .= '<i>'.&mt('status').'</i>-&nbsp;'.$status_types{$statusfilter};
  637:                     }
  638:                     if ($filterchoice) {
  639:                         $discussion .= '<b>'.&mt('Filters').'</b>:&nbsp;'.$filterchoice;
  640:                     }
  641:                     $discussion .= '</font></td>';
  642:                 }
  643:             }
  644:             if ($dischash{$toggkey}) {
  645:                 my $storebutton = &mt('Save read/unread changes');
  646:                 $discussion.='<td align="right">'.
  647:               '<input type="hidden" name="discsymb" value="'.$ressymb.'" />'."\n".
  648:               '<input type="button" name="readoptions" value="'.$storebutton.'"'.
  649:               ' onClick="this.form.submit();" />'."\n".
  650:               '</td>';
  651:             }
  652:             $discussion .= (<<END);
  653:                </tr>
  654:               </table>
  655:              </td>
  656:             </tr>
  657: END
  658:             $discussion .= &action_links_bar($colspan,$ressymb,$visible,
  659:                                              $newpostsflag,$group,
  660:                                              $prevread,$markondisp);
  661:             $discussion .= "
  662:            </table>
  663:            <br /><br /></form>\n";
  664:         } 
  665:         if ($outputtarget eq 'export') {
  666:             if ($manifestok) {
  667:                 while ($currdepth > 0) {
  668:                     print $manifestfile "    </item>\n";
  669:                     $currdepth --;
  670:                 }
  671:                 print $manifestfile qq|
  672:     </organization>
  673:   </organizations>
  674:   <resources>
  675:     $imsresources
  676:   </resources>
  677: </manifest>
  678:                 |;
  679:                 close($manifestfile);
  680:                 if ((defined($imsextras)) && ($$imsextras{'caller'} eq 'imsexport')) {
  681:                     $discussion = $copyresult;
  682:                 } else {
  683: 
  684: #Create zip file in prtspool
  685: 
  686:                     my $imszipfile = '/prtspool/'.
  687:                     $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
  688:                          time.'_'.rand(1000000000).'.zip';
  689:                     my $cwd = &getcwd(); 
  690:                     my $imszip = '/home/httpd/'.$imszipfile;
  691:                     chdir $tempexport;
  692:                     open(OUTPUT, "zip -r $imszip *  2> /dev/null |");
  693:                     close(OUTPUT);
  694:                     chdir $cwd;
  695:                     $discussion .= &mt('Download the zip file from [_1]Discussion Posting Archive','<a href="'.$imszipfile.'">').'</a><br />';
  696:                     if ($copyresult) {
  697:                         $discussion .= &mt('The following errors occurred during export').' - <br />'.$copyresult;
  698:                     }
  699:                 }
  700:             } else {
  701:                 $discussion .= '<br />'.&mt('Unfortunately you will not be able to retrieve an archive of the discussion posts at this time, because there was a problem creating a manifest file.').'<br />';
  702:             }
  703:             return $discussion;
  704:         }
  705:     }
  706:     if ($discussiononly) {
  707:         my $now = time;
  708:         my $attachnum = 0;
  709:         my $currnewattach = [];
  710:         my $currdelold = [];
  711:         my $comment = '';
  712:         my $subject = '';
  713:         if ($env{'form.origpage'}) {
  714:             &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['addnewattach','deloldattach','delnewattach','timestamp','idx','subject','comment']);
  715:             $subject = &unescape($env{'form.subject'});
  716:             $comment = &unescape($env{'form.comment'});
  717:             my @keepold = ();
  718:             &process_attachments($currnewattach,$currdelold,\@keepold);
  719:             if (@{$currnewattach} > 0) {
  720:                 $attachnum += @{$currnewattach};
  721:             }
  722:         }
  723: 	if (&discussion_open($status)) {
  724:             if (($group ne '') && ($mode eq 'board')) {  
  725:                 if (&check_group_priv($group,'pgd') eq 'ok') {
  726:                     $discussion .=
  727: 			&postingform_display($mode,$ressymb,$now,$subject,
  728: 					     $comment,$outputtarget,$attachnum,
  729: 					     $currnewattach,$currdelold,
  730: 					     $group,$crstype);
  731:                 }
  732:             } else {
  733: 	        $discussion.= 
  734: 		    &postingform_display($mode,$ressymb,$now,$subject,
  735: 					 $comment,$outputtarget,$attachnum,
  736: 					 $currnewattach,$currdelold,'',$crstype);
  737:             }
  738: 	}
  739:     } else {
  740:         $discussion.='<div class="LC_feedback_link">';
  741:         if (&discussion_open($status) &&
  742:             &Apache::lonnet::allowed('pch',
  743:     	        $env{'request.course.id'}.
  744: 	        ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) {
  745: 	    if ($outputtarget ne 'tex') {
  746: 		$discussion.= &send_feedback_link($ressymb,$target);
  747:             }
  748: 	}
  749:         if ($outputtarget ne 'tex') {
  750: 	    $discussion.= &send_message_link($ressymb);
  751:         }
  752:         $discussion.='</div>';
  753:     }
  754:     return $discussion;
  755: }
  756: 
  757: sub send_feedback_link {
  758:     my ($ressymb,$target) = @_;
  759:     my $output = '<span class="LC_feedback_link">'.
  760:                  ' <a href="/adm/feedback?replydisc='.
  761:                  &escape($ressymb).':::" '.$target.'>'.
  762:                  '<img alt="" class="LC_noBorder" src="'.
  763:                  &Apache::loncommon::lonhttpdurl('/adm/lonMisc/chat.gif').
  764:                  '" border="0" /><span class="LC_menubuttons_inline_text">'.&mt('Post Discussion').'</span></a></span>';
  765:     return $output;
  766: }
  767: 
  768: sub send_message_link {
  769:     my ($ressymb) = @_;
  770:     my $output = '<span class="LC_message_link">'.
  771:                  '  <a href="/adm/feedback?sendmessageonly=1&amp;symb='.
  772:                  &escape($ressymb).'"><img alt="" class="LC_noBorder" src="'.
  773:                  &Apache::loncommon::lonhttpdurl('/res/adm/pages/com.png').
  774:                  '" border="0" /><span class="LC_menubuttons_inline_text">'.&mt('Send Feedback').'</span></a></span>';
  775:     return $output;
  776: }
  777: 
  778: sub action_links_bar {
  779:     my ($colspan,$ressymb,$visible,$newpostsflag,$group,$prevread,$markondisp) = @_;
  780:     my $discussion = '<tr><td class="LC_disc_action_links_bar" colspan="'.$colspan.'">'.
  781:                      '<table width="100%" class="LC_disc_action_table"><tr>'.
  782:                      '<td class="LC_disc_action_left">';
  783:     my $escsymb=&escape($ressymb);
  784:     if ($visible>2) {
  785:         $discussion .= '<a href="/adm/feedback?cmd=threadedon&amp;symb='.$escsymb;
  786:         if ($newpostsflag) {
  787:             $discussion .= '&previous='.$prevread;
  788:         }
  789:         $discussion .= &group_args($group);
  790:         $discussion .='">'.&mt('Threaded View').'</a>&nbsp;&nbsp;'.
  791:                       '<a href="/adm/feedback?cmd=threadedoff&amp;symb='.$escsymb;
  792:         if ($newpostsflag) {
  793:             $discussion .= '&previous='.$prevread;
  794:         }
  795:         $discussion .= &group_args($group);
  796:         $discussion .='">'.&mt('Chronological View').'</a>&nbsp;&nbsp;
  797:                        <a href="/adm/feedback?cmd=sortfilter&amp;symb='.$escsymb;
  798:         if ($newpostsflag) {
  799:             $discussion .= '&previous='.$prevread;
  800:         }
  801:         $discussion .= &group_args($group);
  802:         $discussion .='">'.&mt('Sorting/Filtering options').'</a>'.('&nbsp;' x2);
  803:     }
  804:     $discussion .='<a href="/adm/feedback?export='.$escsymb;
  805:     if ($newpostsflag) {
  806:         $discussion .= '&previous='.$prevread;
  807:     }
  808:     $discussion .= &group_args($group);
  809:     $discussion .= '">'.&mt('Export').'?</a>&nbsp;&nbsp;</td>';
  810:     if ($newpostsflag) {
  811:         if (!$markondisp) {
  812:             $discussion .='<td class="LC_disc_action_right"><a href="/adm/preferences?action=changediscussions';
  813:             $discussion .= &group_args($group);
  814:             $discussion .= '">'.
  815:                            &mt('Preferences on what is marked as NEW').
  816:                            '</a><br /><a href="/adm/feedback?markread=1&amp;symb='.$escsymb;
  817:             $discussion .= &group_args($group);
  818:             $discussion .= '">'.&mt('Mark NEW posts no longer new').'</a>';
  819:         } else {
  820:             $discussion .= '<td>&nbsp;</td>';
  821:         }
  822:     } else {
  823:         $discussion .= '<td>&nbsp;</td>';
  824:     }
  825:     $discussion .= '</tr></table></td></tr>';
  826:     return $discussion;
  827: }
  828: 
  829: sub postingform_display {
  830:     my ($mode,$ressymb,$now,$subject,$comment,$outputtarget,$attachnum,
  831:         $currnewattach,$currdelold,$group,$crstype) = @_;
  832:     my $newattachmsg;
  833:     my %lt = &Apache::lonlocal::texthash(
  834:               'note' => 'Note: in anonymous discussion, your name is visible only to course faculty',
  835:              'title' => 'Title',
  836:              'podi' => 'Post Discussion',
  837:              'poan' => 'Post Anonymous Discussion',
  838:              'newa' => 'New attachments',
  839:     );
  840:     if ($crstype eq 'Community') {
  841:         $lt{'note'} = &mt('Note: in anonymous discussion, your name is visible only to community facilitators');
  842:     }
  843:     my $postingform = (<<ENDDISCUSS);
  844: <form action="/adm/feedback" method="post" name="mailform" enctype="multipart/form-data"> <input type="submit" name="discuss" value="$lt{'podi'}" />
  845: <input type="submit" name="anondiscuss" value="$lt{'poan'}" /> <input type="hidden" name="symb" value="$ressymb" />
  846: <input type="hidden" name="sendit" value="true" />
  847: <input type="hidden" name="timestamp" value="$now" />
  848: <br /><a name="newpost"></a>
  849: <font size="1">$lt{'note'}</font><br />
  850: <b>$lt{'title'}:</b>&nbsp;<input type="text" name="subject" value="$subject" size="30" /><br /><br />
  851: <textarea name="comment" cols="80" rows="14" wrap="hard">$comment</textarea>
  852: ENDDISCUSS
  853:     if ($env{'form.origpage'}) {
  854:         $postingform .= '<input type="hidden" name="origpage" value="'.
  855:                         $env{'form.origpage'}.'" />'."\n";
  856:         foreach my $att (@{$currnewattach}) {
  857:             $postingform .= '<input type="hidden" name="currnewattach" '.
  858:                             'value="'.$att.'" />'."\n";
  859:         }
  860:     }
  861:     if (exists($env{'form.ref'})) {
  862:         $postingform .= '<input type="hidden" name="ref" value="'.
  863:                         $env{'form.ref'}.'" />';
  864:     }
  865:     if ($group ne '') {
  866:         $postingform .='<input type="hidden" name="group" value="'.$group.'" />';
  867:     }
  868:     my $blockblog = &Apache::loncommon::blocking_status('blogs');
  869:     if (!$blockblog) {
  870:         $postingform .= &add_blog_checkbox($crstype);
  871:     }
  872:     $postingform .= "</form>\n";
  873:     if ($outputtarget ne 'tex') {
  874:         $postingform .= &generate_attachments_button('',$attachnum,$ressymb,
  875:                                                      $now,$currnewattach,
  876:                                                      $currdelold,'',$mode,
  877:                                                      $blockblog);
  878:         if ((ref($currnewattach) eq 'ARRAY') && (@{$currnewattach} > 0)) {
  879:             $newattachmsg = '<br /><b>'.$lt{'newa'}.'</b><br />';
  880:             if (@{$currnewattach} > 1) {
  881:                 $newattachmsg .= '<ol>';
  882:                 foreach my $item (@{$currnewattach}) {
  883:                     $item =~ m#.*/([^/]+)$#;
  884:                     $newattachmsg .= '<li><a href="'.$item.'">'.$1.'</a></li>'."\n";
  885:                 }
  886:                 $newattachmsg .= '</ol>'."\n";
  887:             } else {
  888:                 $$currnewattach[0] =~ m#.*/([^/]+)$#;
  889:                 $newattachmsg .= '<a href="'.$$currnewattach[0].'">'.$1.'</a><br />'."\n";
  890:             }
  891:         }
  892:         $postingform .= $newattachmsg;
  893:         $postingform .= &generate_preview_button();
  894:     }
  895:     return $postingform;
  896: }
  897: 
  898: sub build_posting_display {
  899:     my ($usernamesort,$subjectsort,$namesort,$notshown,$newitem,$dischash,$shown,$alldiscussion,$imsitems,$imsfiles,$roleinfo,$discussionitems,$replies,$depth,$posters,$maxdepth,$visible,$newpostsflag,$current,$status,$viewgrades,$seeid,$prevread,$sortposts,$ressymb,$target,$readkey,$showunmark,$showonlyunread,$totposters,$rolefilter,$sectionpick,$grouppick,$classgroups,$statusfilter,$toggkey,$outputtarget,$anonhash,$anoncnt,$group) = @_;
  900:     my @original=();
  901:     my @index=();
  902:     my $skip_group_check = 0;
  903:     my $symb=&Apache::lonenc::check_decrypt($ressymb);
  904:     my $escsymb=&escape($ressymb);
  905:     my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
  906: 			  $env{'course.'.$env{'request.course.id'}.'.domain'},
  907: 			  $env{'course.'.$env{'request.course.id'}.'.num'});
  908: 
  909:     my $see_anonymous = 
  910: 	&Apache::lonnet::allowed('rin',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''));
  911: 
  912:     if ((@{$grouppick} == 0) || (grep(/^all$/,@{$grouppick}))) {
  913:         $skip_group_check = 1;
  914:     }
  915:     if ($contrib{'version'}) {
  916:         my $oldest = $contrib{'1:timestamp'};
  917:         if ($prevread eq '0') {
  918:             $prevread = $oldest-1;
  919:         }
  920:         my ($skiptest,$rolematch,$roleregexp,$secregexp,$statusregexp);
  921:         if ($sortposts) {
  922:             ($skiptest,$roleregexp,$secregexp,$statusregexp) = 
  923:                      &filter_regexp($rolefilter,$sectionpick,$statusfilter);
  924:             $rolematch = $roleregexp.':'.$secregexp.':'.$statusregexp;
  925:         } 
  926: 	for (my $id=1;$id<=$contrib{'version'};$id++) {
  927: 	    my $idx=$id;
  928:             my $posttime = $contrib{$idx.':timestamp'};
  929:             if ($prevread <= $posttime) {
  930:                 $$newpostsflag = 1;
  931:             }
  932: 	    my $hidden=($contrib{'hidden'}=~/\.$idx\./);
  933:             my $studenthidden=($contrib{'studenthidden'}=~/\.$idx\./);
  934: 	    my $deleted=($contrib{'deleted'}=~/\.$idx\./);
  935: 	    my $origindex='0.';
  936:             my $numoldver=0;
  937: 	    if ($contrib{$idx.':replyto'}) {
  938:                 if ( (($env{'environment.threadeddiscussion'}) && ($sortposts eq '')) || ($sortposts eq 'thread') || ($outputtarget eq 'export')) {
  939: # this is a follow-up message
  940: 		    $original[$idx]=$original[$contrib{$idx.':replyto'}];
  941: 		    $$depth[$idx]=$$depth[$contrib{$idx.':replyto'}]+1;
  942: 		    $origindex=$index[$contrib{$idx.':replyto'}];
  943: 		    if ($$depth[$idx]>$$maxdepth) { $$maxdepth=$$depth[$idx]; }
  944:                 } else {
  945:                     $original[$idx]=0;
  946:                     $$depth[$idx]=0;
  947:                 }
  948: 	    } else {
  949: # this is an original message
  950: 		$original[$idx]=0;
  951: 		$$depth[$idx]=0;
  952: 	    }
  953: 	    if ($$replies[$$depth[$idx]]) {
  954: 		$$replies[$$depth[$idx]]++;
  955: 	    } else {
  956: 		$$replies[$$depth[$idx]]=1;
  957: 	    }
  958: 	    unless ((($hidden) && (!$seeid)) || ($deleted)) {
  959: 		$$visible++;
  960:                 if ($contrib{$idx.':history'}) {
  961:                     if ($contrib{$idx.':history'} =~ /:/) {
  962:                         my @oldversions = split(/:/,$contrib{$idx.':history'});
  963:                         $numoldver = @oldversions;
  964:                     } else {
  965:                         $numoldver = 1;
  966:                     } 
  967:                 }
  968:                 $$current = $numoldver;
  969: 		my %messages = ();
  970:                 my %subjects = ();
  971:                 my %attachtxt = ();
  972:                 my %allattachments = ();
  973:                 my ($screenname,$plainname);
  974:                 my $sender = &mt('Anonymous');
  975: # Anonymous users getting number within a discussion
  976: # Since idx is in static order, this should give the same sequence every time. 
  977: 		my $key=$contrib{$idx.':sendername'}.'@'.$contrib{$idx.':senderdomain'};
  978: 		unless ($$anonhash{$key}) {
  979:                     $anoncnt++;
  980: 		    $$anonhash{$key}=&mt('Anonymous').' '.$anoncnt;
  981: 		}
  982:                 my ($message,$subject,$vgrlink,$ctlink);
  983:                 &get_post_contents(\%contrib,$idx,$seeid,$outputtarget,\%messages,\%subjects,\%allattachments,\%attachtxt,$imsfiles,\$screenname,\$plainname,$numoldver);
  984: 
  985: 
  986: # Set up for sorting by subject
  987:                 unless ($outputtarget eq 'export') {
  988:                     $message=$messages{$numoldver};
  989:                     $message.=$attachtxt{$numoldver};
  990:                     $subject=$subjects{$numoldver};
  991:                     if ($message) {
  992: 	  	        if ($hidden) {
  993: 			    $message='<font color="#888888">'.$message.'</font>';
  994:                             if ($studenthidden) {
  995:                                 $message .='<br /><br />Deleted by poster (student).';
  996:                             }
  997: 		        }
  998: 
  999:                         if ($subject eq '') {
 1000:                            if (defined($$subjectsort{'__No subject'})) {
 1001:                                push(@{$$subjectsort{'__No subject'}}, $idx);
 1002:                            } else {
 1003:                                @{$$subjectsort{'__No subject'}} = ("$idx");
 1004:                            }
 1005:                         } else {
 1006:                             if (defined($$subjectsort{$subject})) {
 1007:                                push(@{$$subjectsort{$subject}}, $idx);
 1008:                             } else {
 1009:                                @{$$subjectsort{$subject}} = ("$idx");
 1010:                             }
 1011:                         }
 1012: 		        if (!$contrib{$idx.':anonymous'} || $see_anonymous) {
 1013: 			    $sender=&Apache::loncommon::aboutmewrapper(
 1014: 					 $plainname,
 1015: 					 $contrib{$idx.':sendername'},
 1016: 					 $contrib{$idx.':senderdomain'}).' ('.
 1017: 					 $contrib{$idx.':sendername'}.':'.
 1018: 					 $contrib{$idx.':senderdomain'}.')';
 1019: 			    if ($contrib{$idx.':anonymous'}) {
 1020: 			        $sender.=' <font color="red"><b>['.$$anonhash{$key}.']</b></font> '.
 1021: 				    $screenname;
 1022: 			    }
 1023: 			    if ($see_anonymous) {
 1024: 				$sender.=&Apache::loncommon::student_image_tag($contrib{$idx.':senderdomain'},$contrib{$idx.':sendername'});
 1025: 			    }
 1026: # Set up for sorting by domain, then username
 1027:                             unless (defined($$usernamesort{$contrib{$idx.':senderdomain'}})) {
 1028:                                 %{$$usernamesort{$contrib{$idx.':senderdomain'}}} = ();
 1029:                             }
 1030:                             if (defined($$usernamesort{$contrib{$idx.':senderdomain'}}{$contrib{$idx.':sendername'}})) {
 1031:                                 push(@{$$usernamesort{$contrib{$idx.':senderdomain'}}{$contrib{$idx.':sendername'}}}, $idx);
 1032:                             } else {
 1033:                                 @{$$usernamesort{$contrib{$idx.':senderdomain'}}{$contrib{$idx.':sendername'}}} = ("$idx");
 1034:                             }
 1035: # Set up for sorting by last name, then first name
 1036:                             my %names = &Apache::lonnet::get('environment',
 1037:                                  ['firstname','lastname'],$contrib{$idx.':senderdomain'},
 1038:                                   ,$contrib{$idx.':sendername'});
 1039:                             my $lastname = $names{'lastname'};
 1040:                             my $firstname = $names{'firstname'};
 1041:                             if ($lastname eq '') {
 1042:                                 $lastname = '_';
 1043:                             }
 1044:                             if ($firstname eq '') {
 1045:                                 $firstname = '_';
 1046:                             }
 1047:                             unless (defined($$namesort{$lastname})) {
 1048:                                 %{$$namesort{$lastname}} = ();
 1049:                             }
 1050:                             if (defined($$namesort{$lastname}{$firstname})) {
 1051:                                 push(@{$$namesort{$lastname}{$firstname}}, $idx);
 1052:                             } else {
 1053:                                 @{$$namesort{$lastname}{$firstname}} = ("$idx");
 1054:                             }
 1055:                             if (&editing_allowed($escsymb.':::'.$idx,$group)) {
 1056:                                 if (($env{'user.domain'} eq $contrib{$idx.':senderdomain'}) && ($env{'user.name'} eq $contrib{$idx.':sendername'})) {
 1057:                                     $sender.=' <a href="/adm/feedback?editdisc='.
 1058:                                          $escsymb.':::'.$idx;
 1059:                                     if ($$newpostsflag) {
 1060:                                         $sender .= '&previous='.$prevread;
 1061:                                     }
 1062: 				    $sender .= &group_args($group);
 1063:                                     $sender .= '" '.$target.'>'.&mt('Edit').'</a>';
 1064:                                     
 1065:                                     unless ($seeid) {
 1066:                                         my $grpargs = &group_args($group);
 1067:                                         $sender.=" <a href=\"javascript:verifydelete('studentdelete','$escsymb','$idx','$$newpostsflag','$prevread','$grpargs')";
 1068:                                         $sender .= '">'.&mt('Delete').'</a>';
 1069:                                     }
 1070:                                 }
 1071:                             } 
 1072: 			    if ($seeid) {
 1073: 			        if ($hidden) {
 1074:                                     unless ($studenthidden) {
 1075: 			                $sender.=' <a href="/adm/feedback?unhide='.
 1076: 				                $escsymb.':::'.$idx;
 1077:                                         if ($$newpostsflag) {
 1078:                                             $sender .= '&previous='.$prevread;
 1079:                                         }
 1080:                                         $sender .= '">'.&mt('Make Visible').'</a>';
 1081:                                     }
 1082: 			        } else {
 1083: 				    $sender.=' <a href="/adm/feedback?hide='.
 1084: 				        $escsymb.':::'.$idx;
 1085:                                     if ($$newpostsflag) {
 1086:                                         $sender .= '&previous='.$prevread;
 1087:                                     }
 1088: 				    $sender .= &group_args($group);
 1089:                                     $sender .= '">'.&mt('Hide').'</a>';
 1090: 			        }
 1091:                                 my $grpargs = &group_args($group);
 1092: 			        $sender.= 
 1093:                                     " <a href=\"javascript:verifydelete('seeiddelete','$escsymb','$idx','$$newpostsflag','$prevread','$grpargs')\">";
 1094:                                 $sender .= &mt('Delete').'</a>';
 1095:                             }
 1096: 		        } else {
 1097: 			    if ($screenname) {
 1098: 			        $sender='<i>'.$screenname.'</i>';
 1099: 			    } else {
 1100: 				$sender='<i>'.$$anonhash{$key}.'</i>';
 1101: 			    }
 1102: # Set up for sorting by domain, then username for anonymous
 1103:                             unless (defined($$usernamesort{'__anon'})) {
 1104:                                 %{$$usernamesort{'__anon'}} = ();
 1105:                             }
 1106:                             if (defined($$usernamesort{'__anon'}{'__anon'})) {
 1107:                                 push(@{$$usernamesort{'__anon'}{'__anon'}}, $idx);
 1108:                             } else {
 1109:                                 @{$$usernamesort{'__anon'}{'__anon'}} = ("$idx");
 1110:                             }
 1111: # Set up for sorting by last name, then first name for anonymous
 1112:                             unless (defined($$namesort{'__anon'})) {
 1113:                                 %{$$namesort{'__anon'}} = ();
 1114:                             }
 1115:                             if (defined($$namesort{'__anon'}{'__anon'})) {
 1116:                                 push(@{$$namesort{'__anon'}{'__anon'}}, $idx);
 1117:                             } else {
 1118:                                 @{$$namesort{'__anon'}{'__anon'}} = ("$idx");
 1119:                             }
 1120: 		        }
 1121: 		        if (&discussion_open($status)) {
 1122:                             if (($group ne '') && 
 1123:                                 (&check_group_priv($group,'pgd') eq 'ok')) {
 1124:                                  $sender.=' <a href="/adm/feedback?replydisc='.
 1125:                                           $escsymb.':::'.$idx;
 1126:                                 if ($$newpostsflag) {
 1127:                                     $sender .= '&previous='.$prevread;
 1128:                                 }
 1129:                                 $sender .= &group_args($group);
 1130:                                 $sender .= '" '.$target.'>'.&mt('Reply').'</a>';
 1131:                             } elsif (&Apache::lonnet::allowed('pch', 
 1132: 				 $env{'request.course.id'}.
 1133: 				 ($env{'request.course.sec'}?'/'.
 1134:                                   $env{'request.course.sec'}:''))) {
 1135: 			         $sender.=' <a href="/adm/feedback?replydisc='.
 1136: 			                  $escsymb.':::'.$idx;
 1137:                                 if ($$newpostsflag) {
 1138:                                     $sender .= '&previous='.$prevread;
 1139:                                 }
 1140:                                 $sender .= '" '.$target.'>'.&mt('Reply').'</a>';
 1141:                             }
 1142:                         }
 1143: 		        if ($viewgrades) {
 1144: 			        $vgrlink=&Apache::loncommon::submlink('Submissions',
 1145:                             $contrib{$idx.':sendername'},$contrib{$idx.':senderdomain'},$ressymb);
 1146: 		        }
 1147:                         if ($$dischash{$readkey}=~/\.$idx\./) { 
 1148:                             $ctlink = '<label><b>'.&mt('Mark unread').'?</b>&nbsp;<input type="checkbox" name="postunread_'.$idx.'" /></label>';
 1149:                         } else {
 1150:                             $ctlink = '<label><b>'.&mt('Mark read').'?</b>&nbsp;<input type="checkbox" name="postread_'.$idx.'" /></label>';
 1151:                         }
 1152:                     }
 1153: #figure out at what position this needs to print
 1154:                 }
 1155:                 if ($outputtarget eq 'export' || $message) {
 1156: 		    my $thisindex=$idx;
 1157: 		    if ( (($env{'environment.threadeddiscussion'}) && ($sortposts eq '')) || ($sortposts eq 'thread') || ($outputtarget eq 'export')) {
 1158: 			$thisindex=$origindex.substr('00'.$$replies[$$depth[$idx]],-2,2);
 1159: 		    }
 1160: 		    $$alldiscussion{$thisindex}=$idx;
 1161:                     $$shown{$idx} = 0;
 1162:                     $index[$idx]=$thisindex;
 1163:                 }
 1164:                 if ($outputtarget eq 'export') {
 1165:                     %{$$imsitems{$idx}} = ();
 1166:                     $$imsitems{$idx}{'isvisible'}='true';
 1167:                     if ($hidden) {
 1168:                         $$imsitems{$idx}{'isvisible'}='false';
 1169:                     }
 1170:                     $$imsitems{$idx}{'title'}=$subjects{$numoldver};
 1171:                     $$imsitems{$idx}{'message'}=$messages{$numoldver};
 1172:                     $$imsitems{$idx}{'attach'}=$attachtxt{$numoldver};
 1173:                     $$imsitems{$idx}{'timestamp'}=$contrib{$idx.':timestamp'};
 1174:                     $$imsitems{$idx}{'sender'}=$plainname.' ('.
 1175:                                          $contrib{$idx.':sendername'}.':'.
 1176:                                          $contrib{$idx.':senderdomain'}.')';
 1177:                     $$imsitems{$idx}{'isanonymous'}='false';
 1178:                     if ($contrib{$idx.':anonymous'}) {
 1179:                         $$imsitems{$idx}{'isanonymous'}='true';
 1180:                     }
 1181:                     $$imsitems{$idx}{'currversion'}=$numoldver;
 1182:                     %{$$imsitems{$idx}{'allattachments'}}=%allattachments;
 1183:                     unless ($messages{$numoldver} eq '' && $attachtxt{$numoldver} eq '') {
 1184:                         $$shown{$idx} = 1;
 1185:                     }
 1186:                 } else {
 1187:                     if ($message) {
 1188:                         my $spansize = 2;
 1189:                         if ($showonlyunread && $prevread > $posttime) {
 1190:                             $$notshown{$idx} = 1;
 1191:                         } elsif ($showunmark && $$dischash{$readkey}=~/\.$idx\./) {
 1192:                             $$notshown{$idx} = 1;
 1193:                         } else {
 1194: # apply filters
 1195:                             my $uname = $contrib{$idx.':sendername'};
 1196:                             my $udom = $contrib{$idx.':senderdomain'};
 1197:                             my $poster = $uname.':'.$udom;
 1198:                             if ($env{'form.totposters'} ne '') {
 1199:                                 if ($totposters == 0) {
 1200:                                     $$shown{$idx} = 0;
 1201:                                 } elsif ($totposters > 0) {
 1202:                                     if (grep/^$poster$/,@{$posters}) {
 1203:                                         $$shown{$idx} = 1;
 1204:                                     }
 1205:                                 }
 1206:                             } elsif ($sortposts) {
 1207:                                 if ($skiptest) {
 1208:                                     $$shown{$idx} = 1;
 1209:                                 } else {
 1210:                                     foreach my $role (@{$$roleinfo{$poster}}) {
 1211:                                         if ($role =~ /^cc:/) {
 1212:                                             my $cc_regexp = $roleregexp.':[^:]*:'.$statusregexp;
 1213:                                             if ($role =~ /$cc_regexp/) {
 1214:                                                 $$shown{$idx} = 1;
 1215:                                                 last;
 1216:                                             }
 1217:                                         } elsif ($role =~ /^$rolematch$/) {
 1218:                                             $$shown{$idx} = 1;
 1219:                                             last;
 1220:                                         }
 1221:                                     }
 1222:                                 }
 1223:                                 if ($$shown{$idx} && !$skip_group_check) {
 1224:                                     my $showflag = 0;
 1225:                                     if (ref($$classgroups{$poster}{active}) eq 'HASH') {
 1226:                                         foreach my $grp (@{$grouppick}) {
 1227:                                             if (grep/^\Q$grp\E$/,
 1228:                                  keys(%{$$classgroups{$poster}{active}})) {
 1229:                                                 $showflag = 1;
 1230:                                                 last;
 1231:                                             }
 1232:                                         }
 1233:                                     }
 1234:                                     if ($showflag) {
 1235:                                         $$shown{$idx} = 1;
 1236:                                     } else {
 1237:                                         $$shown{$idx} = 0;
 1238:                                     }
 1239:                                 }
 1240:                             } else {
 1241:                                 $$shown{$idx} = 1;
 1242:                             }
 1243:                         }
 1244:                         unless ($$notshown{$idx} == 1) {
 1245:                             if ($prevread > 0 && $prevread <= $posttime) {
 1246:                                 $$newitem{$idx} = 1;
 1247:                                 $$discussionitems[$idx] .= '
 1248:                                  <p><table border="0" width="100%">
 1249:                                   <tr><td align="left"><font color="#FF0000"><b>'.&mt('NEW').'</b></font></td>';
 1250:                             } else {
 1251:                                 $$newitem{$idx} = 0;
 1252:                                 $$discussionitems[$idx] .= '
 1253:                                  <p><table border="0" width="100%">
 1254:                                   <tr><td align="left">&nbsp;</td>';
 1255:                             }
 1256:                             $$discussionitems[$idx] .= '<td align="left">&nbsp;&nbsp;'.
 1257:                                 '<b>'.$subject.'</b>&nbsp;&nbsp;'.
 1258:                                 $sender.'</b> '.$vgrlink.' ('.
 1259:                                 &Apache::lonlocal::locallocaltime($posttime).')</td>';
 1260:                             if ($$dischash{$toggkey}) {
 1261:                                 $$discussionitems[$idx].='<td align="right">&nbsp;&nbsp;'.
 1262:                                   $ctlink.'</td>';
 1263:                             }
 1264:                             $$discussionitems[$idx].= '</tr></table><blockquote>'.
 1265:                                     $message.'</blockquote></p>';
 1266:                             if ($contrib{$idx.':history'}) {
 1267:                                 my @postversions = ();
 1268:                                 $$discussionitems[$idx] .= &mt('This post has been edited by the author.');
 1269:                                 if ($seeid) {
 1270:                                     $$discussionitems[$idx] .= '&nbsp;&nbsp;<a href="/adm/feedback?allversions='.$escsymb.':::'.$idx;
 1271: 				    $$discussionitems[$idx] .= &group_args($group);
 1272:                                     $$discussionitems[$idx] .= '">'.&mt('Display all versions').'</a>';
 1273:                                 }
 1274:                                 $$discussionitems[$idx].='<br/>'.&mt('Earlier version(s) were posted on: ');
 1275:                                 if ($contrib{$idx.':history'} =~ m/:/) {
 1276:                                     @postversions = split(/:/,$contrib{$idx.':history'});
 1277:                                 } else {
 1278:                                     @postversions = ("$contrib{$idx.':history'}");
 1279:                                 }
 1280:                                 for (my $i=0; $i<@postversions; $i++) {
 1281:                                     my $version = $i+1;
 1282:                                     $$discussionitems[$idx] .= '<b>'.$version.'.</b> - '.&Apache::lonlocal::locallocaltime($postversions[$i]).'  ';
 1283:                                 }
 1284:                             }
 1285:                         }
 1286:                     }
 1287:                 }
 1288:             }
 1289: 	}
 1290:     }
 1291: }
 1292: 
 1293: sub filter_regexp {
 1294:     my ($rolefilter,$sectionpick,$statusfilter) = @_;
 1295:     my ($roleregexp,$secregexp,$statusregexp);
 1296:     my $skiptest = 1;
 1297:     if (@{$rolefilter} > 0) {
 1298:         my @okrolefilter = ();
 1299:         foreach my $role (@{$rolefilter}) {
 1300:             unless ($role eq '') {
 1301:                 push(@okrolefilter, $role);
 1302:             }
 1303:         }
 1304:         if (@okrolefilter > 0) {
 1305:             if (grep/^all$/,@okrolefilter) {
 1306:                 $roleregexp='[^:]+';
 1307:             } else {
 1308:                 if (@okrolefilter == 1) {
 1309:                     $roleregexp=$okrolefilter[0];
 1310:                 } else {
 1311:                     $roleregexp='('.join('|',@okrolefilter).')';
 1312:                 }
 1313:                 $skiptest = 0;
 1314:             }
 1315:         }
 1316:     }
 1317:     if (@{$sectionpick} > 0) {
 1318:         my @oksectionpick = ();
 1319:         foreach my $sec (@{$sectionpick}) {
 1320:             unless ($sec eq '') {
 1321:                  push(@oksectionpick, $sec);
 1322:             }
 1323:         }
 1324:         if ((@oksectionpick > 0) && (!grep/^all$/,@oksectionpick)) {
 1325:             if (@oksectionpick == 1) {
 1326:                 $secregexp = $oksectionpick[0];
 1327:             } else {
 1328:                 $secregexp .= '('.join('|',@oksectionpick).')';
 1329:             }
 1330:             $skiptest = 0;
 1331:         } else {
 1332:             $secregexp .= '[^:]*';
 1333:         }
 1334:     }
 1335: 
 1336:     if (defined($statusfilter) && $statusfilter ne '') {
 1337:         if ($statusfilter eq 'all') {
 1338:             $statusregexp = '[^:]+';
 1339:         } else {
 1340:             $statusregexp = $statusfilter;
 1341:             $skiptest = 0;
 1342:         }
 1343:     }
 1344:     return ($skiptest,$roleregexp,$secregexp,$statusregexp);
 1345: }
 1346: 
 1347: 
 1348: sub get_post_contents {
 1349:     my ($contrib,$idx,$seeid,$type,$messages,$subjects,$allattachments,$attachtxt,$imsfiles,$screenname,$plainname,$numver) = @_;
 1350:     my $discussion = '';
 1351:     my $start=$numver;
 1352:     my $end=$numver + 1;
 1353:     %{$$imsfiles{$idx}}=();
 1354:     if ($type eq 'allversions') {
 1355:        unless($seeid) {
 1356:            $discussion=&mt('You do not have privileges to view all versions of posts.').' '.&mt('Please select a different role.');
 1357:            return $discussion;
 1358:        } 
 1359:     }
 1360: #    $$screenname=&Apache::loncommon::screenname(
 1361: #                                        $$contrib{$idx.':sendername'},
 1362: #                                        $$contrib{$idx.':senderdomain'});
 1363:     $$plainname=&Apache::loncommon::nickname(
 1364:                                         $$contrib{$idx.':sendername'},
 1365:                                         $$contrib{$idx.':senderdomain'});
 1366:     $$screenname=$$contrib{$idx.':screenname'};
 1367: 
 1368:     my $sender=&Apache::loncommon::aboutmewrapper(
 1369:                                  $$plainname,
 1370:                                  $$contrib{$idx.':sendername'},
 1371:                                  $$contrib{$idx.':senderdomain'}).' ('.
 1372:                                  $$contrib{$idx.':sendername'}.':'.
 1373:                                  $$contrib{$idx.':senderdomain'}.')';
 1374:     my $attachmenturls = $$contrib{$idx.':attachmenturl'};
 1375:     my @postversions = ();
 1376:     if ($type eq 'allversions' || $type eq 'export') {
 1377:         $start = 0;
 1378:         if ($$contrib{$idx.':history'}) {
 1379: 	    @postversions = split(/:/,$$contrib{$idx.':history'});
 1380:         }
 1381:         &get_post_versions($messages,$$contrib{$idx.':message'},1);
 1382:         &get_post_versions($subjects,$$contrib{$idx.':subject'},1);
 1383:         push(@postversions,$$contrib{$idx.':timestamp'});
 1384:         $end = @postversions;
 1385:     } else {
 1386:         &get_post_versions($messages,$$contrib{$idx.':message'},1,$numver);
 1387:         &get_post_versions($subjects,$$contrib{$idx.':subject'},1,$numver);
 1388:     }
 1389: 
 1390:     if ($$contrib{$idx.':anonymous'}) {
 1391:         $sender.=' ['.&mt('anonymous').'] '.$$screenname;
 1392:     }
 1393:     if ($type eq 'allversions') {
 1394:         $discussion=('<b>'.$sender.'</b><br /><ul>');
 1395:     }
 1396:     for (my $i=$start; $i<$end; $i++) {
 1397:         my ($timesent,$attachmsg);
 1398:         my %currattach = ();
 1399:         $timesent = &Apache::lonlocal::locallocaltime($postversions[$i]);
 1400: 	&newline_to_br(\$messages->{$i});
 1401:         $$messages{$i}=&Apache::lontexconvert::msgtexconverted($$messages{$i});
 1402:         $$subjects{$i}=~s/\n/\<br \/\>/g;
 1403:         $$subjects{$i}=&Apache::lontexconvert::msgtexconverted($$subjects{$i});
 1404:         if ($attachmenturls) {
 1405:             &extract_attachments($attachmenturls,$idx,$i,\$attachmsg,$allattachments,\%currattach);
 1406:         }
 1407:         if ($type eq 'export') {
 1408:             $$imsfiles{$idx}{$i} = '';
 1409:             if ($attachmsg) {
 1410:                 $$attachtxt{$i} = '<br />'.&mt('Attachments').':<br />';
 1411:                 foreach my $key (sort(keys(%currattach))) {
 1412:                     if ($$allattachments{$key}{'filename'} =~ m-^/uploaded/([^/]+/[^/]+)(/feedback)?(/?\d*)/([^/]+)$-) {
 1413:                         my $fname = $1.$3.'/'.$4;
 1414:                         $$imsfiles{$idx}{$i} .= '<file href="'.$fname.'">'."\n";
 1415:                         $$attachtxt{$i}.= '<a href="'.$fname.'">'.$4.'</a><br />';
 1416:                     }
 1417:                 }
 1418:             }
 1419:         } else {
 1420:             if ($attachmsg) {
 1421:                 $$attachtxt{$i} = '<br />'.&mt('Attachments').':'.$attachmsg.'<br />';
 1422:             } else {
 1423:                 $$attachtxt{$i} = '';
 1424:             }
 1425:         }
 1426:         if ($type eq 'allversions') {
 1427:             $discussion.= <<"END";
 1428: <li><b>$$subjects{$i}</b>, $timesent<br />
 1429: $$messages{$i}<br />
 1430: $$attachtxt{$i}</li>
 1431: END
 1432:         }
 1433:     }
 1434:     if ($type eq 'allversions') {
 1435:         $discussion.='</ul>';
 1436:         return $discussion;
 1437:     } else {
 1438:         return;
 1439:     }
 1440: }
 1441: 
 1442: sub replicate_attachments {
 1443:     my ($attachrefs,$tempexport) = @_;
 1444:     my $response;
 1445:     foreach my $id (keys(%{$attachrefs})) {
 1446:         if ($$attachrefs{$id}{'filename'} =~ m-^/uploaded/([^/]+)/([^/]+)(/feedback)?(/?\d*)/([^/]+)$-) {
 1447:             my $path = $tempexport;
 1448:             my $tail = $1.'/'.$2.$4;
 1449:             my @extras = split(/\//,$tail);
 1450:             my $destination = $tempexport.'/'.$1.'/'.$2.$4.'/'.$5;
 1451:             if (!-e $destination) {
 1452:                 my $i= 0;
 1453:                 while ($i<@extras) {
 1454:                     $path .= '/'.$extras[$i];
 1455:                     if (!-e $path) {
 1456:                         mkdir($path,0700);
 1457:                     }
 1458:                     $i ++;
 1459:                 }
 1460:                 my ($content,$rtncode);
 1461:                 my $uploadreply = &Apache::lonnet::getuploaded('GET',$$attachrefs{$id}{'filename'},$1,$2,$content,$rtncode);
 1462:                 if ($uploadreply eq 'ok') {
 1463:                     my $attachcopy;
 1464:                     if ($attachcopy = Apache::File->new('>'.$destination)) {
 1465:                         print $attachcopy $content;
 1466:                         close($attachcopy);
 1467:                     } else {
 1468:                         $response .= &mt('Error copying file attachment - [_1] to IMS package',$5).': '.$!.'<br />'."\n";
 1469:                     }
 1470:                 } else {
 1471:                     &Apache::lonnet::logthis("Replication of attachment failed when building IMS export of discussion posts - domain: $1, course: $2, file: $$attachrefs{$id}{'filename'} -error: $rtncode");
 1472:                     $response .= &mt('Error copying file attachment - [_1] to IMS package: ',$5).$rtncode.'<br />'."\n";
 1473:                 }
 1474:             }
 1475:         }
 1476:     }
 1477:     return $response;
 1478: }
 1479: 
 1480: sub mail_screen {
 1481:   my ($r,$feedurl,$options,$caller_symb,$attachmaxtext) = @_;
 1482:   if (exists($env{'form.origpage'})) {
 1483:       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['subject','comment','currnewattach','addnewattach','deloldattach','delnewattach','timestamp','idx','anondiscuss','discuss','blog','group','ref']);
 1484:   }
 1485: 
 1486:   my %lt = &Apache::lonlocal::texthash(
 1487:             'plch' => 'Please check at least one of the following feedback types:',
 1488:             'myqu' => 'My question/comment/feedback:',
 1489:             'title' => 'Title',
 1490:             'reta' => 'Retained attachments',
 1491:             'atta' => 'Attachment',
 1492:            );
 1493:   my $restitle = &get_resource_title($caller_symb,$feedurl);
 1494:   my $quote='';
 1495:   my $subject = '';
 1496:   my $comment = '';
 1497:   my $prevtag = '';
 1498:   my $parentmsg = '';
 1499:   my ($symb,$idx,$attachmenturls);
 1500:   my $numoldver = 0;
 1501:   my $attachmsg = '';
 1502:   my $newattachmsg = '';
 1503:   my @currnewattach = ();
 1504:   my @currdelold = ();
 1505:   my @keepold = ();
 1506:   my %attachments = ();
 1507:   my %currattach = ();
 1508:   my $attachnum = 0;
 1509:   my $anonchk = (<<END);
 1510:   function anonchk() {
 1511:       for (var i=0; i < document.mailform.discuss.length; i++) {
 1512: 	  if (document.mailform.discuss[i].checked) {
 1513: 	      document.attachment.discuss.value = 
 1514: 		  document.mailform.discuss[i].value;
 1515: 	  }
 1516:       }
 1517:       if (document.mailform.blog.checked) {
 1518: 	  document.attachment.blog.value = 1;
 1519:       }
 1520:      return
 1521:    }
 1522: END
 1523:   my $anonscript;
 1524:   if (exists($env{'form.origpage'})) {
 1525:       $anonscript = (<<END);
 1526:   function setposttype() {
 1527:       var disc = "$env{'form.discuss'}";
 1528:       for (var i=0; i < document.mailform.discuss.length; i++) {
 1529: 	  if (disc == document.mailform.discuss[i].value) {
 1530: 	      document.mailform.discuss[i].checked = 1;
 1531: 	  }
 1532:       }
 1533:       var blog = "$env{'form.blog'}";
 1534:       if (blog == 1) {
 1535:           document.mailform.blog.checked=1;
 1536:       }
 1537:       return
 1538:   }
 1539: END
 1540:   } else {
 1541:       $anonscript = (<<END);
 1542:   function setposttype() {
 1543:       return
 1544:   }
 1545: END
 1546:   }
 1547:   if (($env{'form.replydisc'}) || ($env{'form.editdisc'})) {
 1548:       if ($env{'form.replydisc'}) {
 1549:           ($symb,$idx)=split(/\:\:\:/,$env{'form.replydisc'});
 1550:       } else {
 1551:           ($symb,$idx)=split(/\:\:\:/,$env{'form.editdisc'});
 1552:       }
 1553:       my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 1554: 					   $env{'course.'.$env{'request.course.id'}.'.domain'},
 1555: 					   $env{'course.'.$env{'request.course.id'}.'.num'});
 1556:       unless (($contrib{'hidden'}=~/\.$idx\./) || ($contrib{'deleted'}=~/\.$idx\./)) {
 1557:           if ($contrib{$idx.':history'}) {
 1558:               if ($contrib{$idx.':history'} =~ /:/) {
 1559:                   my @oldversions = split(/:/,$contrib{$idx.':history'});
 1560:                   $numoldver = @oldversions;
 1561:               } else {
 1562:                   $numoldver = 1;
 1563:               }
 1564:           }
 1565:           if ($env{'form.replydisc'}) {
 1566:               if ($contrib{$idx.':history'}) {
 1567:                   if ($contrib{$idx.':history'} =~ /:/) {
 1568:                       my @oldversions = split(/:/,$contrib{$idx.':history'});
 1569:                       $numoldver = @oldversions;
 1570:                   } else {
 1571:                       $numoldver = 1;
 1572:                   }
 1573:               }
 1574:               if ($idx > 0) {
 1575:                   my %msgversions = ();
 1576:                   &get_post_versions(\%msgversions,$contrib{$idx.':message'},0,$numoldver);
 1577:                   $quote = $msgversions{$numoldver};
 1578:               }
 1579:               if ($idx > 0) {
 1580:                   my %subversions = ();
 1581:                   &get_post_versions(\%subversions,$contrib{$idx.':subject'},1,$numoldver);
 1582:                   $subject = &mt('Re: ').$subversions{$numoldver};
 1583:               }
 1584:               $subject = &HTML::Entities::encode($subject,'<>&"');
 1585:           } else {
 1586:               $attachmenturls = $contrib{$idx.':attachmenturl'};
 1587:               if ($idx > 0) {
 1588:                   my %msgversions = ();
 1589:                   &get_post_versions(\%msgversions,$contrib{$idx.':message'},0,$numoldver);
 1590:                   $comment = $msgversions{$numoldver};
 1591:                   my %subversions = ();
 1592:                   &get_post_versions(\%subversions,$contrib{$idx.':subject'},0,$numoldver);
 1593:                   $subject = $subversions{$numoldver}; 
 1594:               }
 1595:               if (defined($contrib{$idx.':replyto'})) {
 1596:                   $parentmsg = $contrib{$idx.':replyto'};
 1597:               }
 1598:               unless (exists($env{'form.origpage'})) {
 1599:                   my $anonflag = 'nonanon';
 1600:                   if ($contrib{$idx.':anonymous'}) {
 1601:                       $anonflag = 'anon';
 1602:                   }
 1603:                   $anonscript = (<<END);
 1604:   function setposttype () {
 1605:       var currtype = "$anonflag";
 1606:       for (var i=0; i<document.mailform.discuss.length; i++) {
 1607: 	  if (document.mailform.elements.discuss[i].value == currtype ) {
 1608: 	      document.mailform.elements.discuss[i].checked=1;
 1609: 	  } 
 1610:       }
 1611:       return
 1612:   }
 1613: END
 1614:               }
 1615:           }
 1616:       }
 1617:       if ($env{'form.previous'}) {
 1618:           $prevtag = '<input type="hidden" name="previous" value="'.$env{'form.previous'}.'" />';
 1619:       }
 1620:   }
 1621: 
 1622:   if ($env{'form.origpage'}) {
 1623:       $subject = &unescape($env{'form.subject'});
 1624:       $comment = &unescape($env{'form.comment'});
 1625:       &process_attachments(\@currnewattach,\@currdelold,\@keepold);
 1626:   }
 1627:   my $latexHelp=&Apache::loncommon::helpLatexCheatsheet(undef,undef,1);
 1628:   my $send=&mt('Send');
 1629:   my $alert = &mt('Please select a feedback type.');
 1630:   my $js= <<END;
 1631: <script type="text/javascript">
 1632: //<!--
 1633:     function gosubmit() {
 1634:         var rec=0;
 1635:         if (typeof(document.mailform.elements.discuss)!="undefined") {
 1636: 	    if (typeof(document.mailform.elements.discuss.length) == "undefined") {
 1637: 		if (document.mailform.elements.discuss.checked ) {
 1638: 		    rec=1;
 1639: 		}
 1640: 	    } else {
 1641: 		for (var i=0; i<document.mailform.elements.discuss.length; i++) {
 1642: 		    if (document.mailform.elements.discuss[i].checked ) {
 1643: 			rec=1;
 1644: 		    } 
 1645: 		}
 1646: 	    }
 1647: 	}
 1648:         if (typeof(document.mailform.elements.blog)!="undefined") {
 1649:           if (document.mailform.elements.blog.checked) {
 1650:              rec=1;
 1651:           } 
 1652:         }
 1653: 
 1654:         if (rec) {
 1655:             if (typeof(document.mailform.onsubmit)=='function') {
 1656: 		document.mailform.onsubmit();
 1657: 	    }
 1658: 	    document.mailform.submit();
 1659:         } else {
 1660:             alert('$alert');
 1661: 	}
 1662:     }
 1663:     $anonchk
 1664:     $anonscript
 1665: //-->
 1666: </script>
 1667: END
 1668: 
 1669:   # Breadcrumbs
 1670:   my $brcrum = [{'href' => '',
 1671:                  'text' => 'Resource Feedback and Discussion'}];
 1672: 
 1673:   my %onload = ('onload' => 'window.focus();setposttype();');
 1674:   my $start_page=
 1675:       &Apache::loncommon::start_page('Resource Feedback and Discussion',$js,
 1676:                                      {'add_entries' => \%onload,
 1677:                                       'bread_crumbs' => $brcrum,});
 1678: 
 1679:   if ($quote ne '') {
 1680:       &newline_to_br(\$quote);
 1681:       $quote='<blockquote>'.&Apache::lontexconvert::msgtexconverted($quote).'</blockquote>';
 1682:   }
 1683: 
 1684:   $r->print(<<END);
 1685: $start_page
 1686: <h2><tt>$restitle</tt></h2>
 1687: <form action="/adm/feedback" method="post" name="mailform"
 1688: enctype="multipart/form-data">
 1689: $prevtag
 1690: <input type="hidden" name="postdata" value="$feedurl" />
 1691: END
 1692:   if ($env{'form.replydisc'}) {
 1693:       $r->print(<<END);
 1694: <input type="hidden" name="replydisc" value="$env{'form.replydisc'}" />
 1695: END
 1696:   } elsif ($env{'form.editdisc'}) {
 1697:      $r->print(<<END);
 1698: <input type="hidden" name="editdisc" value="$env{'form.editdisc'}" />
 1699: <input type="hidden" name="parentmsg" value="$parentmsg" />
 1700: END
 1701:   }
 1702:   $r->print(<<END);
 1703: $lt{'plch'}
 1704: $options<hr />
 1705: $quote
 1706: <p>$lt{'myqu'}</p>
 1707: <p>
 1708: $latexHelp
 1709: </p>
 1710: <p>
 1711: $lt{'title'}: <input type="text" name="subject" size="30" value="$subject" /></p>
 1712: <p>
 1713: <textarea name="comment" id="comment" cols="60" rows="10" wrap="hard">$comment
 1714: </textarea></p>
 1715: <p>
 1716: END
 1717:     if ( ($env{'form.editdisc'}) || ($env{'form.replydisc'}) ) {
 1718:         if ($env{'form.origpage'}) {
 1719:             foreach my $attach (@currnewattach) {
 1720:                 $r->print('<input type="hidden" name="currnewattach" value="'.$attach.'" />'."\n");
 1721:             }
 1722:             foreach my $oldatt (@currdelold) {
 1723:                 $r->print('<input type="hidden" name="deloldattach" value="'.$oldatt.'" />'."\n");
 1724:             }
 1725:         }
 1726:         if ($env{'form.editdisc'}) {
 1727:             if ($attachmenturls) {
 1728:                 &extract_attachments($attachmenturls,$idx,$numoldver,\$attachmsg,\%attachments,\%currattach,\@currdelold);
 1729:                 $attachnum = scalar(keys(%currattach));
 1730:                 foreach my $key (keys(%currattach)) {
 1731:                     $r->print('<input type="hidden" name="keepold" value="'.$key.'" />'."\n");
 1732:                 }
 1733:             }
 1734:         }
 1735:     } else {
 1736:         $r->print(<<END);
 1737: $lt{'atta'} $attachmaxtext: <input type="file" name="attachment" />
 1738: </p>
 1739: END
 1740:     }
 1741:     if (exists($env{'form.group'})) {
 1742:         $r->print('<input type="hidden" name="group" value="'.$env{'form.group'}.'" />');
 1743:     }
 1744:     if (exists($env{'form.ref'})) {
 1745:         $r->print('<input type="hidden" name="ref" value="'.$env{'form.ref'}.'" />');
 1746:     }
 1747:     $r->print(<<END);
 1748: <p>
 1749: <input type="hidden" name="sendit" value="1" />
 1750: <input type="button" value="$send" onClick='gosubmit();' />
 1751: </p>
 1752: </form>
 1753: END
 1754:     if ($env{'form.editdisc'} || $env{'form.replydisc'}) {
 1755:         my $now = time;
 1756:         my $ressymb = $symb;
 1757:         &Apache::lonenc::check_encrypt(\$ressymb);
 1758:         my $postidx = '';
 1759:         if ($env{'form.editdisc'}) {
 1760:             $postidx = $idx;
 1761:         }
 1762:         if (@currnewattach > 0) {
 1763:             $attachnum += @currnewattach;
 1764:         }
 1765:         my $blockblog = &Apache::loncommon::blocking_status('blogs');
 1766:         $r->print(&generate_attachments_button($postidx,$attachnum,$ressymb,$now,\@currnewattach,\@currdelold,$numoldver,'',$blockblog));
 1767:         if ($attachnum > 0) {
 1768:             if (@currnewattach > 0) {
 1769:                 $newattachmsg .= '<br /><b>'.&mt('New attachments').'</b><br />';
 1770:                 if (@currnewattach > 1) {
 1771:                     $newattachmsg .= '<ol>';
 1772:                     foreach my $item (@currnewattach) {
 1773:                         $item =~ m#.*/([^/]+)$#;
 1774:                         $newattachmsg .= '<li><a href="'.$item.'">'.$1.'</a></li>'."\n";
 1775:                     }
 1776:                     $newattachmsg .= '</ol>'."\n";
 1777:                 } else {
 1778:                     $currnewattach[0] =~ m#.*/([^/]+)$#;
 1779:                     $newattachmsg .= '<a href="'.$currnewattach[0].'">'.$1.'</a><br />'."\n";
 1780:                 }
 1781:             }
 1782:             if ($attachmsg) {
 1783:                 $r->print("<br /><b>$lt{'reta'}</b>:$attachmsg<br />\n");
 1784:             }
 1785:             if ($newattachmsg) {
 1786:                 $r->print("$newattachmsg<br />");
 1787:             }
 1788:         }
 1789:     }
 1790:     $r->print(&generate_preview_button().
 1791:               &Apache::lonhtmlcommon::htmlareaselectactive('comment').
 1792: 	      &Apache::loncommon::end_page());
 1793: 
 1794: }
 1795: 
 1796: sub print_display_options {
 1797:     my ($r,$symb,$previous,$dispchgA,$dispchgB,$markchg,$toggchg,$feedurl) = @_;
 1798:     &Apache::loncommon::content_type($r,'text/html');
 1799:     $r->send_http_header;
 1800: 
 1801:     my $function = &Apache::loncommon::get_users_function();
 1802:     my $tabcolor = &Apache::loncommon::designparm($function.'.tabbg',
 1803:                                                     $env{'user.domain'});
 1804: 
 1805:     my %lt = &Apache::lonlocal::texthash(
 1806:         'pref' => 'Display Preference',
 1807:         'curr' => 'Current setting ',
 1808:         'actn' => 'Action',
 1809:         'deff' => 'Default for all discussions',
 1810:         'prca' => 'Preferences can be set for this discussion that determine ....',
 1811:         'whpo' => 'Which posts are displayed when you display this discussion board or resource, and',
 1812:         'unwh' => 'Under what circumstances posts are identified as "NEW", and',
 1813:         'wipa' => 'Whether individual posts can be marked as read/unread',
 1814:         'allposts' => 'All posts',
 1815:         'unread' => 'New posts only',
 1816:         'unmark' => 'Posts not marked read',
 1817:         'ondisp' => 'Once displayed',
 1818:         'onmark' => 'Once marked not NEW',
 1819:         'toggon' => 'Shown',
 1820:         'toggoff' => 'Not shown',
 1821:         'disa' => 'Posts displayed?',
 1822:         'npmr' => 'New posts cease to be identified as "NEW"?',
 1823:         'dotm' => 'Option to mark each post as read/unread?',  
 1824:         'chgt' => 'Change to ',
 1825:         'mkdf' => 'Set to ',
 1826:         'yhni' => 'You have not indicated that you wish to change any of the discussion settings',
 1827:         'ywbr' => 'You will be returned to the previous page if you click OK.'
 1828:     );
 1829: 
 1830:     my $dispchangeA = $lt{'unread'};
 1831:     my $dispchangeB = $lt{'unmark'};
 1832:     my $markchange = $lt{'ondisp'};
 1833:     my $toggchange = $lt{'toggon'};
 1834:     my $currdisp = $lt{'allposts'};
 1835:     my $currmark = $lt{'onmark'};
 1836:     my $discdisp = 'allposts';
 1837:     my $discmark = 'onmark';
 1838:     my $currtogg = $lt{'toggoff'};
 1839:     my $disctogg = 'toggoff';
 1840:                                                                                       
 1841:     if ($dispchgA eq 'allposts') {
 1842:         $dispchangeA = $lt{'allposts'};
 1843:         $currdisp = $lt{'unread'};
 1844:         $discdisp = 'unread';
 1845:     }
 1846: 
 1847:     if ($markchg eq 'markonread') {
 1848:         $markchange = $lt{'onmark'};
 1849:         $currmark = $lt{'ondisp'};
 1850:         $discmark = 'ondisp';
 1851:     }
 1852: 
 1853:     if ($dispchgB eq 'onlyunread') {
 1854:         $dispchangeB = $lt{'unread'};
 1855:         $currdisp = $lt{'unmark'};
 1856:         $discdisp = 'unmark';
 1857:     }
 1858:     if ($toggchg eq 'toggoff') {
 1859:         $toggchange = $lt{'toggoff'};
 1860:         $currtogg = $lt{'toggon'};
 1861:         $disctogg = 'toggon';
 1862:     }
 1863: 
 1864:     my $js = <<END;
 1865: <script type="text/javascript">
 1866: function discdispChk(caller) {
 1867:     var disctogg = '$toggchg'
 1868:     if (caller == 0) {
 1869:         if (document.modifydisp.discdisp[0].checked == true) {
 1870:             if (document.modifydisp.discdisp[1].checked == true) {
 1871:                 document.modifydisp.discdisp[1].checked = false
 1872:             }
 1873:         }
 1874:     }
 1875:     if (caller == 1) {
 1876:         if (document.modifydisp.discdisp[1].checked == true) {
 1877:             if (document.modifydisp.discdisp[0].checked == true) {
 1878:                 document.modifydisp.discdisp[0].checked = false
 1879:             }
 1880:             if (disctogg == 'toggon') {
 1881:                 document.modifydisp.disctogg.checked = true
 1882:             }
 1883:             if (disctogg == 'toggoff') {
 1884:                 document.modifydisp.disctogg.checked = false
 1885:             }
 1886:         }
 1887:     }
 1888:     if (caller == 2) {
 1889:         var dispchgB = '$dispchgB'
 1890:         if (disctogg == 'toggoff') {
 1891:             if (document.modifydisp.disctogg.checked == true) {
 1892:                 if (dispchgB == 'onlyunmark') {
 1893:                     document.modifydisp.discdisp[1].checked = false
 1894:                 }
 1895:             }
 1896:         }
 1897:     }  
 1898: }
 1899: 
 1900: function setDisp() {
 1901:     var prev = "$previous"
 1902:     var chktotal = 0
 1903:     if (document.modifydisp.discdisp[0].checked == true) {
 1904:         document.modifydisp.$dispchgA.value = "$symb"
 1905:         chktotal ++
 1906:     }
 1907:     if (document.modifydisp.discdisp[1].checked == true) {
 1908:         document.modifydisp.$dispchgB.value = "$symb"
 1909:         chktotal ++
 1910:     }
 1911:     if (document.modifydisp.discmark.checked == true) {
 1912:         document.modifydisp.$markchg.value = "$symb"
 1913:         chktotal ++
 1914:     }
 1915:     if (document.modifydisp.disctogg.checked == true) {
 1916:         document.modifydisp.$toggchg.value = "$symb"
 1917:         chktotal ++
 1918:     }
 1919:     if (chktotal > 0) { 
 1920:         document.modifydisp.submit()
 1921:     } else {
 1922:         if(confirm("$lt{'yhni'}. \\n$lt{'ywbr'}"))      {
 1923:             if (prev > 0) {
 1924:                 location.href = "$feedurl?previous=$previous"
 1925:             } else {
 1926:                 location.href = "$feedurl"
 1927:             }
 1928:         }
 1929:     }
 1930: }
 1931: </script>
 1932: END
 1933: 
 1934: 
 1935:     my $start_page =
 1936: 	&Apache::loncommon::start_page('Discussion display options',$js);
 1937:     my $end_page =
 1938: 	&Apache::loncommon::end_page();
 1939:     $r->print(<<END);
 1940: $start_page
 1941: <form name="modifydisp" method="post" action="/adm/feedback">
 1942: $lt{'sdpf'}<br/> $lt{'prca'}  <ol><li>$lt{'whpo'}</li><li>$lt{'unwh'}</li><li>$lt{'wipa'}</li></ol>
 1943: <br />
 1944: END
 1945:     $r->print(&Apache::loncommon::start_data_table());
 1946:     $r->print(<<END);
 1947:        <tr>
 1948:         <th>$lt{'pref'}</td>
 1949:         <th>$lt{'curr'}</td>
 1950:         <th>$lt{'actn'}?</td>
 1951:        </tr>
 1952: END
 1953:     $r->print(&Apache::loncommon::start_data_table_row());
 1954:     $r->print(<<END);
 1955:        <td>$lt{'disa'}</td>
 1956:        <td>$lt{$discdisp}</td>
 1957:        <td><label><input type="checkbox" name="discdisp" onClick="discdispChk('0')" />&nbsp;$lt{'chgt'} "$dispchangeA"</label>
 1958:            <br />
 1959:            <label><input type="checkbox" name="discdisp" onClick="discdispChk('1')" />&nbsp;$lt{'chgt'} "$dispchangeB"</label>
 1960:        </td>
 1961: END
 1962:     $r->print(&Apache::loncommon::end_data_table_row());
 1963:     $r->print(&Apache::loncommon::start_data_table_row());
 1964:     $r->print(<<END);
 1965:        <td>$lt{'npmr'}</td>
 1966:        <td>$lt{$discmark}</td>
 1967:        <td><label><input type="checkbox" name="discmark" />$lt{'chgt'} "$markchange"</label></td>
 1968: END
 1969:     $r->print(&Apache::loncommon::end_data_table_row());
 1970:     $r->print(&Apache::loncommon::start_data_table_row());
 1971:     $r->print(<<END);
 1972:        <td>$lt{'dotm'}</td>
 1973:        <td>$lt{$disctogg}</td>
 1974:        <td><label><input type="checkbox" name="disctogg" onClick="discdispChk('2')" />$lt{'chgt'} "$toggchange"</label></td>
 1975: END
 1976:     my $save = &mt('Save');
 1977:     $r->print(&Apache::loncommon::end_data_table_row());
 1978:     $r->print(&Apache::loncommon::end_data_table());
 1979:     $r->print(<<END);
 1980: <br />
 1981: <br />
 1982: <input type="hidden" name="symb" value="$symb" />
 1983: <input type="hidden" name="previous" value="$previous" />
 1984: <input type="hidden" name="$dispchgA" value="" />
 1985: <input type="hidden" name="$dispchgB" value="" />
 1986: <input type="hidden" name="$markchg" value="" />
 1987: <input type="hidden" name="$toggchg" value="" />
 1988: <input type="button" name="sub" value="$save" onClick="javascript:setDisp()" />
 1989: END
 1990:     if (exists($env{'form.group'})) {
 1991:         $r->print('<input type="hidden" name="group" value="'.$env{'form.group'}.'" />');
 1992:     }
 1993:     if (exists($env{'form.ref'})) {
 1994:         $r->print('<input type="hidden" name="ref" value="'.$env{'form.ref'}.'" />');
 1995:     }
 1996:     $r->print("
 1997: <br />
 1998: <br />
 1999: </form>
 2000: $end_page
 2001:     ");
 2002:     return;
 2003: }
 2004: 
 2005: sub print_sortfilter_options {
 2006:     my ($r,$symb,$previous,$feedurl) = @_;
 2007: 
 2008:     &Apache::loncommon::content_type($r,'text/html');
 2009:     $r->send_http_header;
 2010: 
 2011:     &Apache::lonenc::check_encrypt(\$symb);
 2012:     my @sections;
 2013:     my $section_sel = '';
 2014:     my $numvisible = 5;
 2015:     my @groups;
 2016:     my $group_sel = '';
 2017:     my $numgroupvis = 5;
 2018:     my %sectioncount = &Apache::loncommon::get_sections();
 2019:     my @courseroles = qw(st ad ep ta in);
 2020:     my $crstype = &Apache::loncommon::course_type();
 2021:     my $ccrole = 'cc';
 2022:     if ($crstype eq 'Community') {
 2023:         $ccrole = 'co';
 2024:     }
 2025:     push(@courseroles,$ccrole);
 2026:     
 2027:     if ($env{'request.course.sec'} !~ /^\s*$/) {  #Restrict section choice to current section 
 2028:         @sections = ('all',$env{'request.course.sec'});
 2029:         $numvisible = 2;
 2030:     } else {
 2031:         @sections = sort {$a cmp $b} keys(%sectioncount);
 2032:         if (scalar(@sections) < 4) {
 2033:             $numvisible = scalar(@sections) + 1;
 2034:         }
 2035:         unshift(@sections,'all'); # Put 'all' at the front of the list
 2036: 
 2037:     }
 2038:     foreach my $sec (@sections) {
 2039:         $section_sel .= "  <option value=\"$sec\">$sec</option>\n";
 2040:     }
 2041: 
 2042:     if (&check_group_priv() eq 'ok') {
 2043:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2044:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'}; 
 2045:         my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 2046:         @groups = sort {$a cmp $b} keys(%curr_groups);
 2047:         if (scalar(@groups) < 4) {
 2048:             $numgroupvis = scalar(@groups) + 1;
 2049:         }
 2050:         unshift(@groups,'all'); # Put 'all' at the front of the list
 2051:     } else { 
 2052:         my @coursegroups = split(/:/,$env{'request.course.groups'});
 2053:         if (@coursegroups > 0) {
 2054:             @coursegroups = sort {$a cmp $b} @coursegroups;
 2055:             @groups = ('all',@coursegroups);
 2056:             if (scalar(@groups) < 4) {
 2057:                 $numgroupvis = scalar(@groups) + 1;
 2058:             }
 2059:         } else {
 2060:             @groups = ('all');
 2061:             $numgroupvis = 1;
 2062:         }
 2063:     }
 2064:     foreach my $group (@groups) {
 2065:         $group_sel .= "  <option value=\"$group\">$group</option>\n";
 2066:     }
 2067: 
 2068:     my $function = &Apache::loncommon::get_users_function();
 2069:     my $tabcolor = &Apache::loncommon::designparm($function.'.tabbg',
 2070:                                                     $env{'user.domain'});
 2071:     my %lt = &Apache::lonlocal::texthash(
 2072:         'diop' => 'Display Options',
 2073:         'curr' => 'Current setting ',
 2074:         'actn' => 'Action',
 2075:         'prca' => 'Set options that control the sort order of posts, and/or which posts are displayed.',
 2076:         'soor' => 'Sort order',
 2077:         'spur' => 'Specific user roles',
 2078:         'sprs' => 'Specific role status',
 2079:         'spse' => 'Specific sections',
 2080:         'spgr' => 'Specific groups',
 2081:         'psub' => 'Pick specific users (by name)',
 2082:         'shal' => 'Show a list of current posters',
 2083:         'stor' => 'Save changes',
 2084:     );
 2085: 
 2086:     my %sort_types = ();
 2087:     my %role_types = ();
 2088:     my %status_types = ();
 2089:     &sort_filter_names(\%sort_types,\%role_types,\%status_types,$crstype);
 2090: 
 2091:     my $js = <<END;
 2092: <script type="text/javascript">
 2093: function verifyFilter() {
 2094:     var rolenum = 0
 2095:     for (var i=0; i<document.modifyshown.rolefilter.length; i++) {
 2096:         if (document.modifyshown.rolefilter.options[i].selected == true) {
 2097:             rolenum ++
 2098:         }
 2099:     }
 2100:     if (rolenum == 0) {
 2101:         document.modifyshown.rolefilter.options[0].selected = true
 2102:     }
 2103: 
 2104:     var secnum = 0
 2105:     for (var i=0; i<document.modifyshown.sectionpick.length; i++) {
 2106:         if (document.modifyshown.sectionpick.options[i].selected == true) {
 2107:             secnum ++
 2108:         }
 2109:     }
 2110:     if (secnum == 0) {
 2111:         document.modifyshown.sectionpick.options[0].selected = true
 2112:     }
 2113: 
 2114:     var grpnum = 0
 2115:     for (var i=0; i<document.modifyshown.grouppick.length; i++) {
 2116:         if (document.modifyshown.grouppick.options[i].selected == true) {
 2117:             grpnum ++
 2118:         }
 2119:     }
 2120:     if (grpnum == 0) {
 2121:         document.modifyshown.grouppick.options[0].selected = true
 2122:     }
 2123: 
 2124:     document.modifyshown.submit();
 2125: }
 2126: </script>
 2127: END
 2128: 
 2129:     my $start_page=
 2130: 	&Apache::loncommon::start_page('Discussion options',$js);
 2131:     my $end_page=
 2132: 	&Apache::loncommon::end_page();
 2133: 
 2134:     $r->print(<<END);
 2135: $start_page
 2136: <form name="modifyshown" method="post" action="/adm/feedback">
 2137: <b>$lt{'diso'}</b><br/> $lt{'prca'}
 2138: <br /><br />
 2139: <table border="0">
 2140:  <tr>
 2141:   <td><b>$lt{'soor'}</b></td>
 2142:   <td>&nbsp;</td>
 2143:   <td><b>$lt{'sprs'}</b></td>
 2144:   <td>&nbsp;</td>
 2145:   <td><b>$lt{'spur'}</b></td>
 2146:   <td>&nbsp;</td>
 2147:   <td><b>$lt{'spse'}</b></td>
 2148:   <td>&nbsp;</td>
 2149:   <td><b>$lt{'spgr'}</b></td>
 2150:   <td>&nbsp;</td>
 2151:   <td><b>$lt{'psub'}</b></td>
 2152:  </tr>
 2153:  <tr>
 2154:   <td align="center" valign="top">
 2155:    <select name="sortposts">
 2156:     <option value="ascdate" selected="selected">$sort_types{'ascdate'}</option>
 2157:     <option value="descdate">$sort_types{'descdate'}</option>
 2158:     <option value="thread">$sort_types{'thread'}</option>
 2159:     <option value="subject">$sort_types{'subject'}</option>
 2160:     <option value="username">$sort_types{'username'}</option>
 2161:     <option value="lastfirst">$sort_types{'lastfirst'}</option>
 2162:    </select>
 2163:   </td>
 2164:   <td>&nbsp;</td>
 2165:   <td align="center" valign="top">
 2166:    <select name="statusfilter">
 2167:     <option value="all" selected="selected">$status_types{'all'}</option>
 2168:     <option value="Active">$status_types{'Active'}</option>
 2169:     <option value="Expired">$status_types{'Expired'}</option>
 2170:     <option value="Future">$status_types{'Future'}</option>
 2171:    </select>
 2172:   </td>
 2173:   <td>&nbsp;</td>
 2174:   <td align="center" valign="top">
 2175:    <select name="rolefilter" multiple="multiple" size="5">
 2176:     <option value="all">$role_types{'all'}</option>
 2177:     <option value="st">$role_types{'st'}</option>
 2178:     <option value="$ccrole">$role_types{$ccrole}</option>
 2179:     <option value="in">$role_types{'in'}</option>
 2180:     <option value="ta">$role_types{'ta'}</option>
 2181:     <option value="ep">$role_types{'ep'}</option>
 2182:     <option value="ad">$role_types{'ad'}</option>
 2183:     <option value="cr">$role_types{'cr'}</option>
 2184:    </select>
 2185:   </td>
 2186:   <td>&nbsp;</td>
 2187:   <td align="center" valign="top">
 2188:    <select name="sectionpick" multiple="multiple" size="$numvisible">
 2189:     $section_sel
 2190:    </select>
 2191:   </td>
 2192:   <td>&nbsp;</td>
 2193:   <td align="center" valign="top">
 2194:    <select name="grouppick" multiple="multiple" size="$numvisible">
 2195:     $group_sel
 2196:    </select>
 2197:   </td>
 2198:   <td>&nbsp;</td>
 2199:   <td valign="top"><label><input type="checkbox" name="posterlist" value="$symb" />$lt{'shal'}</label></td>
 2200:  </tr>
 2201: </table>
 2202: <br />
 2203: <br />
 2204: <input type="hidden" name="previous" value="$previous" />
 2205: <input type="hidden" name="applysort" value="$symb" />
 2206: <input type="button" name="sub" value="$lt{'stor'}" onClick="verifyFilter()" />
 2207: END
 2208:     if (exists($env{'form.group'})) {
 2209:         $r->print('<input type="hidden" name="group" value="'.$env{'form.group'}.'" />');
 2210:     }
 2211:     if (exists($env{'form.ref'})) {
 2212:         $r->print('<input type="hidden" name="ref" value="'.$env{'form.ref'}.'" />');
 2213:     }
 2214:     $r->print("
 2215: <br />
 2216: <br />
 2217: </form>
 2218: $end_page
 2219: ");
 2220: }
 2221: 
 2222: sub print_showposters {
 2223:     my ($r,$symb,$previous,$feedurl,$sortposts) = @_;
 2224: 
 2225:     &Apache::loncommon::content_type($r,'text/html');
 2226:     $r->send_http_header;
 2227: 
 2228:     &Apache::lonenc::check_encrypt(\$symb);
 2229:     my $crs='/'.$env{'request.course.id'};
 2230:     if ($env{'request.course.sec'}) {
 2231:         $crs.='_'.$env{'request.course.sec'};
 2232:     }
 2233:     $crs=~s/\_/\//g;
 2234:     my $seeid;
 2235:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2236:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2237:     my $group = $env{'form.group'};
 2238:     my $ressymb = &wrap_symb($symb);
 2239:     if (($group ne '') &&
 2240:         ($ressymb =~ m|^bulletin___ \d+___adm/wrapper/adm/\Q$cdom\E/\Q$cnum\E/\d+/bulletinboard$|)) {
 2241:         if (&check_group_priv($group,'dgp') eq 'ok') {
 2242:             $seeid = 1;
 2243:         }
 2244:     } else {
 2245:         $seeid=&Apache::lonnet::allowed('rin',$crs);
 2246:     }
 2247:     my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 2248:                                          $cdom,$cnum);
 2249:     my %namesort = ();
 2250:     my %postcounts = ();
 2251: 
 2252:     my %lt = &Apache::lonlocal::texthash(
 2253:                                           sele => 'Select',
 2254:                                           full => 'Fullname',
 2255:                                           usdo => 'Username:domain',
 2256:                                           post => 'Posts',
 2257:                                         );
 2258:     if ($contrib{'version'}) {
 2259:         for (my $idx=1;$idx<=$contrib{'version'};$idx++) {
 2260:             my $hidden=($contrib{'hidden'}=~/\.$idx\./);
 2261:             my $deleted=($contrib{'deleted'}=~/\.$idx\./);
 2262:             unless ((($hidden) && (!$seeid)) || ($deleted)) {
 2263:                 if ((!$contrib{$idx.':anonymous'}) || (&Apache::lonnet::allowed('rin',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 2264:                     my %names = &Apache::lonnet::get('environment',['firstname','lastname'],$contrib{$idx.':senderdomain'},$contrib{$idx.':sendername'});
 2265:                     my $lastname = $names{'lastname'};
 2266:                     my $firstname = $names{'firstname'};
 2267:                     if ($lastname eq '') {
 2268:                         $lastname = '_';
 2269:                     }
 2270:                     if ($firstname eq '') {
 2271:                         $firstname = '_';
 2272:                     }
 2273:                     unless (defined($namesort{$lastname})) {
 2274:                         %{$namesort{$lastname}} = ();
 2275:                     }
 2276:                     my $poster =  $contrib{$idx.':sendername'}.':'.$contrib{$idx.':senderdomain'};
 2277:                     $postcounts{$poster} ++;
 2278:                     if (defined($namesort{$lastname}{$firstname})) {
 2279:                         if (!grep/^$poster$/,@{$namesort{$lastname}{$firstname}}) {
 2280:                             push(@{$namesort{$lastname}{$firstname}}, $poster);
 2281:                         }
 2282:                     } else {
 2283:                         @{$namesort{$lastname}{$firstname}} = ("$poster");
 2284:                     }
 2285:                 }
 2286:             }
 2287:         }
 2288:     }
 2289: 
 2290:     my $start_page = &Apache::loncommon::start_page('Discussion options');
 2291:     my $table_start =&Apache::loncommon::start_data_table();
 2292:     $r->print(<<END);
 2293: $start_page
 2294:  <form name="pickpostersform" method="post">
 2295:  <br />
 2296:     $table_start
 2297:       <tr>
 2298:        <th>#</th>
 2299:        <th>$lt{'sele'}</th>
 2300:        <th>$lt{'full'} <font color="#999999">($lt{'usdo'})</font></th>
 2301:        <th>$lt{'post'}</th>
 2302:       </tr>
 2303: END
 2304:     my $count = 0;
 2305:     foreach my $last (sort(keys(%namesort))) {
 2306:         foreach my $first (sort(keys(%{$namesort{$last}}))) {
 2307:             foreach my $user (sort(@{$namesort{$last}{$first}})) {
 2308:                 my ($uname,$udom) = split(/:/,$user);
 2309:                 if (!$uname || !$udom) { 
 2310:                     next;
 2311:                 } else {
 2312:                     $count ++;
 2313:                     $r->print(&Apache::loncommon::start_data_table_row().
 2314: 			      '<td align="right">'.$count.'</td>
 2315:                                <td align="center"><label><input name="stuinfo" type="checkbox" value="'.$user.'" /></td>
 2316:                                <td>'.$last.', '.$first.' ('.$uname.':'.$udom.')</label></td>
 2317:                                <td>'.$postcounts{$user}.'</td>'.
 2318: 			      &Apache::loncommon::end_data_table_row());
 2319:                 }
 2320:             }
 2321:         }
 2322:     }
 2323:     $r->print(&Apache::loncommon::end_data_table());
 2324:     my $end_page   = &Apache::loncommon::end_page();
 2325:     $r->print(<<END);
 2326: <br />
 2327: <input type="hidden" name="sortposts" value="$sortposts" />
 2328: <input type="hidden" name="userpick" value="$symb" />
 2329: <input type="button" name="store" value="Display posts" onClick="javascript:document.pickpostersform.submit()" />
 2330: </form>
 2331: $end_page
 2332: END
 2333: }
 2334: 
 2335: sub get_post_versions {
 2336:     my ($versions,$incoming,$htmldecode,$numver) = @_;
 2337:     if ($incoming =~ /^<version num="0">/) {
 2338:         my $p = HTML::LCParser->new(\$incoming);
 2339:         my $done = 0; 
 2340: 
 2341:         while ( (my $token = $p->get_tag("version")) && (!$done)) {
 2342:             my $num = $token->[1]{num};
 2343:             my $text = $p->get_text("/version");
 2344:             if (defined($numver)) {
 2345:                 if ($num == $numver) {
 2346:                     if ($htmldecode) {
 2347:                         $text = &HTML::Entities::decode($text);
 2348:                     }
 2349:                     $$versions{$numver}=$text;
 2350:                     $done = 1;
 2351:                 }
 2352:             } else {
 2353:                 if ($htmldecode) {
 2354:                     $text = &HTML::Entities::decode($text);
 2355:                 }
 2356:                 $$versions{$num}=$text;
 2357:             }
 2358:         }
 2359:     } else {
 2360:         if (!defined($numver)) {
 2361:             $numver = 0;
 2362:         }
 2363:         if ($htmldecode) {
 2364:             $$versions{$numver} = $incoming;
 2365:         } else {
 2366:             $$versions{$numver} = &HTML::Entities::encode($incoming,'<>&"');
 2367:         }
 2368:     }
 2369:     return;
 2370: }
 2371: 
 2372: sub get_post_attachments {
 2373:     my ($attachments,$attachmenturls) = @_;
 2374:     my $num;
 2375:     if ($attachmenturls =~ m/^<attachment id="0">/) {
 2376:         my $p = HTML::LCParser->new(\$attachmenturls);
 2377:         while (my $token = $p->get_tag("attachment","filename","post"))  {
 2378:             if ($token->[0] eq "attachment") {
 2379:                 $num = $token->[1]{id};
 2380:                 %{$$attachments{$num}} =();
 2381:             } elsif ($token->[0] eq "filename") {
 2382:                 $$attachments{$num}{'filename'} = $p->get_text("/filename");
 2383:             } elsif ($token->[0] eq "post") {
 2384:                 my $id = $token->[1]{id};
 2385:                 $$attachments{$num}{$id} = $p->get_text("/post");
 2386:             }
 2387:         }
 2388:     } else {
 2389:         %{$$attachments{'0'}} = ();
 2390:         $$attachments{'0'}{'filename'} = $attachmenturls;
 2391:         $$attachments{'0'}{'0'} = 'n';
 2392:     }
 2393: 
 2394:     return;
 2395: }
 2396: 
 2397: sub fail_redirect {
 2398:   my ($r,$feedurl) = @_;
 2399:   if ($feedurl=~/^\/adm\//) { $feedurl.='?register=1' };
 2400:   my %lt = &Apache::lonlocal::texthash(
 2401:                  'sorr' => 'Sorry, no recipients  ...',
 2402:   );
 2403:   my $logo=&Apache::loncommon::lonhttpdurl('/adm/lonIcons/lonlogos.gif');
 2404:   $r->print(&Apache::loncommon::start_page('Feedback not sent',undef,
 2405: 					   {'redirect'  => [2,$feedurl],
 2406: 					    'only_body' => 1,}));
 2407:   $r->print(<<ENDFAILREDIR);
 2408: <img align="right" src="$logo" />
 2409: <b>$lt{'sorr'}</b>
 2410: ENDFAILREDIR
 2411:   $r->print(&Apache::loncommon::end_page());
 2412: }
 2413: 
 2414: sub redirect_back {
 2415:   my ($r,$feedurl,$typestyle,$sendsomething,$sendposts,$blog,$status,$previous,$sort,$rolefilter,$statusfilter,$sectionpick,$grouppick,$numpicks,$group,$toolarge) = @_;
 2416:   my $sorttag = '';
 2417:   my $roletag = '';
 2418:   my $statustag = '';
 2419:   my $sectag = '';
 2420:   my $grptag = '';
 2421:   my $userpicktag = '';
 2422:   my $qrystr = '';
 2423:   my $prevtag = '';
 2424: 
 2425:   &Apache::loncommon::content_type($r,'text/html');
 2426:   $r->send_http_header;
 2427:   &dewrapper(\$feedurl);
 2428:   if ($feedurl=~/^\/adm\//) { $feedurl.='?register=1' };
 2429:   if ($previous > 0) {
 2430:       $qrystr = 'previous='.$previous;
 2431:       if ($feedurl =~ /\?register=1/) {
 2432:           $feedurl .= '&'.$qrystr;
 2433:       } else {
 2434:           $feedurl .= '?'.$qrystr;
 2435:       }
 2436:       $prevtag = '<input type="hidden" name="previous" value="'.$previous.'" />';
 2437:   }
 2438:   if (defined($sort)) {
 2439:       my $sortqry = 'sortposts='.$sort;
 2440:       if (($feedurl =~ /\?register=1/) || ($feedurl =~ /\?previous=/)) {
 2441:           $feedurl .= '&'.$sortqry;
 2442:       } else {
 2443:           $feedurl .= '?'.$sortqry;
 2444:       }
 2445:       $sorttag = '<input type="hidden" name="sortposts" value="'.$sort.'" />';
 2446:       if (defined($numpicks)) {
 2447:           my $userpickqry = 'totposters='.$numpicks;
 2448:           $feedurl .= '&'.$userpickqry;
 2449:           $userpicktag = '<input type="hidden" name="totposters" value="'.$numpicks.'" />';
 2450:       } else {
 2451:           if (ref($sectionpick) eq 'ARRAY') {
 2452:               $feedurl .= '&sectionpick=';
 2453:               $sectag .=  '<input type="hidden" name="sectionpick" value="';
 2454:               foreach my $sec (@{$sectionpick}) {
 2455:                   $feedurl .= $sec.',';
 2456:                   $sectag .= $sec.',';
 2457:               }
 2458:               $feedurl =~ s/,$//;
 2459:               $sectag =~ s/,$//;
 2460:               $sectag .= '" />';
 2461:           } else {
 2462:               $feedurl .= '&sectionpick='.$sectionpick;
 2463:               $sectag = '<input type="hidden" name="sectionpick" value="'.$sectionpick.'" />';
 2464:           }
 2465:           if (ref($grouppick) eq 'ARRAY') {
 2466:               $feedurl .= '&grouppick=';
 2467:               $sectag .=  '<input type="hidden" name="grouppick" value="';
 2468:               foreach my $grp (@{$grouppick}) {
 2469:                   $feedurl .= $grp.',';
 2470:                   $grptag .= $grp.',';
 2471:               }
 2472:               $feedurl =~ s/,$//;
 2473:               $grptag =~ s/,$//;
 2474:               $grptag .= '" />';
 2475:           } else {
 2476:               $feedurl .= '&grouppick='.$grouppick;
 2477:               $grptag = '<input type="hidden" name="grouppick" value="'.$grouppick.'" />';
 2478:           }
 2479:           if (ref($rolefilter) eq 'ARRAY') {
 2480:               $feedurl .= '&rolefilter=';
 2481:               $roletag .=  '<input type="hidden" name="rolefilter" value="';
 2482:               foreach my $role (@{$rolefilter}) {
 2483:                   $feedurl .= $role.',';
 2484:                   $roletag .= $role.',';
 2485:               }
 2486:               $feedurl =~ s/,$//;
 2487:               $roletag =~ s/,$//;
 2488:               $roletag .= '" />';
 2489:           } else {
 2490:               $feedurl .= '&rolefilter='.$rolefilter;
 2491:               $roletag = '<input type="hidden" name="rolefilter" value="'.$rolefilter.'" />';
 2492:           }
 2493:           $feedurl .= '&statusfilter='.$statusfilter;
 2494:           $statustag ='<input type="hidden" name="statusfilter" value="'.$statusfilter.'" />';
 2495:       }
 2496:   }
 2497:   my $grouptag;
 2498:   if ($group ne '') {
 2499:       $grouptag = '<input type="hidden" name="group" value="'.$group.'" />';
 2500:       my $refarg;
 2501:       if (exists($env{'form.ref'})) {
 2502:           $refarg = '&amp;ref='.$env{'form.ref'};
 2503:           $grouptag .= '<input type="hidden" name="ref" value="'.$env{'form.ref'}.'" />';
 2504:       }
 2505:       if ($feedurl =~ /\?/) {
 2506:           $feedurl .= '&amp;group='.$group.$refarg;
 2507:       } else {
 2508:           $feedurl .= '?group='.$group.$refarg;
 2509:       }
 2510:   } 
 2511:   &Apache::lonenc::check_encrypt(\$feedurl);
 2512:   my $logo=&Apache::loncommon::lonhttpdurl('/adm/lonIcons/lonlogos.gif');
 2513:   my %onload;
 2514:   if ($env{'environment.remote'} ne 'off') {
 2515:       $onload{'onload'} =
 2516: 	  "if (window.name!='loncapaclient') { this.document.reldt.submit(); self.window.close(); }";
 2517:   }
 2518:   my $start_page=
 2519:       &Apache::loncommon::start_page('Feedback sent',undef,
 2520: 				     {'redirect'    => [0,$feedurl],
 2521: 				      'only_body'   => 1,
 2522: 				      'add_entries' => \%onload});
 2523:   my $end_page = &Apache::loncommon::end_page();
 2524:   $r->print(<<ENDREDIR);
 2525: $start_page
 2526: <img align="right" src="$logo" />
 2527: $typestyle
 2528: <b>Sent $sendsomething message(s), and $sendposts post(s).</b>
 2529: $blog
 2530: $toolarge
 2531: <font color="red">$status</font>
 2532: <form name="reldt" action="$feedurl" target="loncapaclient">
 2533: $prevtag
 2534: $sorttag
 2535: $statustag
 2536: $roletag
 2537: $sectag
 2538: $grptag
 2539: $userpicktag
 2540: $grouptag
 2541: </form>
 2542: $end_page
 2543: ENDREDIR
 2544: }
 2545: 
 2546: sub no_redirect_back {
 2547:   my ($r,$feedurl) = @_;
 2548:   my $nofeed=&mt('Sorry, no feedback possible on this resource  ...');
 2549:  
 2550:   my %onload;
 2551:   if ($env{'environment.remote'} ne 'off') {
 2552:       $onload{'onload'} = 
 2553: 	  "if (window.name!='loncapaclient') { self.window.close(); }";
 2554:   }
 2555: 
 2556:   my %body_options = ('only_body'   => 1,
 2557: 		      'bgcolor'     => '#FFFFFF',
 2558: 		      'add_entries' => \%onload,);
 2559: 
 2560:   if ($feedurl !~ m{^/adm/feedback}) { 
 2561:       $body_options{'rediect'} = [2,$feedurl];
 2562:   }
 2563:   my $start_page=
 2564:       &Apache::loncommon::start_page('Feedback not sent',undef,
 2565: 				     \%body_options);
 2566: 				      
 2567:   my $end_page = &Apache::loncommon::end_page();
 2568: 
 2569:   &Apache::lonenc::check_encrypt(\$feedurl);
 2570:   my $logo=&Apache::loncommon::lonhttpdurl('/adm/lonIcons/lonlogos.gif');
 2571:   $r->print (<<ENDNOREDIRTWO);
 2572: $start_page
 2573: <img align="right" src="$logo" />
 2574: <b>$nofeed</b>
 2575: <br />
 2576: $end_page
 2577: ENDNOREDIRTWO
 2578: }
 2579: 
 2580: sub screen_header {
 2581:     my ($feedurl,$symb) = @_;
 2582:     my $crscontent = &mt('Question/Comment/Feedback about course content');
 2583:     my $crspolicy = &mt('Question/Comment/Feedback about course policy');
 2584:     my $contribdisc = &mt('Contribution to course discussion of resource');
 2585:     my $anoncontrib = &mt('Anonymous contribution to course discussion of resource');
 2586:     my $namevis = &mt('name only visible to course faculty');
 2587:     my $crstype;
 2588:     if ($env{'request.course.id'}) {
 2589:         $crstype = &Apache::loncommon::course_type();
 2590:         if ($crstype eq 'Community') {
 2591:             $crscontent = &mt('Question/Comment/Feedback about community content');
 2592:             $crspolicy = &mt('Question/Comment/Feedback about community policy');
 2593:             $contribdisc = &mt('Contribution to community discussion of resource');
 2594:             $anoncontrib = &mt('Anonymous contribution to community discussion of resource');
 2595:             $namevis = &mt('name only visible to community facilitators');
 2596:         }
 2597:     }
 2598:     my $msgoptions='';
 2599:     my $discussoptions='';
 2600:     unless (($env{'form.replydisc'}) || ($env{'form.editdisc'})) {
 2601: 	if (($feedurl=~/^\/res\//) && ($feedurl!~/^\/res\/adm/) && ($env{'user.adv'})) {
 2602: 	    $msgoptions= 
 2603: 		'<p><label><input type="radio" name="discuss" value="author" /> '.
 2604: 		&mt('Feedback to resource author').'</label></p>';
 2605: 	}
 2606:         my %optionhash=();
 2607:         foreach my $type ('question','comment','policy') {
 2608: 	    $optionhash{$type}=$env{'course.'.$env{'request.course.id'}.'.'.$type.'.email.text'};
 2609: 	}
 2610: 	if (&feedback_available(1)) {
 2611: 	    $msgoptions.=
 2612: 		'<p><label><input type="radio" name="discuss" value="question" /> '.
 2613: 		($optionhash{'question'}?$optionhash{'question'}:&mt('Question about resource content')).'</label></p>';
 2614: 	}
 2615: 	if (&feedback_available(0,1)) {
 2616: 	    $msgoptions.=
 2617: 		'<p><label><input type="radio" name="discuss" value="course" /> '.
 2618: 		($optionhash{'comment'}?$optionhash{'comment'}:$crscontent).
 2619: 		'</label></p>';
 2620: 	}
 2621: 	if (&feedback_available(0,0,1)) {
 2622: 	    $msgoptions.=
 2623: 		'<p><label><input type="radio" name="discuss" value="policy" /> '.
 2624: 		($optionhash{'policy'}?$optionhash{'policy'}:$crspolicy).
 2625: 		'</label></p>';
 2626: 	}
 2627:     }
 2628:     if (($env{'request.course.id'}) && (!$env{'form.sendmessageonly'})) {
 2629:         my ($blocked,$blocktext) = &Apache::loncommon::blocking_status('boards');
 2630:         if (!$blocked && &discussion_open(undef,$symb) && 
 2631: 	    &Apache::lonnet::allowed('pch',
 2632: 				     $env{'request.course.id'}.
 2633: 				     ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) {
 2634: 	    $discussoptions='<label><input type="radio" name="discuss" value="nonanon" checked="checked" /> '.
 2635: 		$contribdisc.
 2636: 	        '</label><br /><label><input type="radio" name="discuss" value="anon" /> '.
 2637: 		$anoncontrib.
 2638: 		' <i>('.$namevis.')</i></label> '.
 2639: 		'<a href="/adm/preferences?action=changescreenname">'.&mt('Change Screenname').'</a>';
 2640:             my $blockblog = &Apache::loncommon::blocking_status('blogs');
 2641:             if (!$blockblog) {
 2642:                 $discussoptions.= &add_blog_checkbox($crstype);
 2643:             }
 2644:         }
 2645:     }
 2646:     if ($msgoptions) {
 2647:         $msgoptions='<h2><img src="'.&Apache::loncommon::lonhttpdurl('/res/adm/pages/com.png').'" />'
 2648:                    .' '.&mt('Send Feedback').'</h2>'
 2649:                    .$msgoptions;
 2650:     }
 2651:     if ($discussoptions) { 
 2652: 	$discussoptions='<h2><img src="'.&Apache::loncommon::lonhttpdurl('/adm/lonMisc/chat.gif').'" />'
 2653:                         .' '.&mt('Discussion Contributions').'</h2>'
 2654:                         .$discussoptions;
 2655:     }
 2656:     return $msgoptions.$discussoptions;
 2657: }
 2658: 
 2659: sub resource_output {
 2660:   my ($feedurl) = @_;
 2661:   my $usersaw=&Apache::lonnet::ssi_body($feedurl);
 2662:   $usersaw=~s/\<body[^\>]*\>//gi;
 2663:   $usersaw=~s/\<\/body\>//gi;
 2664:   $usersaw=~s/\<html\>//gi;
 2665:   $usersaw=~s/\<\/html\>//gi;
 2666:   $usersaw=~s/\<head\>//gi;
 2667:   $usersaw=~s/\<\/head\>//gi;
 2668:   $usersaw=~s/action\s*\=/would_be_action\=/gi;
 2669:   return $usersaw;
 2670: }
 2671: 
 2672: sub clear_out_html {
 2673:   my ($message,$override,$ignore_htmlarea)=@_;
 2674:   if (!$ignore_htmlarea
 2675:       && !&Apache::lonhtmlcommon::htmlareablocked()) { return $message; }
 2676: # Always allow the <m>-tag
 2677:   my %html=(M=>1);
 2678: # Check if more is allowed
 2679:   my $cid=$env{'request.course.id'};
 2680:   if (($env{"course.$cid.allow_limited_html_in_feedback"} =~ m/yes/i) ||
 2681:       ($override)) {
 2682:       # allows <B> <I> <P> <A> <LI> <OL> <UL> <EM> <BR> <TT> <STRONG> 
 2683:       # <BLOCKQUOTE> <DIV .*> <DIV> <IMG> <M> <SPAN> <H1> <H2> <H3> <H4> <SUB>
 2684:       # <SUP>
 2685:       %html=(B=>1, I=>1, P=>1, A=>1, LI=>1, OL=>1, UL=>1, EM=>1,
 2686: 	     BR=>1, TT=>1, STRONG=>1, BLOCKQUOTE=>1, DIV=>1, IMG=>1,
 2687: 	     M=>1, ALGEBRA=>1, SUB=>1, SUP=>1, SPAN=>1, 
 2688: 	     H1=>1, H2=>1, H3=>1, H4=>1, H5=>1);
 2689:   }
 2690: # Do the substitution of everything that is not explicitly allowed
 2691:   $message =~ s/\<(\/?\s*(\w+)[^\>\<]*)/
 2692: 	  {($html{uc($2)}&&(length($1)<1000))?"\<$1":"\&lt;$1"}/ge;
 2693:   $message =~ s/(\<?\s*(\w+)[^\<\>]*)\>/
 2694: 	  {($html{uc($2)}&&(length($1)<1000))?"$1\>":"$1\&gt;"}/ge;
 2695:   return $message;
 2696: }
 2697: 
 2698: sub assemble_email {
 2699:   my ($message,$prevattempts,$usersaw,$useranswer)=@_;
 2700:   my %lt = &Apache::lonlocal::texthash(
 2701:              'prev' => 'Previous attempts of student (if applicable)',
 2702:              'orig' => 'Original screen output (if applicable)',
 2703:              'corr' => 'Correct Answer(s) (if applicable)',
 2704:   );
 2705:   if (&Apache::loncommon::course_type() eq 'Community') {
 2706:       $lt{'prev'} = &mt('Previous attempts of member (if applicable)');
 2707:   }
 2708:   my $email=<<"ENDEMAIL";
 2709: $message
 2710: ENDEMAIL
 2711:     my $citations=<<"ENDCITE";
 2712: <h2>$lt{'prev'}</h2>
 2713: $prevattempts
 2714: <br /><hr />
 2715: <h2>$lt{'orig'}</h2>
 2716: $usersaw
 2717: <h2>$lt{'corr'}</h2>
 2718: $useranswer
 2719: ENDCITE
 2720:   return ($email,$citations);
 2721: }
 2722: 
 2723: 
 2724: sub feedback_available {
 2725:     my ($question,$course,$policy)=@_;
 2726:     my ($typestyle,%to)=&Apache::lonmsg::decide_receiver('',0,$question,
 2727: 							 $course,$policy);
 2728:     return scalar(%to);
 2729: }
 2730: 
 2731: sub send_msg {
 2732:     my ($title,$feedurl,$email,$citations,$attachmenturl,$symb,%to)=@_;
 2733:     my $status='';
 2734:     my $sendsomething=0;
 2735:     my $restitle = &get_resource_title($symb,$feedurl);
 2736:     if ($title=~/^Error/) { $title=&mt('Feedback').': '.$title; }
 2737:     unless ($title=~/\w/) { $title=&mt('Feedback'); }
 2738:     foreach my $key (keys(%to)) {
 2739: 	if ($key) {
 2740: 	    my ($user,$domain) = split(/\:/,$key,2);
 2741: 	    if (!defined($user)) {
 2742: 		$status.='<br />'.&mt('Error sending message to [_1], no user specified.',$key);
 2743: 	    } elsif (!defined($domain)) {
 2744: 		$status.='<br />'.&mt('Error sending message to [_1], no domain specified.',$key);
 2745: 	    } else {
 2746: 		unless (&Apache::lonmsg::user_normal_msg($user,$domain,
 2747: 							 $title.' ['.$restitle.']',$email,$citations,$feedurl,
 2748: 							 $attachmenturl,undef,undef,$symb,$restitle)=~/ok/) {
 2749: 		    $status.='<br />'.&mt('Error sending message to').' '.$key.'<br />';
 2750: 		} else {
 2751: 		    $sendsomething++;
 2752: 		}
 2753: 	    }
 2754: 	}
 2755:     }
 2756: 
 2757: 
 2758:     my %record=&Apache::lonnet::restore('_feedback');
 2759:     my ($temp)=keys(%record);
 2760:     unless ($temp=~/^error\:/) {
 2761: 	my %newrecord=();
 2762: 	$newrecord{'resource'}=$feedurl;
 2763: 	$newrecord{'subnumber'}=$record{'subnumber'}+1;
 2764: 	unless (&Apache::lonnet::cstore(\%newrecord,'_feedback') eq 'ok') {
 2765: 	    $status.='<br />'.&mt('Not registered').'<br />';
 2766: 	}
 2767:     }
 2768:     
 2769:     return ($status,$sendsomething);
 2770: }
 2771: 
 2772: sub adddiscuss {
 2773:     my ($symb,$email,$anon,$attachmenturl,$subject)=@_;
 2774:     my $status='';
 2775:     my $realsymb;
 2776:     if ($symb=~/^bulletin___/) {
 2777: 	my $filename=(&Apache::lonnet::decode_symb($symb))[2];
 2778: 	$filename=~s|^adm/wrapper/||;
 2779: 	$realsymb=&Apache::lonnet::symbread($filename);
 2780:     }
 2781:     if (&discussion_open(undef,$realsymb) &&
 2782: 	&Apache::lonnet::allowed('pch',$env{'request.course.id'}.
 2783:         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) {
 2784: 
 2785:     my %contrib=('message'      => $email,
 2786:                  'sendername'   => $env{'user.name'},
 2787:                  'senderdomain' => $env{'user.domain'},
 2788:                  'screenname'   => $env{'environment.screenname'},
 2789:                  'plainname'    => $env{'environment.firstname'}.' '.
 2790: 		                   $env{'environment.middlename'}.' '.
 2791:                                    $env{'environment.lastname'}.' '.
 2792:                                    $env{'enrironment.generation'},
 2793:                  'attachmenturl'=> $attachmenturl,
 2794:                  'subject'      => $subject);
 2795:     if ($env{'form.replydisc'}) {
 2796: 	$contrib{'replyto'}=(split(/\:\:\:/,$env{'form.replydisc'}))[1];
 2797:     }
 2798:     if ($anon) {
 2799: 	$contrib{'anonymous'}='true';
 2800:     }
 2801:     if (($symb) && ($email)) {
 2802:         my $now = time;
 2803:         if ($env{'form.editdisc'}) {
 2804:             $contrib{'ip'}=$ENV{'REMOTE_ADDR'};
 2805:             $contrib{'host'}=$Apache::lonnet::perlvar{'lonHostID'};
 2806:             $contrib{'timestamp'} = $now;
 2807:             $contrib{'history'} = '';
 2808:             my $numoldver = 0;
 2809:             my ($oldsymb,$oldidx)=split(/\:\:\:/,$env{'form.editdisc'});
 2810: 	    &Apache::lonenc::check_decrypt(\$oldsymb);
 2811:             $oldsymb=~s|(bulletin___\d+___)adm/wrapper/|$1|;
 2812: # get timestamp for last post and history
 2813:             my %oldcontrib=&Apache::lonnet::restore($oldsymb,$env{'request.course.id'},
 2814:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 2815:                      $env{'course.'.$env{'request.course.id'}.'.num'});
 2816:             if (defined($oldcontrib{$oldidx.':replyto'})) {
 2817:                 $contrib{'replyto'} = $oldcontrib{$oldidx.':replyto'};
 2818:             }
 2819:             if (defined($oldcontrib{$oldidx.':history'})) {
 2820:                 if ($oldcontrib{$oldidx.':history'} =~ /:/) {
 2821:                     my @oldversions = split(/:/,$oldcontrib{$oldidx.':history'});
 2822:                     $numoldver = @oldversions;
 2823:                 } else {
 2824:                     $numoldver = 1;
 2825:                 }
 2826:                 $contrib{'history'} = $oldcontrib{$oldidx.':history'}.':';
 2827:             }
 2828:             my $numnewver = $numoldver + 1;
 2829:             if (defined($oldcontrib{$oldidx.':subject'})) {
 2830:                 if ($oldcontrib{$oldidx.':subject'} =~ /^<version num="0">/) {
 2831:                     $contrib{'subject'} = '<version num="'.$numnewver.'">'.&HTML::Entities::encode($contrib{'subject'},'<>&"').'</version>';
 2832:                     $contrib{'subject'} = $oldcontrib{$oldidx.':subject'}.$contrib{'subject'};
 2833:                 } else {
 2834:                     $contrib{'subject'} = '<version num="0">'.&HTML::Entities::encode($oldcontrib{$oldidx.':subject'},'<>&"').'</version><version num="1">'.&HTML::Entities::encode($contrib{'subject'},'<>&"').'</version>';
 2835:                 }
 2836:             } 
 2837:             if (defined($oldcontrib{$oldidx.':message'})) {
 2838:                 if ($oldcontrib{$oldidx.':message'} =~ /^<version num="0">/) {
 2839:                     $contrib{'message'} = '<version num="'.$numnewver.'">'.&HTML::Entities::encode($contrib{'message'},'<>&"').'</version>';
 2840:                     $contrib{'message'} = $oldcontrib{$oldidx.':message'}.$contrib{'message'};
 2841:                 } else {
 2842:                     $contrib{'message'} = '<version num="0">'.&HTML::Entities::encode($oldcontrib{$oldidx.':message'},'<>&"').'</version><version num="1">'.&HTML::Entities::encode($contrib{'message'},'<>&"').'</version>';
 2843:                 }
 2844:             }
 2845:             $contrib{'history'} .= $oldcontrib{$oldidx.':timestamp'};
 2846:             my $put_reply = &Apache::lonnet::putstore($env{'request.course.id'},
 2847:                   $oldsymb,$oldidx,\%contrib,
 2848:                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 2849:                   $env{'course.'.$env{'request.course.id'}.'.num'});
 2850:             $status='Editing class discussion'.($anon?' (anonymous)':'');
 2851:         } else {
 2852:            $status='Adding to class discussion'.($anon?' (anonymous)':'').': '.
 2853:            &Apache::lonnet::store(\%contrib,$symb,$env{'request.course.id'},
 2854:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 2855: 		     $env{'course.'.$env{'request.course.id'}.'.num'});
 2856:         }
 2857:         my %storenewentry=($symb => $now);
 2858:         $status.='<br />'.&mt('Updating discussion time').': '.
 2859:         &Apache::lonnet::put('discussiontimes',\%storenewentry,
 2860:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 2861: 		     $env{'course.'.$env{'request.course.id'}.'.num'});
 2862:     }
 2863:     my %record=&Apache::lonnet::restore('_discussion');
 2864:     my ($temp)=keys(%record);
 2865:     unless ($temp=~/^error\:/) {
 2866:        my %newrecord=();
 2867:        $newrecord{'resource'}=$symb;
 2868:        $newrecord{'subnumber'}=$record{'subnumber'}+1;
 2869:        $status.='<br />'.&mt('Registering').': '.
 2870:                &Apache::lonnet::cstore(\%newrecord,'_discussion');
 2871:     }
 2872:     } else {
 2873: 	$status.='Failed.';
 2874:     }
 2875:     return $status.'<br />';   
 2876: }
 2877: 
 2878: sub get_discussion_info {
 2879:     my ($idx,%contrib) = @_;
 2880:     my $changelast = 0;
 2881:     my $count = 0;
 2882:     my $hiddenflag = 0;
 2883:     my $deletedflag = 0;
 2884:     my ($hidden,$deleted,%info,$newlastdisc);
 2885:     my $version = $contrib{'version'};
 2886:     if ($version) {
 2887:         for (my $id=$version; $id>0; $id--) {
 2888:             my $vkeys=$contrib{$id.':keys'};
 2889:             my @keys=split(/:/,$vkeys);
 2890:             if (grep(/^hidden$/,@keys)) {
 2891:                 if (!$hiddenflag) {
 2892:                     $hidden = $contrib{$id.':hidden'};
 2893:                     $hiddenflag = 1;
 2894:                 }
 2895:             } elsif (grep(/^deleted$/,@keys)) {
 2896:                 if (!$deletedflag) {
 2897:                     $deleted = $contrib{$id.':deleted'};
 2898:                     $deletedflag = 1;
 2899:                 }
 2900:             } else {
 2901:                 if (($hidden !~/\.$id\./) && ($deleted !~/\.$id\./)) {
 2902:                     $count++;
 2903:                     $info{$count}{'id'} = $id;
 2904:                     $info{$count}{'timestamp'}=$contrib{$id.':timestamp'}; 
 2905:                 }
 2906:             }
 2907:         }
 2908:         if ($info{'1'}{'id'} == $idx) {
 2909:             $changelast = 1;
 2910:             if ($count > 1) { 
 2911:                 $newlastdisc =  $info{'2'}{'timestamp'};
 2912:             } else {
 2913:                 $newlastdisc = 0;
 2914:             }
 2915:         }
 2916:     }
 2917:     return ($changelast,$newlastdisc);
 2918: }
 2919: 
 2920: # ----------------------------------------------------------- Preview function
 2921: 
 2922: sub show_preview {
 2923:     my ($r) = @_;
 2924:     &Apache::loncommon::content_type($r,'text/html');
 2925:     $r->send_http_header;
 2926:     my $start_page=
 2927: 	&Apache::loncommon::start_page('Preview',undef,
 2928: 				       {'only_body'   => 1,});
 2929: 
 2930:     my $message=&clear_out_html($env{'form.comment'});
 2931:     &newline_to_br(\$message);
 2932:     $message=&Apache::lonspeller::markeduptext($message);
 2933:     $message=&Apache::lontexconvert::msgtexconverted($message);
 2934:     my $subject=&clear_out_html($env{'form.subject'},undef,1);
 2935:     $subject=~s/\n/\<br \/\>/g;
 2936:     $subject=&Apache::lontexconvert::msgtexconverted($subject);
 2937: 					
 2938:     my $end_page = &Apache::loncommon::end_page();
 2939: 
 2940:     $r->print($start_page
 2941:              .'<h1>'.&mt('Preview').'</h1>'
 2942:              .&Apache::lonhtmlcommon::start_pick_box()
 2943:              .&Apache::lonhtmlcommon::row_title(&mt('Subject'))
 2944:              .$subject
 2945:              .&Apache::lonhtmlcommon::row_closure()
 2946:              .&Apache::lonhtmlcommon::row_title(&mt('Message'))
 2947:              .$message
 2948:              .&Apache::lonhtmlcommon::row_closure(1)
 2949:              .&Apache::lonhtmlcommon::end_pick_box()
 2950:              .$end_page
 2951:     );
 2952: }
 2953: 
 2954: 
 2955: sub newline_to_br {
 2956:     my ($message)=@_;
 2957:     my $newmessage;
 2958:     my $parser=HTML::LCParser->new($message);
 2959:     while (my $token=$parser->get_token()) {
 2960: 	if ($token->[0] eq 'T') {
 2961: 	    my $text=$token->[1];
 2962: 	    $text=~s/\n/\<br \/\>/g;
 2963: 	    $newmessage.=$text;
 2964: 	} elsif ($token->[0] eq 'D' || $token->[0] eq 'C') {
 2965: 	    $newmessage.=$token->[1];
 2966: 	} elsif ($token->[0] eq 'PI' || $token->[0] eq 'E') {
 2967: 	    $newmessage.=$token->[2];
 2968: 	} elsif ($token->[0] eq 'S') {
 2969: 	    $newmessage.=$token->[4];
 2970: 	}
 2971: 	    
 2972:     }
 2973:     $$message=$newmessage;
 2974: }
 2975: 
 2976: sub generate_preview_button {
 2977:     my ($formname,$fieldname)=@_;
 2978:     unless ($formname) { $formname='mailform'; }
 2979:     unless ($fieldname) { $fieldname='comment'; }
 2980:     my $pre=&mt("Show Preview and Check Spelling");
 2981:     return(<<ENDPREVIEW);
 2982: <br />
 2983: <form name="preview" action="/adm/feedback?preview=1" method="post" target="preview">
 2984: <input type="hidden" name="subject" />
 2985: <input type="hidden" name="comment" />
 2986: <input type="button" value="$pre"
 2987: onClick="if (typeof(document.$formname.onsubmit)=='function') {document.$formname.onsubmit();};this.form.comment.value=document.$formname.$fieldname.value;this.form.subject.value=document.$formname.subject.value;this.form.submit();" />
 2988: </form>
 2989: ENDPREVIEW
 2990: }
 2991: 
 2992: sub modify_attachments {
 2993:     my ($r,$currnewattach,$currdelold,$symb,$idx,$attachmenturls,
 2994:         $attachmaxtext,$toolarge)=@_;
 2995: 
 2996:     my %lt = &Apache::lonlocal::texthash(
 2997:                'subj' => 'Subject',
 2998:                'thfo' => 'The following attachments were part of the most recent saved version of this posting.',
 2999:                'chth' => 'Check the checkboxes for any you wish to remove.',
 3000:                'thef' => 'The following attachments have been uploaded for inclusion with this posting.',
 3001:                'adda' => 'Add a new attachment to this post.',
 3002:                'stch' => 'Save Changes',
 3003:              );
 3004:     my $js = <<END;
 3005: <script type="text/javascript">
 3006:  function setAction () {
 3007:    document.modattachments.action = document.modattachments.origpage.value;
 3008:    document.modattachments.submit();
 3009:  }
 3010: </script> 
 3011: END
 3012: 
 3013:     # Breadcrumbs
 3014:     my $brcrum = [{'href' => '',
 3015:                    'text' => 'Discussion Post Attachments'}];
 3016:     my $start_page = 
 3017: 	&Apache::loncommon::start_page('Discussion Post Attachments',$js,
 3018:                                    {'bread_crumbs' => $brcrum,});
 3019: 
 3020:     my $orig_subject = &unescape($env{'form.subject'});
 3021:     my $subject=&clear_out_html($orig_subject,undef,1);
 3022:     $subject=~s/\n/\<br \/\>/g;
 3023:     $subject=&Apache::lontexconvert::msgtexconverted($subject);
 3024:     my $timestamp=$env{'form.timestamp'};
 3025:     my $numoldver=$env{'form.numoldver'};
 3026: 
 3027:     my $msg = '';
 3028:     my %attachments = ();
 3029:     my %currattach = ();
 3030:     if ($idx) {
 3031:         &extract_attachments($attachmenturls,$idx,$numoldver,\$msg,\%attachments,\%currattach,$currdelold);
 3032:     }
 3033:     &Apache::lonenc::check_encrypt(\$symb);
 3034: 
 3035:     my $end_page = 
 3036: 	&Apache::loncommon::end_page();
 3037: 				       
 3038:     $r->print(<<END);
 3039: $start_page
 3040: $toolarge
 3041: <form name="modattachments" method="post" enctype="multipart/form-data" action="/adm/feedback?attach=$symb">
 3042:  <br />
 3043:  <table class="LC_data_table">
 3044:   <tr>
 3045:    <td colspan="2">
 3046:     <b>Subject:</b> $subject</b><br /><br />
 3047: END
 3048:     if ($idx) {
 3049:         if ($attachmenturls) {
 3050:             my @currold = keys(%currattach);
 3051:             if (@currold > 0) {
 3052:                 $r->print($lt{'thfo'}.'<br />'.$lt{'chth'}.'<br />'."\n");  
 3053:                 foreach my $id (@currold) {
 3054:                     my $attachurl = &HTML::Entities::decode($attachments{$id}{'filename'}); 
 3055:                     $attachurl =~ m#/([^/]+)$#;
 3056:                     $r->print('<label><input type="checkbox" name="deloldattach" value="'.$id.'" />&nbsp;'.$1.'</label><br />'."\n");
 3057:                 }
 3058:                 $r->print("<br />");
 3059:             }
 3060:         }
 3061:     }
 3062:     if ((ref($currnewattach) eq 'ARRAY') && (@{$currnewattach} > 0)) {
 3063:         $r->print($lt{'thef'}.'<br />'.$lt{'chth'}.'<br />'."\n");
 3064:         foreach my $attach (@{$currnewattach}) {
 3065:             $attach =~ m#/([^/]+)$#;
 3066:             $r->print('<label><input type="checkbox" name="delnewattach" value="'.$attach.'" />&nbsp;'.$1.'</label><br />'."\n");
 3067:         }
 3068:         $r->print("<br />"); 
 3069:     }
 3070:     $r->print(<<END);
 3071:    </td></tr>
 3072:    <tr>
 3073:     <td>
 3074:    $lt{'adda'}</td><td><input type="file" name="addnewattach" /><input type="button" name="upload" value="Upload" onClick="this.form.submit()" />    
 3075:    </td>
 3076:   </tr>
 3077:   <tr>
 3078:    <td colspan="2">$attachmaxtext</td>
 3079:   </tr>
 3080:  </table>
 3081: <input type="hidden" name="subject" value="$env{'form.subject'}" />
 3082: <input type="hidden" name="comment" value="$env{'form.comment'}" />
 3083: <input type="hidden" name="timestamp" value="$env{'form.timestamp'}" />
 3084: <input type="hidden" name="idx" value="$env{'form.idx'}" />
 3085: <input type="hidden" name="numoldver" value="$env{'form.numoldver'}" />
 3086: <input type="hidden" name="origpage" value="$env{'form.origpage'}" />
 3087: <input type="hidden" name="blog" value="$env{'form.blog'}" />
 3088: <input type="hidden" name="discuss" value="$env{'form.discuss'}" />
 3089: END
 3090:     foreach my $item (@{$currnewattach}) {
 3091:         $r->print('<input type="hidden" name="currnewattach" value="'.$item.'" />'."\n");
 3092:     }
 3093:     foreach my $item (@{$currdelold}) {
 3094:         $r->print('<input type="hidden" name="deloldattach" value="'.$item.'" />'."\n");
 3095:     }
 3096:     $r->print(<<END);
 3097:  <input type="button" name="rtntoedit" value="$lt{'stch'}" onClick="setAction()" />
 3098: </form>
 3099: $end_page
 3100: END
 3101:     return;
 3102: }
 3103: 
 3104: sub process_attachments {
 3105:     my ($currnewattach,$currdelold,$keepold) = @_;
 3106: 
 3107:     @{$currnewattach}=
 3108: 	&Apache::loncommon::get_env_multiple('form.currnewattach');
 3109:     @{$currdelold}=
 3110: 	&Apache::loncommon::get_env_multiple('form.deloldattach');
 3111:     if (exists($env{'form.delnewattach'})) {
 3112:         my @currdelnew =
 3113: 	    &Apache::loncommon::get_env_multiple('form.delnewattach');
 3114:         my @currnew = ();
 3115:         foreach my $newone (@{$currnewattach}) {
 3116:             my $delflag = 0;
 3117:             foreach my $item (@currdelnew) {
 3118:                 if ($newone eq $item) {
 3119:                     $delflag = 1;
 3120:                     last;
 3121:                 }
 3122:             }
 3123:             unless ($delflag) {
 3124:                 push(@currnew, $newone);
 3125:             }
 3126:         }
 3127:         @{$currnewattach} = @currnew;
 3128:     }
 3129:     @{$keepold} = &Apache::loncommon::get_env_multiple('form.keepold');
 3130: }
 3131: 
 3132: sub generate_attachments_button {
 3133:     my ($idx,$attachnum,$ressymb,$now,$currnewattach,$deloldattach,
 3134:         $numoldver,$mode,$blockblog) = @_;
 3135:     my $origpage = $ENV{'REQUEST_URI'};
 3136:     my $att=$attachnum.' '.&mt("attachments");
 3137:     my %lt = &Apache::lonlocal::texthash(
 3138:                 'clic' => 'Click to add/remove attachments',
 3139:     ); 
 3140:     my $response = (<<END);
 3141: <br />
 3142: <form name="attachment" action="/adm/feedback?attach=$ressymb" method="post">
 3143: $lt{'clic'}:&nbsp;<input type="button" value="$att"
 3144: onClick="if (typeof(document.mailform.onsubmit)=='function') {document.mailform.onsubmit();};this.form.comment.value=escape(document.mailform.comment.value);this.form.subject.value=escape(document.mailform.subject.value);
 3145: END
 3146:     if (!$blockblog) {
 3147:         $response .= 'setblogvalue();';
 3148:     }
 3149:     unless ($mode eq 'board') {
 3150:         $response .= 'javascript:anonchk();';
 3151:     }
 3152:     $response .= (<<ENDATTACH);
 3153: this.form.submit();" />
 3154: <input type="hidden" name="origpage" value="$origpage" />
 3155: <input type="hidden" name="idx" value="$idx" />
 3156: <input type="hidden" name="timestamp" value="$now" />
 3157: <input type="hidden" name="subject" />
 3158: <input type="hidden" name="comment" />
 3159: <input type="hidden" name="blog" value="0" />
 3160: <input type="hidden" name="discuss" value="0" />
 3161: <input type="hidden" name="numoldver" value="$numoldver" />
 3162: ENDATTACH
 3163:     if (defined($deloldattach)) {
 3164:         if (@{$deloldattach} > 0) {
 3165:             foreach my $delatt (@{$deloldattach}) {
 3166:                 $response .= '<input type="hidden" name="deloldattach" value="'.$delatt.'" />'."\n";
 3167:             }
 3168:         }
 3169:     }
 3170:     if (defined($currnewattach)) {
 3171:         if (@{$currnewattach} > 0) {
 3172:             foreach my $attach (@{$currnewattach}) {
 3173:                 $response .= '<input type="hidden" name="currnewattach" value="'.$attach.'" />'."\n";
 3174:             }
 3175:         }
 3176:     }
 3177:     $response .= '</form>';
 3178:     return $response;
 3179: }
 3180: 
 3181: sub extract_attachments {
 3182:     my ($attachmenturls,$idx,$numoldver,$message,$attachments,$currattach,$currdelold) = @_;
 3183:     %{$attachments}=();
 3184:     &get_post_attachments($attachments,$attachmenturls);
 3185:     foreach my $id (sort(keys(%{$attachments}))) {
 3186:         if (exists($$attachments{$id}{$numoldver})) {
 3187:             if (defined($currdelold)) {
 3188:                 if (@{$currdelold} > 0) {
 3189:                     unless (grep/^$id$/,@{$currdelold}) {
 3190:                         $$currattach{$id} = $$attachments{$id}{$numoldver}; 
 3191:                     }
 3192:                 } else {
 3193:                     $$currattach{$id} = $$attachments{$id}{$numoldver};
 3194:                 }
 3195:             } else {
 3196:                 $$currattach{$id} = $$attachments{$id}{$numoldver};
 3197:             }
 3198:         }
 3199:     }
 3200:     my @attached = (sort { $a <=> $b } keys(%{$currattach}));
 3201:     if (@attached == 1) {
 3202:         my $id = $attached[0];
 3203:         my $attachurl;
 3204:         if ($attachmenturls =~ m/^<attachment id="0">/) {
 3205:             $attachurl = &HTML::Entities::decode($$attachments{$id}{'filename'});
 3206:         } else {
 3207:             $attachurl = $$attachments{$id}{'filename'};
 3208:         }
 3209:         $attachurl=~m|/([^/]+)$|;
 3210:         $$message.='<br /><a href="'.$attachurl.'"><tt>'.
 3211:         $1.'</tt></a><br />';
 3212:         &Apache::lonnet::allowuploaded('/adm/feedback',
 3213:                                $attachurl);
 3214:     } elsif (@attached > 1) {
 3215:         $$message.='<ol>';
 3216:         foreach my $attach (@attached) {
 3217:             my $id = $attach;
 3218:             my $attachurl = &HTML::Entities::decode($$attachments{$id}{'filename'});
 3219:             my ($fname)
 3220:               =($attachurl=~m|/([^/]+)$|);
 3221:             $$message .= '<li><a href="'.$attachurl.
 3222:               '"><tt>'.
 3223:               $fname.'</tt></a></li>';
 3224:             &Apache::lonnet::allowuploaded('/adm/feedback',
 3225:                              $attachurl);
 3226:         }
 3227:         $$message .= '</ol>';
 3228:     }
 3229: }
 3230: 
 3231: sub construct_attachmenturl {
 3232:     my ($currnewattach,$keepold,$symb,$idx)=@_;
 3233:     my $oldattachmenturl;
 3234:     my $newattachmenturl;
 3235:     my $startnum = 0;
 3236:     my $currver = 0;
 3237:     if (($env{'form.editdisc'}) && ($idx)) {
 3238:         my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 3239:                        $env{'course.'.$env{'request.course.id'}.'.domain'},
 3240:                        $env{'course.'.$env{'request.course.id'}.'.num'});
 3241:         $oldattachmenturl = $contrib{$idx.':attachmenturl'};
 3242:         if ($contrib{$idx.':history'}) {
 3243:             if ($contrib{$idx.':history'} =~ /:/) {
 3244:                 my @oldversions = split(/:/,$contrib{$idx.':history'});
 3245:                 $currver = 1 + scalar(@oldversions);
 3246:             } else {
 3247:                 $currver = 2;
 3248:             }
 3249:         } else {
 3250:             $currver = 1;
 3251:         }
 3252:         if ($oldattachmenturl) {
 3253:             if ($oldattachmenturl =~ m/^<attachment id="0">/) {
 3254:                 my %attachments = ();
 3255:                 my $prevver = $currver-1;
 3256:                 &get_post_attachments(\%attachments,$oldattachmenturl);
 3257:                 my $numattach = scalar(keys(%attachments));
 3258:                 $startnum += $numattach;
 3259:                 foreach my $num (sort {$a <=> $b} keys(%attachments)) {
 3260:                     $newattachmenturl .= '<attachment id="'.$num.'"><filename>'.$attachments{$num}{'filename'}.'</filename>';
 3261:                     foreach my $item (sort {$a <=> $b} keys(%{$attachments{$num}})) {
 3262:                         unless ($item eq 'filename') {
 3263:                             $newattachmenturl .= '<post id="'.$item.'">'.$attachments{$num}{$item}.'</post>';
 3264:                         }
 3265:                     }
 3266:                     if (grep/^$num$/,@{$keepold}) {
 3267:                         $newattachmenturl .= '<post id="'.$currver.'">'.$attachments{$num}{$prevver}.'</post>';
 3268:                     }
 3269:                     $newattachmenturl .= '</attachment>';
 3270:                 }
 3271:             } else {
 3272:                 $newattachmenturl = '<attachment id="0"><filename>'.&HTML::Entities::encode($oldattachmenturl).'</filename><post id="0">n</post>';
 3273:                 unless (grep/^0$/,@{$keepold}) {
 3274:                     $newattachmenturl .= '<post id="1">n</post>';
 3275:                 }
 3276:                 $newattachmenturl .= '</attachment>';
 3277:                 $startnum ++;
 3278:             }
 3279:         }
 3280:     }
 3281:     for (my $i=0; $i<@{$currnewattach}; $i++) {
 3282:         my $attachnum = $startnum + $i;
 3283:         $newattachmenturl .= '<attachment id="'.$attachnum.'"><filename>'.&HTML::Entities::encode($$currnewattach[$i]).'</filename><post id="'.$currver.'">n</post></attachment>';
 3284:     }
 3285:     return $newattachmenturl; 
 3286: }
 3287: 
 3288: sub add_blog_checkbox {
 3289:     my ($crstype) = @_;
 3290:     my $checkstatus;
 3291:     if ($env{'form.blog'}) {
 3292:         $checkstatus = 'checked="checked"';
 3293:     }
 3294:     my $output = '
 3295: <script type="text/javascript">
 3296: function setblogvalue() {
 3297:     if (document.mailform.blog.checked) {
 3298:         document.attachment.blog.value = 1;
 3299:     } else {
 3300:         document.attachment.blog.value = 0;
 3301:     }
 3302: }
 3303: </script><br />
 3304: <label><input type="checkbox" name="blog" '.$checkstatus.' /> ';
 3305:     if ($crstype eq 'Community') {
 3306:         $output .= &mt('Add to my public community blog');
 3307:     } else {
 3308:         $output .= &mt('Add to my public course blog');
 3309:     } 
 3310:     $output .= '</label><br />'."\n";
 3311:     return $output;
 3312: }
 3313: 
 3314: sub has_discussion {
 3315:     my $resourcesref = shift;
 3316:     my $navmap = Apache::lonnavmaps::navmap->new();
 3317:     if (defined($navmap)) {
 3318:         my @allres=$navmap->retrieveResources();
 3319:         foreach my $resource (@allres) {
 3320:             if ($resource->hasDiscussion()) {
 3321:                 my $ressymb = $resource->wrap_symb();
 3322:                 if (ref($resourcesref) eq 'ARRAY') {
 3323:                     push(@{$resourcesref}, $ressymb);
 3324:                 }
 3325:             }
 3326:         }
 3327:     } else {
 3328:         &Apache::lonnet::logthis('Has discussion check failed - could not create navmap object.');
 3329:     }
 3330:     return;
 3331: }
 3332: 
 3333: sub sort_filter_names {
 3334:     my ($sort_types,$role_types,$status_types,$crstype) = @_;
 3335:     if (ref($sort_types) eq 'HASH') {
 3336:         %{$sort_types} = (
 3337:                      ascdate => 'Date order - oldest first',
 3338:                      descdate => 'Date order - newest first',
 3339:                      thread => 'Threaded',
 3340:                      subject => 'By subject',
 3341:                      username => 'By domain and username',
 3342:                      lastfirst => 'By last name, first name'
 3343:                    );
 3344:     }
 3345:     my @courseroles = qw(st in ta ep ad);
 3346:     if ($crstype eq 'Community') {
 3347:         push(@courseroles,'co');
 3348:     } else {
 3349:         push(@courseroles,'cc');
 3350:     }
 3351:     if (ref($role_types) eq 'HASH') {
 3352:         foreach my $role (@courseroles) {
 3353:             $role_types->{$role} = &Apache::lonnet::plaintext($role,$crstype);
 3354:         }
 3355:         $role_types->{'all'} = 'All roles';
 3356:         $role_types->{'cr'} = 'Custom role';
 3357:     }
 3358:     if (ref($status_types) eq 'HASH') {
 3359:         %{$status_types} = (
 3360:                      all     => 'Roles of any status',
 3361:                      Active  => 'Only active roles',
 3362:                      Expired => 'Only past roles',
 3363:                      Future  => 'Only future roles',
 3364:                    );
 3365:     }
 3366: }
 3367:   
 3368: sub handler {
 3369:   my $r = shift;
 3370:   if ($r->header_only) {
 3371:      &Apache::loncommon::content_type($r,'text/html');
 3372:      $r->send_http_header;
 3373:      return OK;
 3374:   }
 3375: 
 3376: # --------------------------- Get query string for limited number of parameters
 3377: 
 3378:   &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 3379:          ['hide','unhide','deldisc','postdata','preview','replydisc','editdisc','cmd','symb','onlyunread','allposts','onlyunmark','previous','markread','markonread','markondisp','toggoff','toggon','modifydisp','changes','navtime','navmaps','navurl','sortposts','applysort','rolefilter','statusfilter','sectionpick','groupick','posterlist','userpick','attach','origpage','currnewattach','deloldattach','keepold','allversions','export','sendmessageonly','group','ref']);
 3380:   my $group = $env{'form.group'};
 3381:   my %attachmax = (
 3382:                     text => &mt('(128 KB max size)'),
 3383:                     num  => 131072,
 3384:                   );
 3385:   if ($env{'form.editdisc'}) {
 3386:       if (!(&editing_allowed($env{'form.editdisc'},$env{'form.group'}))) {
 3387:           my $symb=(split(/\:\:\:/,$env{'form.editdisc'}))[0];
 3388:           my ($map,$id,$url)=&Apache::lonnet::decode_symb($symb);
 3389:           my $feedurl=&Apache::lonnet::clutter($url);
 3390:           &redirect_back($r,$feedurl,&mt('Editing not permitted').'<br />',                     '0','0','','',$env{'form.previous'},undef,undef,undef,
 3391:                     undef,undef,undef,$group);
 3392:           return OK;
 3393:       }
 3394:   } 
 3395:   if ($env{'form.discsymb'}) {
 3396:       my ($symb,$feedurl) = &get_feedurl_and_clean_symb($env{'form.discsymb'});
 3397:       my $readkey = $symb.'_read';
 3398:       my $chgcount = 0;
 3399:       my %readinghash = &Apache::lonnet::get('nohist_'.$env{'request.course.id'}.'_discuss',[$readkey],$env{'user.domain'},$env{'user.name'});
 3400:       foreach my $key (keys(%env)) {
 3401:           if ($key =~ m/^form\.postunread_(\d+)/) {
 3402:               if ($readinghash{$readkey} =~ /\.$1\./) {
 3403:                   $readinghash{$readkey} =~ s/\.$1\.//;
 3404:                   $chgcount ++;
 3405:               }
 3406:           } elsif ($key =~ m/^form\.postread_(\d+)/) {
 3407:               unless ($readinghash{$readkey} =~ /\.$1\./) {
 3408:                   $readinghash{$readkey} .= '.'.$1.'.';
 3409:                   $chgcount ++;
 3410:               }
 3411:           }
 3412:       }
 3413:       if ($chgcount > 0) {
 3414:           &Apache::lonnet::put('nohist_'.$env{'request.course.id'}.'_discuss',
 3415: 			  \%readinghash,$env{'user.domain'},$env{'user.name'});
 3416:       }
 3417:       &redirect_back($r,$feedurl,&mt('Marked postings read/unread').'<br />',
 3418: 		     '0','0','','',$env{'form.previous'},'','','',
 3419:                      undef,undef,undef,$group);
 3420:       return OK;
 3421:   }
 3422:   if ($env{'form.allversions'}) {
 3423:       &Apache::loncommon::content_type($r,'text/html');
 3424:       &Apache::loncommon::no_cache($r);
 3425:       $r->send_http_header;
 3426: 
 3427:       # Breadcrumbs
 3428:       my $brcrum = [{'href' => '',
 3429:                      'text' => 'Discussion Post Versions'}];
 3430: 
 3431:       $r->print(&Apache::loncommon::start_page('Discussion Post Versions',undef,
 3432:                                                {'bread_crumbs' => $brcrum,})
 3433:       );
 3434: 
 3435:       my $crs='/'.$env{'request.course.id'};
 3436:       if ($env{'request.course.sec'}) {
 3437:           $crs.='_'.$env{'request.course.sec'};
 3438:       }
 3439:       $crs=~s|_|/|g;
 3440:       my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3441:       my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3442:       my ($symb,$idx)=split(/\:\:\:/,$env{'form.allversions'});
 3443:       ($symb)=&get_feedurl_and_clean_symb($symb);
 3444:       my $ressymb = &wrap_symb($symb);
 3445:       my $group = $env{'form.group'};
 3446:       my $seeid;
 3447:       if (($group ne '') && (($ressymb =~ m|^bulletin___\d+___adm/wrapper/adm/\Q$cdom\E/\Q$cnum\E/\d+/bulletinboard$|))) {
 3448:           if (&check_group_priv($group,'dgp') eq 'ok') {
 3449:               $seeid = 1;
 3450:           }
 3451:       } else {
 3452:           $seeid = &Apache::lonnet::allowed('rin',$crs);
 3453:       }
 3454:       if ($idx > 0) {
 3455:           my %messages = ();
 3456:           my %subjects = ();
 3457:           my %attachmsgs = ();
 3458:           my %allattachments = ();
 3459:           my %imsfiles = ();
 3460:           my ($screenname,$plainname);
 3461:           my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 3462:                            $env{'course.'.$env{'request.course.id'}.'.domain'},
 3463:                            $env{'course.'.$env{'request.course.id'}.'.num'});
 3464:           $r->print(&get_post_contents(\%contrib,$idx,$seeid,'allversions',\%messages,\%subjects,\%allattachments,\%attachmsgs,\%imsfiles,\$screenname,\$plainname));
 3465:       }
 3466:       $r->print(&Apache::loncommon::end_page());
 3467:       return OK;
 3468:   }
 3469:   if ($env{'form.posterlist'}) {
 3470:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.applysort'});
 3471:       &print_showposters($r,$symb,$env{'form.previous'},$feedurl,
 3472: 			 $env{'form.sortposts'});
 3473:       return OK;
 3474:   }
 3475:   if ($env{'form.userpick'}) {
 3476:       my @posters = &Apache::loncommon::get_env_multiple('form.stuinfo');
 3477:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.userpick'});
 3478:       my $numpicks = @posters;
 3479:       my %discinfo;
 3480:       $discinfo{$symb.'_userpick'} = join('&',@posters);
 3481:       &Apache::lonnet::put('nohist_'.$env{'request.course.id'}.'_discuss',
 3482: 			   \%discinfo,$env{'user.domain'},$env{'user.name'});
 3483:       &redirect_back($r,$feedurl,&mt('Changed sort/filter').'<br />','0','0','',
 3484: 		     '',$env{'form.previous'},$env{'form.sortposts'},'','','',
 3485: 		     '',$numpicks,$group);
 3486:       return OK;
 3487:   }
 3488:   if ($env{'form.applysort'}) {
 3489:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.applysort'});
 3490:       &redirect_back($r,$feedurl,&mt('Changed sort/filter').'<br />','0','0','',
 3491: 		     '',$env{'form.previous'},$env{'form.sortposts'},
 3492: 		     $env{'form.rolefilter'},$env{'form.statusfilter'},
 3493: 		     $env{'form.sectionpick'},$env{'form.grouppick'},
 3494:                      undef,$group);
 3495:       return OK;
 3496:   } elsif ($env{'form.cmd'} eq 'sortfilter') {
 3497:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.symb'});
 3498:       &print_sortfilter_options($r,$symb,$env{'form.previous'},$feedurl);
 3499:       return OK;
 3500:   } elsif ($env{'form.navtime'}) {
 3501:       my %discinfo = ();
 3502:       my @resources = ();
 3503:       if (defined($env{'form.navmaps'})) {
 3504:           if ($env{'form.navmaps'} =~ /:/) {
 3505:               @resources = split(/:/,$env{'form.navmaps'});
 3506:           } else {
 3507:               @resources = ("$env{'form.navmaps'}");
 3508:           }
 3509:       } else {
 3510:           &has_discussion(\@resources);
 3511:       }
 3512:       my $numitems = @resources;
 3513:       my $feedurl = '/adm/navmaps';
 3514:       if ($env{'form.navurl'}) { $feedurl .= '?'.$env{'form.navurl'}; }
 3515:       my %lt = &Apache::lonlocal::texthash(
 3516:           'mnpa' => 'Marked "New" posts as read in a total of',
 3517:           'robb' => 'resources/bulletin boards.',
 3518:           'twnp' => 'There are currently no resources or discussion boards with unread discussion postings.'
 3519:       );       
 3520:       foreach my $res (@resources) {
 3521:           my $ressymb=$res;
 3522: 	  &Apache::lonenc::check_decrypt(\$ressymb);
 3523:           my $lastkey = $ressymb.'_lastread';
 3524:           $discinfo{$lastkey} = $env{'form.navtime'};
 3525:       }
 3526:       my $textline = "<b>$lt{'mnpa'} $numitems $lt{'robb'}</b>";
 3527:       if ($numitems > 0) {
 3528:           &Apache::lonnet::put('nohist_'.$env{'request.course.id'}.'_discuss',
 3529: 			     \%discinfo,$env{'user.domain'},$env{'user.name'});
 3530:       } else {
 3531:           $textline = "<b>$lt{'twnp'}</b>";
 3532:       }
 3533:       &Apache::loncommon::content_type($r,'text/html');
 3534:       $r->send_http_header;
 3535:       my $logo=&Apache::loncommon::lonhttpdurl('/adm/lonIcons/lonlogos.gif');
 3536:       my %onload;
 3537:       if ($env{'environment.remote'} ne 'off') {
 3538: 	  $onload{'onload'} =
 3539: 	      "if (window.name!='loncapaclient') { this.document.reldt.submit(); self.window.close(); }";
 3540:       }
 3541: 
 3542:       my $start_page=
 3543: 	  &Apache::loncommon::start_page('New posts marked as read',undef,
 3544: 					 {'redirect'    => [2,$feedurl],
 3545: 					  'only_body'   => 1,
 3546: 					  'add_entries' => \%onload});
 3547:       my $end_page = &Apache::loncommon::end_page();
 3548:       $r->print (<<ENDREDIR);
 3549: $start_page
 3550: <img align="right" src="$logo" />
 3551: $textline
 3552: <form name="reldt" action="$feedurl" target="loncapaclient">
 3553: </form>
 3554: <br />
 3555: $end_page
 3556: ENDREDIR
 3557:       return OK;
 3558:   } elsif ($env{'form.modifydisp'}) {
 3559:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.modifydisp'});
 3560:       my ($dispchgA,$dispchgB,$markchg,$toggchg) = 
 3561: 	  split(/_/,$env{'form.changes'});
 3562:       &print_display_options($r,$symb,$env{'form.previous'},$dispchgA,
 3563: 			     $dispchgB,$markchg,$toggchg,$feedurl);
 3564:       return OK;
 3565:   } elsif ($env{'form.markondisp'} || $env{'form.markonread'} ||
 3566: 	   $env{'form.allposts'}   || $env{'form.onlyunread'} ||
 3567: 	   $env{'form.onlyunmark'} || $env{'form.toggoff'}    ||
 3568: 	   $env{'form.toggon'}     || $env{'form.markread'}) {
 3569:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.symb'});
 3570:       my %discinfo;
 3571: # ------------------------ Modify setting for read/unread toggle for each post 
 3572:       if ($env{'form.toggoff'}) { $discinfo{$symb.'_readtoggle'}=0; }
 3573:       if ($env{'form.toggon'})  { $discinfo{$symb.'_readtoggle'}=1; }
 3574: # --------- Modify setting for identification of 'NEW' posts in this discussion
 3575:       if ($env{'form.markondisp'}) {
 3576: 	  $discinfo{$symb.'_lastread'} = time;
 3577: 	  $discinfo{$symb.'_markondisp'} = 1;
 3578:       }
 3579:       if ($env{'form.markonread'}) {
 3580: 	  if ( $env{'form.previous'} > 0 ) {
 3581: 	      $discinfo{$symb.'_lastread'} = $env{'form.previous'};
 3582: 	  }
 3583: 	  $discinfo{$symb.'_markondisp'} = 0;
 3584:       }
 3585: # --------------------------------- Modify display setting for this discussion 
 3586:       if ($env{'form.allposts'}) {
 3587: 	  $discinfo{$symb.'_showonlyunread'} = 0;
 3588: 	  $discinfo{$symb.'_showonlyunmark'} = 0;
 3589:       }
 3590:       if ($env{'form.onlyunread'}) { $discinfo{$symb.'_showonlyunread'} = 1;  }
 3591:       if ($env{'form.onlyunmark'}) { $discinfo{$symb.'_showonlyunmark'} = 1;  }
 3592: # ----------------------------------------------------- Mark new posts not NEW 
 3593:       if ($env{'form.markread'})   { $discinfo{$symb.'_lastread'} = time; }
 3594:       &Apache::lonnet::put('nohist_'.$env{'request.course.id'}.'_discuss',
 3595: 			   \%discinfo,$env{'user.domain'},$env{'user.name'});
 3596:       my $previous=$env{'form.previous'};
 3597:       if ($env{'form.markondisp'}) { $previous=undef; }
 3598:       &redirect_back($r,$feedurl,&mt('Changed display status').'<br />',
 3599: 		     '0','0','','',$previous,'','','','','','',$group);
 3600:       return OK;
 3601:   } elsif (($env{'form.hide'}) || ($env{'form.unhide'})) {
 3602: # ----------------------------------------------------------------- Hide/unhide
 3603:       my $entry=$env{'form.hide'}?$env{'form.hide'}:$env{'form.unhide'};
 3604:       my ($symb,$idx)=split(/\:\:\:/,$entry);
 3605:       ($symb,my $feedurl)=&get_feedurl_and_clean_symb($symb);
 3606: 
 3607:       my $crs='/'.$env{'request.course.id'};
 3608:       if ($env{'request.course.sec'}) {
 3609:           $crs.='_'.$env{'request.course.sec'};
 3610:       }
 3611:       $crs=~s/\_/\//g;
 3612:       my $seeid=&Apache::lonnet::allowed('rin',$crs);
 3613: 
 3614:       if ($env{'form.hide'} && !$seeid && !(&editing_allowed($env{'form.hide'},$env{'form.group'}))) {
 3615:           &redirect_back($r,$feedurl,&mt('Deletion not permitted').'<br />',                 '0','0','','',$env{'form.previous'},'','','','',
 3616:                  undef,undef,$group,);
 3617:           return OK;
 3618:       }
 3619: 
 3620:       my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 3621:                           $env{'course.'.$env{'request.course.id'}.'.domain'},
 3622: 		          $env{'course.'.$env{'request.course.id'}.'.num'});
 3623: 
 3624:       my $currenthidden=$contrib{'hidden'};
 3625:       my $currentstudenthidden=$contrib{'studenthidden'};
 3626: 
 3627:       if ($env{'form.hide'}) {
 3628: 	  $currenthidden.='.'.$idx.'.';
 3629: 	  unless ($seeid) {
 3630: 	      $currentstudenthidden.='.'.$idx.'.';
 3631: 	  }
 3632:       } else {
 3633: 	  $currenthidden=~s/\.$idx\.//g;
 3634:       }
 3635:       my %newhash=('hidden' => $currenthidden);
 3636:       if ( ($env{'form.hide'}) && (!$seeid) ) {
 3637: 	  $newhash{'studenthidden'} = $currentstudenthidden;
 3638:       }
 3639:       if ($env{'form.hide'}) {
 3640:           my $changelast = 0;
 3641:           my $newlast;
 3642:           ($changelast,$newlast) = &get_discussion_info($idx,%contrib);
 3643:           if ($changelast) {
 3644:               &Apache::lonnet::put('discussiontimes',{$symb => $newlast},
 3645:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 3646:                      $env{'course.'.$env{'request.course.id'}.'.num'});
 3647:           }
 3648:       }
 3649:       &Apache::lonnet::store(\%newhash,$symb,$env{'request.course.id'},
 3650:                            $env{'course.'.$env{'request.course.id'}.'.domain'},
 3651: 			   $env{'course.'.$env{'request.course.id'}.'.num'});
 3652: 
 3653:       &redirect_back($r,$feedurl,&mt('Changed discussion status').'<br />',
 3654: 		     '0','0','','',$env{'form.previous'},undef,undef,undef,
 3655:                      undef,undef,undef,$group);
 3656:       return OK;
 3657:   } elsif ($env{'form.cmd'}=~/^(threadedoff|threadedon)$/) {
 3658:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.symb'});
 3659:       if ($env{'form.cmd'} eq 'threadedon') {
 3660: 	  &Apache::lonnet::put('environment',{'threadeddiscussion' => 'on'});
 3661: 	  &Apache::lonnet::appenv({'environment.threadeddiscussion' => 'on'});
 3662:       } else {
 3663:  	  &Apache::lonnet::del('environment',['threadeddiscussion']);
 3664: 	  &Apache::lonnet::delenv('environment.threadeddiscussion');
 3665:       }
 3666:       &redirect_back($r,$feedurl,&mt('Changed discussion view mode').'<br />',
 3667: 		     '0','0','','',$env{'form.previous'},undef,undef,undef,
 3668:                      undef,undef,undef,$group);
 3669:       return OK;
 3670:   } elsif ($env{'form.deldisc'}) {
 3671: # --------------------------------------------------------------- Hide for good
 3672:       my ($symb,$idx)=split(/\:\:\:/,$env{'form.deldisc'});
 3673:       ($symb,my $feedurl)=&get_feedurl_and_clean_symb($symb);
 3674:       my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 3675:                           $env{'course.'.$env{'request.course.id'}.'.domain'},
 3676: 		          $env{'course.'.$env{'request.course.id'}.'.num'});
 3677:       my ($changelast,$newlast) = &get_discussion_info($idx,%contrib);
 3678:       if ($changelast) {
 3679:           &Apache::lonnet::put('discussiontimes',{$symb => $newlast},
 3680:                    $env{'course.'.$env{'request.course.id'}.'.domain'},                   $env{'course.'.$env{'request.course.id'}.'.num'});
 3681:       }
 3682:       my %newhash=('deleted' => $contrib{'deleted'}.".$idx.");
 3683:       &Apache::lonnet::store(\%newhash,$symb,$env{'request.course.id'},
 3684: 			   $env{'course.'.$env{'request.course.id'}.'.domain'},
 3685: 			   $env{'course.'.$env{'request.course.id'}.'.num'});
 3686:       &redirect_back($r,$feedurl,&mt('Changed discussion status').'<br />',
 3687: 		     '0','0','','',$env{'form.previous'},undef,undef,undef,
 3688:                      undef,undef,undef,$group);
 3689:       return OK;
 3690:   } elsif ($env{'form.preview'}) {
 3691: # -------------------------------------------------------- User wants a preview
 3692:       &show_preview($r);
 3693:       return OK;
 3694:   } elsif ($env{'form.attach'}) {
 3695: # -------------------------------------------------------- Work on attachments
 3696:       &Apache::loncommon::content_type($r,'text/html');
 3697:       $r->send_http_header;
 3698:       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['subject','comment','addnewattach','delnewattach','timestamp','numoldver','idx','discuss','blog']);
 3699:       my (@currnewattach,@currdelold,@keepold,$toolarge);
 3700:       &process_attachments(\@currnewattach,\@currdelold,\@keepold);
 3701:       if (exists($env{'form.addnewattach.filename'})) {
 3702:           if (length($env{'form.addnewattach'})<=$attachmax{'num'}) {
 3703:               my $subdir = 'feedback/'.$env{'form.timestamp'};
 3704:               my $newattachment=&Apache::lonnet::userfileupload('addnewattach',undef,$subdir);
 3705: 	      push(@currnewattach, $newattachment);
 3706:           } else {
 3707:               $toolarge = '<p><span class="LC_warning">'.&mt('Attachment not included - exceeded permitted length').'</span><br /></p>';
 3708:           }
 3709:       }
 3710:       my $attachmenturls;
 3711:       my ($symb) = &get_feedurl_and_clean_symb($env{'form.attach'});
 3712:       my $idx = $env{'form.idx'};
 3713:       if ($idx) {
 3714:           my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 3715:                          $env{'course.'.$env{'request.course.id'}.'.domain'},
 3716:                          $env{'course.'.$env{'request.course.id'}.'.num'});
 3717:           $attachmenturls = $contrib{$idx.':attachmenturl'};
 3718:       }
 3719:       &modify_attachments($r,\@currnewattach,\@currdelold,$symb,$idx,
 3720: 			  $attachmenturls,$attachmax{'text'},$toolarge);
 3721:       return OK;
 3722:   } elsif ($env{'form.export'}) {
 3723:       &Apache::loncommon::content_type($r,'text/html');
 3724:       $r->send_http_header;
 3725:       my ($symb,$feedurl) = &get_feedurl_and_clean_symb($env{'form.export'});
 3726:       my $mode='board';
 3727:       my $status='OPEN';
 3728:       my $previous=$env{'form.previous'};
 3729:       if ($feedurl =~ /\.(problem|exam|quiz|assess|survey|form|library|task)$/) {
 3730:           $mode='problem';
 3731:           $status=$Apache::inputtags::status[-1];
 3732:       }
 3733:       my $discussion = &list_discussion($mode,$status,$symb); 
 3734:       my $start_page = 
 3735: 	  &Apache::loncommon::start_page('Resource Feedback and Discussion');
 3736:       my $end_page = 
 3737: 	  &Apache::loncommon::end_page();
 3738:       $r->print($start_page.$discussion.$end_page);
 3739:       return OK;
 3740:   } else {
 3741: # ------------------------------------------------------------- Normal feedback
 3742:       my $feedurl=$env{'form.postdata'};
 3743:       $feedurl=~s/^https?\:\/\///;
 3744:       $feedurl=~s/^$ENV{'SERVER_NAME'}//;
 3745:       $feedurl=~s/^$ENV{'HTTP_HOST'}//;
 3746:       $feedurl=~s/\?.+$//;
 3747: 
 3748:       my $symb;
 3749:       if ($env{'form.replydisc'}) {
 3750: 	  $symb=(split(/\:\:\:/,$env{'form.replydisc'}))[0];
 3751:       } elsif ($env{'form.editdisc'}) {
 3752: 	  $symb=(split(/\:\:\:/,$env{'form.editdisc'}))[0];
 3753:       } elsif ($env{'form.origpage'}) {
 3754: 	  $symb=""; 
 3755:       } else {
 3756: 	  $symb=&Apache::lonnet::symbread($feedurl);
 3757:       }
 3758:       unless ($symb) {
 3759: 	  $symb=$env{'form.symb'};
 3760:       }
 3761:       if (defined($symb)) {
 3762:           ($symb,$feedurl)=&get_feedurl_and_clean_symb($symb);
 3763:       } else {
 3764:           # backward compatibility (bulletin boards used to be 'wrapped')
 3765:           &Apache::lonenc::check_decrypt(\$feedurl);
 3766:           &dewrapper(\$feedurl);
 3767:       }
 3768:       my $goahead=1;
 3769:       if ($feedurl=~/\.(problem|exam|quiz|assess|survey|form|task)$/) {
 3770: 	  unless ($symb) { $goahead=0; }
 3771:       }
 3772:       if (!$goahead) {
 3773:           # Ambiguous Problem Resource
 3774: 	  $r->internal_redirect('/adm/ambiguous');
 3775: 	  return OK;
 3776:       }
 3777: # Go ahead with feedback, no ambiguous reference
 3778:       unless (
 3779: 	  (
 3780: 	   ($feedurl=~m:^/res:) && ($feedurl!~m:^/res/adm:)
 3781: 	   ) 
 3782: 	  || 
 3783: 	  ($env{'request.course.id'} && ($feedurl!~m:^/adm:))
 3784: 	  ||
 3785: 	  ($env{'request.course.id'} && ($symb=~/^bulletin\_\_\_/))
 3786: 	  ) {
 3787: 	  &Apache::loncommon::content_type($r,'text/html');
 3788: 	  $r->send_http_header;
 3789: # Unable to give feedback
 3790:           &Apache::lonenc::check_encrypt(\$feedurl);
 3791: 	  &no_redirect_back($r,$feedurl);
 3792: 	  return OK;
 3793:       }
 3794: # --------------------------------------------------- Print login screen header
 3795:       unless ($env{'form.sendit'}) {
 3796:           &Apache::lonenc::check_encrypt(\$feedurl);
 3797: 	  &Apache::loncommon::content_type($r,'text/html');
 3798: 	  $r->send_http_header;
 3799:           if (($env{'form.replydisc'}) || ($env{'form.editdisc'})) {
 3800:               my ($blocked,$blocktext) = 
 3801:                      &Apache::loncommon::blocking_status('boards');
 3802:               if ($blocked) {
 3803:                   $r->print(&blocked_reply_or_edit($blocktext));
 3804:                   return OK;
 3805:               }
 3806:           }
 3807: 	  my $options=&screen_header($feedurl,$symb);
 3808: 	  if ($options) {
 3809: 	      &mail_screen($r,$feedurl,$options,$symb,$attachmax{'text'});
 3810: 	  } else {
 3811: 	      &fail_redirect($r,$feedurl);
 3812: 	  }
 3813: 	  return OK;
 3814:       }
 3815:       
 3816: # Get previous user input
 3817:       my $prevattempts=&Apache::loncommon::get_previous_attempt(
 3818:                                    $symb,$env{'user.name'},$env{'user.domain'},
 3819: 				   $env{'request.course.id'});
 3820: 
 3821: # Get output from resource
 3822:       &Apache::lonenc::check_encrypt(\$feedurl);
 3823:       my $usersaw=&resource_output($feedurl);
 3824: 
 3825: # Get resource answer (need to allow student to view grades for this to work)
 3826:       &Apache::lonnet::appenv({'allowed.vgr'=>'F'});
 3827:       my $usersymb = &Apache::lonenc::check_encrypt($symb);
 3828:       my $useranswer=
 3829:           &Apache::loncommon::get_student_answers(
 3830:               $usersymb,$env{'user.name'},$env{'user.domain'},
 3831:               $env{'request.course.id'});
 3832:       &Apache::lonnet::delenv('allowed.vgr');
 3833: # Get attachments, if any, and not too large
 3834:       my $attachmenturl='';
 3835:       my $toolarge='';
 3836:       if (($env{'form.origpage'}) || ($env{'form.editdisc'}) ||
 3837: 	  ($env{'form.replydisc'})) {
 3838: 	  my ($symb,$idx);
 3839: 	  if ($env{'form.replydisc'}) {
 3840: 	      ($symb,$idx)=split(/\:\:\:/,$env{'form.replydisc'});
 3841: 	  } elsif ($env{'form.editdisc'}) {
 3842: 	      ($symb,$idx)=split(/\:\:\:/,$env{'form.editdisc'});
 3843: 	  } elsif ($env{'form.origpage'}) {
 3844: 	      $symb = $env{'form.symb'};
 3845: 	  }
 3846: 	  &Apache::lonenc::check_decrypt(\$symb);
 3847: 	  my @currnewattach = ();
 3848: 	  my @deloldattach = ();
 3849: 	  my @keepold = ();
 3850: 	  &process_attachments(\@currnewattach,\@deloldattach,\@keepold);
 3851: 	  $symb=~s|(bulletin___\d+___)adm/wrapper/|$1|;
 3852: 	  $attachmenturl=&construct_attachmenturl(\@currnewattach,\@keepold,$symb,$idx);
 3853:       } elsif ($env{'form.attachment.filename'}) {
 3854: 	  if (length($env{'form.attachment'})<=$attachmax{'num'}) {
 3855:               my $now = time;
 3856:               my $subdir = 'feedback/'.$now;
 3857: 	      $attachmenturl=&Apache::lonnet::userfileupload('attachment',undef,$subdir);
 3858: 	  } else {
 3859:               $toolarge = '<p><span class="LC_warning">'.&mt('Attachment not included - exceeded permitted length').'</span><br /></p>';
 3860:           }
 3861:       }
 3862: # Filter HTML out of message (could be nasty)
 3863:       my $message=&clear_out_html($env{'form.comment'});
 3864: 
 3865: # Assemble email
 3866:       my ($email,$citations)=&assemble_email($message,$prevattempts,
 3867: 					     $usersaw,$useranswer);
 3868:  
 3869: # Who gets this?
 3870:       my ($typestyle,%to) = &Apache::lonmsg::decide_receiver($feedurl);
 3871: 
 3872: # Actually send mail
 3873:       my ($status,$numsent)=&send_msg(&clear_out_html($env{'form.subject'},
 3874: 						      undef,1),
 3875: 				      $feedurl,$email,$citations,
 3876: 				      $attachmenturl,$usersymb,%to);
 3877: 
 3878: # Discussion? Store that.
 3879:       my $numpost=0;
 3880:       if (  ($env{'form.discuss'} ne ''
 3881: 	     && $env{'form.discuss'} !~ /^(?:author|question|course|policy)/)
 3882: 	   || $env{'form.anondiscuss'} ne '') {
 3883: 	  my $subject = &clear_out_html($env{'form.subject'},undef,1);
 3884: 	  my $anonmode=($env{'form.discuss'} eq 'anon' || $env{'form.anondiscuss'} );
 3885: 	  $typestyle.=&adddiscuss($symb,$message,$anonmode,$attachmenturl,
 3886: 				  $subject);
 3887: 	  $numpost++;
 3888:       }
 3889: 
 3890: # Add to blog?
 3891: 
 3892:       my $blog='';
 3893:       if ($env{'form.blog'}) {
 3894: 	  my $subject = &clear_out_html($env{'form.subject'},undef,1);
 3895: 	  $status.=&Apache::lonrss::addentry($env{'user.name'},
 3896: 				    $env{'user.domain'},
 3897: 				    'CourseBlog_'.$env{'request.course.id'},
 3898: 				    $subject,$message,$feedurl,'public');
 3899:           if (&Apache::loncommon::course_type() eq 'Community') {
 3900:               $blog='<br />'.&mt('Added to my community blog').'<br />';
 3901:           } else {
 3902: 	      $blog='<br />'.&mt('Added to my course blog').'<br />';
 3903:           }
 3904:       }
 3905: 	  
 3906: # Receipt screen and redirect back to where came from
 3907:       &redirect_back($r,$feedurl,$typestyle,$numsent,$numpost,$blog,$status,$env{'form.previous'},undef,undef,undef,undef,undef,undef,$group,$toolarge);
 3908:   }
 3909:   return OK;
 3910: }
 3911: 
 3912: sub blocked_reply_or_edit {
 3913:     my ($blocktext) = @_;
 3914:     return 
 3915:       &Apache::loncommon::start_page('Resource Feedback and Discussion').
 3916:       $blocktext.'<br /><br /><a href="javascript:history.go(-1)">'.
 3917:       &mt('Back to previous page').
 3918:       &Apache::loncommon::end_page();
 3919: } 
 3920: 
 3921: sub wrap_symb {
 3922:     my ($ressymb)=@_;
 3923:     if ($ressymb =~ /bulletin___\d+___/) {
 3924:         unless ($ressymb =~ m|bulletin___\d+___adm/wrapper|) {
 3925:             $ressymb=~s|(bulletin___\d+___)|$1adm/wrapper|;
 3926:         }
 3927:     }
 3928:     return $ressymb;
 3929: }
 3930: sub dewrapper {
 3931:     my ($feedurl)=@_;
 3932:     if ($$feedurl=~m|^/adm/wrapper/adm/.*/bulletinboard$|) {
 3933:         $$feedurl=~s|^/adm/wrapper||;
 3934:     }
 3935: }
 3936: 
 3937: sub get_feedurl {
 3938:     my ($symb)=@_;
 3939:     my ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);
 3940:     my $feedurl = &Apache::lonnet::clutter($url);
 3941:     &dewrapper(\$feedurl);
 3942:     return $feedurl;
 3943: }
 3944: 
 3945: sub get_feedurl_and_clean_symb {
 3946:     my ($symb)=@_;
 3947:     &Apache::lonenc::check_decrypt(\$symb);
 3948: # backward compatibility (bulletin boards used to be 'wrapped')
 3949:     unless ($symb =~ m|bulletin___\d+___adm/wrapper|) {
 3950: 	$symb=~s|(bulletin___\d+___)|$1adm/wrapper|;
 3951:     }
 3952:     my $feedurl = &get_feedurl($symb);
 3953:     return ($symb,$feedurl);
 3954: }
 3955: 
 3956: sub editing_allowed {
 3957:     my ($postid,$group) = @_;
 3958:     $postid = &unescape($postid);
 3959:     my $can_edit = 0;
 3960:     if ($group ne '') {
 3961:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3962:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3963:         if ($postid =~ m|^bulletin___\d+___adm/wrapper(/adm/\Q$cdom\E/\Q$cnum\E/\d+/bulletinboard)|) {
 3964:             if (&check_group_priv($group,'egp') eq 'ok') {
 3965:                 $can_edit = 1;
 3966:             }
 3967:             return $can_edit;
 3968:         }     
 3969:     } 
 3970:     my $cid = $env{'request.course.id'};
 3971:     my $role = (split(/\./,$env{'request.role'}))[0];
 3972:     my $section = $env{'request.course.sec'};
 3973:     my $allow_editing_config = 
 3974: 	$env{'course.'.$cid.'.allow_discussion_post_editing'};
 3975:     if ($allow_editing_config =~ m/^\s*yes\s*$/i) {
 3976:         $can_edit = 1;
 3977:     } else {
 3978: 	foreach my $editor (split(/,/,$allow_editing_config)) {
 3979: 	    my ($editor_role,$editor_sec) = split(/:/,$editor);
 3980: 	    if ($editor_role eq $role
 3981: 		&& defined($editor_sec)
 3982: 		&& defined($section)
 3983: 		&& $editor_sec eq $section) {
 3984: 		$can_edit = 1;
 3985: 		last;
 3986: 	    }
 3987: 	    if ($editor_role eq $role
 3988: 		&& !defined($editor_sec)) {
 3989: 		$can_edit = 1;
 3990: 	    }
 3991: 	}
 3992:     }
 3993:     return $can_edit;
 3994: }
 3995: 
 3996: sub check_group_priv {
 3997:     my ($group,$grp_priv) = @_;
 3998:     foreach my $priv ('mdg','vcg') {
 3999:         my $checkcourse = $env{'request.course.id'}.
 4000:             ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'');
 4001:         if (&Apache::lonnet::allowed($priv,$checkcourse)) {
 4002:             return 'ok';
 4003:         }
 4004:     }
 4005:     if ($grp_priv && $group ne '') {
 4006:         if (&Apache::lonnet::allowed($grp_priv,$env{'request.course.id'}.'/'.$group)) {
 4007:             return 'ok';
 4008:         }
 4009:     }
 4010:     return '';
 4011: }
 4012: 
 4013: sub group_args { 
 4014:     my ($group) = @_;
 4015:     if ($group eq '') { return ''; }
 4016:     my $extra_args = '&amp;group='.$group;
 4017:     if (exists($env{'form.ref'})) {
 4018:         $extra_args .= '&amp;ref='.$env{'form.ref'};
 4019:     }
 4020:     return $extra_args;
 4021: }
 4022: 
 4023: sub get_resource_title {
 4024:     my ($symb,$feedurl) = @_;
 4025:     my ($restitle,$plainurl);
 4026:     if (defined($symb)) {
 4027:         my $plain_symb = &Apache::lonenc::check_decrypt($symb);
 4028:         $restitle = &Apache::lonnet::gettitle($plain_symb);
 4029:     }
 4030:     if (defined($feedurl)) {
 4031:         $plainurl = &Apache::lonenc::check_decrypt($feedurl);
 4032:     }
 4033:     if (!defined($restitle)) {
 4034:         if (defined($feedurl)) {
 4035:             $restitle = &Apache::lonnet::gettitle($plainurl);
 4036:         }
 4037:     }
 4038:     if ($plainurl ne $feedurl) {
 4039:         my ($plain_filename) = ($plainurl =~ m-/([^/]+)$-);
 4040:         if ($plain_filename eq $restitle) {
 4041:             $restitle = &mt('Untitled resource');
 4042:         }
 4043:     }
 4044:     if ($restitle eq '') {
 4045:         $restitle = &mt('Untitled resource');
 4046:     }
 4047:     return $restitle;
 4048: }
 4049: 
 4050: 1;
 4051: __END__
 4052: 
 4053: 
 4054: =pod
 4055: 
 4056: =head1 NAME
 4057: 
 4058: Apache::lonfeedback.pm
 4059: 
 4060: =head1 SYNOPSIS
 4061: 
 4062: Handles feedback from students to instructors and system administrators.
 4063: 
 4064: Provides a screenshot of the current resource, as well as previous attempts if the resource was a homework.
 4065: 
 4066: Used by lonmsg.pm.
 4067: 
 4068: This is part of the LearningOnline Network with CAPA project
 4069: described at http://www.lon-capa.org.
 4070: 
 4071: =head1 OVERVIEW
 4072: 
 4073: None
 4074: 
 4075: =head1 SUBROUTINES
 4076: 
 4077: =over
 4078: 
 4079: =item discussion_open()
 4080: 
 4081: =item discussion_visible()
 4082: 
 4083: =item list_discussion()
 4084: 
 4085: =item send_feedback_link()
 4086: 
 4087: =item send_message_link()
 4088: 
 4089: =item action_links_bar()
 4090: 
 4091: =item postingform_display()
 4092: 
 4093: =item build_posting_display
 4094: 
 4095: =item filter_regexp()
 4096: 
 4097: =item get_post_contents()
 4098: 
 4099: =item replicate_attachments()
 4100: 
 4101: =item mail_screen()
 4102: 
 4103: =item print_display_options()
 4104: 
 4105: =item print_sortfilter_options()
 4106: 
 4107: =item print_showposters()
 4108: 
 4109: =item get_post_versions()
 4110: 
 4111: =item get_post_attachments()
 4112: 
 4113: =item fail_redirect()
 4114: 
 4115: =item redirect_back()
 4116: 
 4117: =item no_redirect_back()
 4118: 
 4119: =item screen_header()
 4120: 
 4121: =item resource_output()
 4122: 
 4123: =item clear_out_html()
 4124: 
 4125: =item assemble_email()
 4126: 
 4127: =item feedback_available()
 4128: 
 4129: =item send_msg()
 4130: 
 4131: =item adddiscuss()
 4132: 
 4133: =item get_discussion_info()
 4134: 
 4135: =item show_preview()
 4136: 
 4137: =item newline_to_br()
 4138: 
 4139: =item generate_preview_button()
 4140: 
 4141: =item modify_attachments()
 4142: 
 4143: =item process_attachments()
 4144: 
 4145: =item generate_attachments_button()
 4146: 
 4147: =item extract_attachments()
 4148: 
 4149: =item construct_attachmenturl()
 4150: 
 4151: =item add_blog_checkbox()
 4152: 
 4153: =item has_discussion()
 4154: 
 4155: =item sort_filter_names()
 4156: 
 4157: =item handler()
 4158: 
 4159: =item blocked_reply_or_edit()
 4160: 
 4161: =item wrap_symb()
 4162: 
 4163: =item dewrapper()
 4164: 
 4165: =item get_feedurl()
 4166: 
 4167: =item get_feedurl_and_clean_symb()
 4168: 
 4169: =item editing_allowed()
 4170: 
 4171: =item check_group_priv()
 4172: 
 4173: =item group_args()
 4174: 
 4175: =item get_resource_title()
 4176: 
 4177: =back
 4178: 
 4179: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>