File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.222: download - view: text, annotated - select for diffs
Wed Nov 29 04:25:23 2006 UTC (17 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
bug 4772. Duplicate discussion control bar at the end of the display of discussions to reduce scrolling.

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

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