File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.273.4.10: download - view: text, annotated - select for diffs
Tue Sep 21 04:56:15 2010 UTC (13 years, 8 months ago) by raeburn
Branches: version_2_9_X
Diff to branchpoint 1.273: preferred, unified
- Part of 1.294 omitted in backport (in 1.273.4.9).

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

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