File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.207: download - view: text, annotated - select for diffs
Fri Jun 30 04:49:03 2006 UTC (17 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: version_2_1_99_0, HEAD
- BUG#4895, non-anon bulletin borad posting was broken

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

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