File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.187: download - view: text, annotated - select for diffs
Tue Mar 21 18:37:25 2006 UTC (18 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- start_page
-elimintate Continue links in favor of the auto-generated ones

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

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