File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.215: download - view: text, annotated - select for diffs
Mon Aug 14 21:44:14 2006 UTC (17 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: version_2_1_99_3, HEAD
- xhmtl

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

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