File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.315: download - view: text, annotated - select for diffs
Tue Jan 3 18:21:58 2012 UTC (12 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Cleanup

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

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