File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.180: download - view: text, annotated - select for diffs
Thu Feb 9 22:11:54 2006 UTC (18 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Bug 4651.  Specify which roles can edit their own discussion posts.

    1: # The LearningOnline Network
    2: # Feedback
    3: #
    4: # $Id: lonfeedback.pm,v 1.180 2006/02/09 22:11:54 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonfeedback;
   31: 
   32: use strict;
   33: use Apache::Constants qw(:common);
   34: use Apache::lonmsg();
   35: use Apache::loncommon();
   36: use Apache::lontexconvert();
   37: use Apache::lonlocal; # must not have ()
   38: use Apache::lonnet;
   39: use Apache::lonhtmlcommon();
   40: use Apache::lonnavmaps;
   41: use Apache::lonenc();
   42: use Apache::lonrss();
   43: use HTML::LCParser();
   44: use Apache::lonspeller();
   45: use 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></body></html>');
 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:   my $bodytag=&Apache::loncommon::bodytag('Resource Feedback and Discussion',
 1307:                                           '','onLoad="window.focus();setposttype();"');
 1308:   my $title=&Apache::lonnet::gettitle($feedurl);
 1309:   if (!$title) { $title = $feedurl; }
 1310:   my $quote='';
 1311:   my $subject = '';
 1312:   my $comment = '';
 1313:   my $prevtag = '';
 1314:   my $parentmsg = '';
 1315:   my ($symb,$idx,$attachmenturls);
 1316:   my $numoldver = 0;
 1317:   my $attachmsg = '';
 1318:   my $newattachmsg = '';
 1319:   my @currnewattach = ();
 1320:   my @currdelold = ();
 1321:   my @keepold = ();
 1322:   my %attachments = ();
 1323:   my %currattach = ();
 1324:   my $attachnum = 0;
 1325:   my $anonchk = (<<END);
 1326:   function anonchk() {
 1327:      if (document.mailform.anondiscuss.checked == true) {
 1328:           document.attachment.anondiscuss.value = '1'
 1329:      }
 1330:      if (document.mailform.discuss.checked == true) {
 1331:           document.attachment.discuss.value = '1'
 1332:      }
 1333:      return
 1334:    }
 1335: END
 1336:   my $anonscript;
 1337:   if (exists($env{'form.origpage'})) {
 1338:       $anonscript = (<<END);
 1339:   function setposttype() {
 1340:       var anondisc = $env{'form.anondiscuss'};
 1341:       var disc = $env{'form.discuss'};
 1342:       if (anondisc == 1) {
 1343:           document.mailform.anondiscuss.checked = true
 1344:       }
 1345:       if (disc == 1) {
 1346:           document.mailform.discuss.checked = true
 1347:       }
 1348:       return
 1349:   }
 1350: END
 1351:   } else {
 1352:       $anonscript = (<<END);
 1353:   function setposttype() {
 1354:       return
 1355:   }
 1356: END
 1357:   }
 1358:   if (($env{'form.replydisc'}) || ($env{'form.editdisc'})) {
 1359:       if ($env{'form.replydisc'}) {
 1360:           ($symb,$idx)=split(/\:\:\:/,$env{'form.replydisc'});
 1361:       } else {
 1362:           ($symb,$idx)=split(/\:\:\:/,$env{'form.editdisc'});
 1363:       }
 1364:       my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 1365: 					   $env{'course.'.$env{'request.course.id'}.'.domain'},
 1366: 					   $env{'course.'.$env{'request.course.id'}.'.num'});
 1367:       unless (($contrib{'hidden'}=~/\.$idx\./) || ($contrib{'deleted'}=~/\.$idx\./)) {
 1368:           if ($contrib{$idx.':history'}) {
 1369:               if ($contrib{$idx.':history'} =~ /:/) {
 1370:                   my @oldversions = split/:/,$contrib{$idx.':history'};
 1371:                   $numoldver = @oldversions;
 1372:               } else {
 1373:                   $numoldver = 1;
 1374:               }
 1375:           }
 1376:           if ($env{'form.replydisc'}) {
 1377:               if ($contrib{$idx.':history'}) {
 1378:                   if ($contrib{$idx.':history'} =~ /:/) {
 1379:                       my @oldversions = split/:/,$contrib{$idx.':history'};
 1380:                       $numoldver = @oldversions;
 1381:                   } else {
 1382:                       $numoldver = 1;
 1383:                   }
 1384:               }
 1385:               my $message;
 1386:               if ($idx > 0) {
 1387:                   my %msgversions = ();
 1388:                   &get_post_versions(\%msgversions,$contrib{$idx.':message'},0,$numoldver);
 1389:                   $message = $msgversions{$numoldver};
 1390:               }
 1391: 	      &newline_to_br(\$message);
 1392: 	      $quote='<blockquote>'.&Apache::lontexconvert::msgtexconverted($message).'</blockquote>';
 1393:               if ($idx > 0) {
 1394:                   my %subversions = ();
 1395:                   &get_post_versions(\%subversions,$contrib{$idx.':subject'},1,$numoldver);
 1396:                   $subject = 'Re: '.$subversions{$numoldver};
 1397:               }
 1398:               $subject = &HTML::Entities::encode($subject,'<>&"');
 1399:           } else {
 1400:               $attachmenturls = $contrib{$idx.':attachmenturl'};
 1401:               if ($idx > 0) {
 1402:                   my %msgversions = ();
 1403:                   &get_post_versions(\%msgversions,$contrib{$idx.':message'},0,$numoldver);
 1404:                   $comment = $msgversions{$numoldver};
 1405:                   my %subversions = ();
 1406:                   &get_post_versions(\%subversions,$contrib{$idx.':subject'},0,$numoldver);
 1407:                   $subject = $subversions{$numoldver}; 
 1408:               }
 1409:               if (defined($contrib{$idx.':replyto'})) {
 1410:                   $parentmsg = $contrib{$idx.':replyto'};
 1411:               }
 1412:               unless (exists($env{'form.origpage'})) {
 1413:                   my $anonflag = 0;
 1414:                   if ($contrib{$idx.':anonymous'}) {
 1415:                       $anonflag = 1;
 1416:                   }
 1417:                   $anonscript = (<<END);
 1418:   function setposttype () {
 1419:       var currtype = $anonflag
 1420:       if (currtype == 1) {
 1421:           document.mailform.elements.discuss.checked = false
 1422:           document.mailform.elements.anondiscuss.checked = true
 1423:       }
 1424:       if (currtype == 0) {
 1425:           document.mailform.elements.anondiscuss.checked = false
 1426:           document.mailform.elements.discuss.checked = true
 1427:       }
 1428:       return
 1429:   }
 1430: END
 1431:               }
 1432:           }
 1433:       }
 1434:       if ($env{'form.previous'}) {
 1435:           $prevtag = '<input type="hidden" name="previous" value="'.$env{'form.previous'}.'" />';
 1436:       }
 1437:   }
 1438: 
 1439:   if ($env{'form.origpage'}) {
 1440:       $subject = &Apache::lonnet::unescape($env{'form.subject'});
 1441:       $comment = &Apache::lonnet::unescape($env{'form.comment'});
 1442:       &process_attachments(\@currnewattach,\@currdelold,\@keepold);
 1443:   }
 1444:   my $latexHelp=&Apache::loncommon::helpLatexCheatsheet();
 1445:   my $htmlheader=&Apache::lonhtmlcommon::htmlareaheaders();
 1446:   my $send=&mt('Send');
 1447:   my $html=&Apache::lonxml::xmlbegin();
 1448:   $r->print(<<END);
 1449: $html
 1450: <head>
 1451: <title>The LearningOnline Network with CAPA</title>
 1452: <meta http-equiv="pragma" content="no-cache"></meta>
 1453: $htmlheader
 1454: <script type="text/javascript">
 1455: //<!--
 1456:     function gosubmit() {
 1457:         var rec=0;
 1458:         if (typeof(document.mailform.elements.author)!="undefined") {
 1459:           if (document.mailform.elements.author.checked) {
 1460:              rec=1;
 1461:           } 
 1462:         }
 1463:         if (typeof(document.mailform.elements.question)!="undefined") {
 1464:           if (document.mailform.elements.question.checked) {
 1465:              rec=1;
 1466:           } 
 1467:         }
 1468:         if (typeof(document.mailform.elements.course)!="undefined") {
 1469:           if (document.mailform.elements.course.checked) {
 1470:              rec=1;
 1471:           } 
 1472:         }
 1473:         if (typeof(document.mailform.elements.policy)!="undefined") {
 1474:           if (document.mailform.elements.policy.checked) {
 1475:              rec=1;
 1476:           } 
 1477:         }
 1478:         if (typeof(document.mailform.elements.discuss)!="undefined") {
 1479:           if (document.mailform.elements.discuss.checked) {
 1480:              rec=1;
 1481:           } 
 1482:         }
 1483:         if (typeof(document.mailform.elements.anondiscuss)!="undefined") {
 1484:           if (document.mailform.elements.anondiscuss.checked) {
 1485:              rec=1;
 1486:           } 
 1487:         }
 1488:         if (typeof(document.mailform.elements.blog)!="undefined") {
 1489:           if (document.mailform.elements.blog.checked) {
 1490:              rec=1;
 1491:           } 
 1492:         }
 1493: 
 1494:         if (rec) {
 1495:             if (typeof(document.mailform.onsubmit)=='function') {
 1496: 		document.mailform.onsubmit();
 1497: 	    }
 1498: 	    document.mailform.submit();
 1499:         } else {
 1500:             alert('Please check a feedback type.');
 1501: 	}
 1502:     }
 1503:     $anonchk
 1504:     $anonscript
 1505: //-->
 1506: </script>
 1507: </head>
 1508: $bodytag
 1509: <h2><tt>$title</tt></h2>
 1510: <form action="/adm/feedback" method="post" name="mailform"
 1511: enctype="multipart/form-data">
 1512: $prevtag
 1513: <input type="hidden" name="postdata" value="$feedurl" />
 1514: END
 1515:   if ($env{'form.replydisc'}) {
 1516:       $r->print(<<END);
 1517: <input type="hidden" name="replydisc" value="$env{'form.replydisc'}" />
 1518: END
 1519:   } elsif ($env{'form.editdisc'}) {
 1520:      $r->print(<<END);
 1521: <input type="hidden" name="editdisc" value ="$env{'form.editdisc'}" />
 1522: <input type="hidden" name="parentmsg" value ="$parentmsg" />
 1523: END
 1524:   }
 1525:   $r->print(<<END);
 1526: Please check at least one of the following feedback types:
 1527: $options<hr />
 1528: $quote
 1529: <p>My question/comment/feedback:</p>
 1530: <p>
 1531: $latexHelp
 1532: Title: <input type="text" name="subject" size="30" value="$subject" /></p>
 1533: <p>
 1534: <textarea name="comment" id="comment" cols="60" rows="10" wrap="hard">$comment
 1535: </textarea></p>
 1536: <p>
 1537: END
 1538:     if ( ($env{'form.editdisc'}) || ($env{'form.replydisc'}) ) {
 1539:         if ($env{'form.origpage'}) {
 1540:             foreach (@currnewattach) {
 1541:                 $r->print('<input type="hidden" name="currnewattach" value="'.$_.'" />'."\n");
 1542:             }
 1543:             foreach (@currdelold) {
 1544:                 $r->print('<input type="hidden" name="deloldattach" value="'.$_.'" />'."\n");
 1545:             }
 1546:         }
 1547:         if ($env{'form.editdisc'}) {
 1548:             if ($attachmenturls) {
 1549:                 &extract_attachments($attachmenturls,$idx,$numoldver,\$attachmsg,\%attachments,\%currattach,\@currdelold);
 1550:                 $attachnum = scalar(keys %currattach);
 1551:                 foreach (keys %currattach) {
 1552:                     $r->print('<input type="hidden" name="keepold" value="'.$_.'" />'."\n");
 1553:                 }
 1554:             }
 1555:         }
 1556:     } else {
 1557:         $r->print(<<END);
 1558: Attachment (128 KB max size): <input type="file" name="attachment" />
 1559: </p>
 1560: END
 1561:     }
 1562:     $r->print(<<END);
 1563: <p>
 1564: <input type="hidden" name="sendit" value="1" />
 1565: <input type="button" value="$send" onClick='gosubmit();' />
 1566: </p>
 1567: </form>
 1568: END
 1569:     if ($env{'form.editdisc'} || $env{'form.replydisc'}) {
 1570:         my $now = time;
 1571:         my $ressymb = $symb;
 1572:         my $postidx = '';
 1573:         if ($env{'form.editdisc'}) {
 1574:             $postidx = $idx;
 1575:         }
 1576:         if (@currnewattach > 0) {
 1577:             $attachnum += @currnewattach;
 1578:         }
 1579:         $r->print(&generate_attachments_button($postidx,$attachnum,$ressymb,$now,\@currnewattach,\@currdelold,$numoldver));
 1580:         if ($attachnum > 0) {
 1581:             if (@currnewattach > 0) {
 1582:                 $newattachmsg .= '<b>New attachments</b><br />';
 1583:                 if (@currnewattach > 1) {
 1584:                     $newattachmsg .= '<ol>';
 1585:                     foreach my $item (@currnewattach) {
 1586:                         $item =~ m#.*/([^/]+)$#;
 1587:                         $newattachmsg .= '<li><a href="'.$item.'">'.$1.'</a></li>'."\n";
 1588:                     }
 1589:                     $newattachmsg .= '</ol>'."\n";
 1590:                 } else {
 1591:                     $currnewattach[0] =~ m#.*/([^/]+)$#;
 1592:                     $newattachmsg .= '<a href="'.$currnewattach[0].'">'.$1.'</a><br />'."\n";
 1593:                 }
 1594:             }
 1595:             if ($attachmsg) {
 1596:                 $r->print("<b>Retained attachments</b>:$attachmsg<br />\n");
 1597:             }
 1598:             if ($newattachmsg) {
 1599:                 $r->print("$newattachmsg<br />");
 1600:             }
 1601:         }
 1602:     }
 1603:     $r->print(&generate_preview_button().
 1604:               &Apache::lonhtmlcommon::htmlareaselectactive('comment').
 1605:               '</body></html>');
 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:     my $bodytag=&Apache::loncommon::bodytag('Discussion options',
 1617:                                           '','');
 1618: 
 1619:     my %lt = &Apache::lonlocal::texthash(
 1620:         'dido' => 'Discussion display options',
 1621:         'pref' => 'Display Preference',
 1622:         'curr' => 'Current setting ',
 1623:         'actn' => 'Action',
 1624:         'deff' => 'Default for all discussions',
 1625:         'prca' => 'Preferences can be set for this discussion that determine ....',
 1626:         'whpo' => 'Which posts are displayed when you display this bulletin board or resource, and',
 1627:         'unwh' => 'Under what circumstances posts are identified as "NEW", and',
 1628:         'wipa' => 'Whether individual posts can be marked as read/unread',
 1629:         'allposts' => 'All posts',
 1630:         'unread' => 'New posts only',
 1631:         'unmark' => 'Posts not marked read',
 1632:         'ondisp' => 'Once displayed',
 1633:         'onmark' => 'Once marked not NEW ',
 1634:         'toggon' => 'Shown',
 1635:         'toggoff' => 'Not shown',
 1636:         'disa' => 'Posts displayed?',
 1637:         'npmr' => 'New posts cease to be identified as "NEW"?',
 1638:         'dotm' => 'Option to mark each post as read/unread?',  
 1639:         'chgt' => 'Change to ',
 1640:         'mkdf' => 'Set to ',
 1641:         'yhni' => 'You have not indicated that you wish to change any of the discussion settings',
 1642:         'ywbr' => 'You will be returned to the previous page if you click OK.'
 1643:     );
 1644: 
 1645:     my $dispchangeA = $lt{'unread'};
 1646:     my $dispchangeB = $lt{'unmark'};
 1647:     my $markchange = $lt{'ondisp'};
 1648:     my $toggchange = $lt{'toggon'};
 1649:     my $currdisp = $lt{'allposts'};
 1650:     my $currmark = $lt{'onmark'};
 1651:     my $discdisp = 'allposts';
 1652:     my $discmark = 'onmark';
 1653:     my $currtogg = $lt{'toggoff'};
 1654:     my $disctogg = 'toggoff';
 1655:                                                                                       
 1656:     if ($dispchgA eq 'allposts') {
 1657:         $dispchangeA = $lt{'allposts'};
 1658:         $currdisp = $lt{'unread'};
 1659:         $discdisp = 'unread';
 1660:     }
 1661: 
 1662:     if ($markchg eq 'markonread') {
 1663:         $markchange = $lt{'onmark'};
 1664:         $currmark = $lt{'ondisp'};
 1665:         $discmark = 'ondisp';
 1666:     }
 1667: 
 1668:     if ($dispchgB eq 'onlyunread') {
 1669:         $dispchangeB = $lt{'unread'};
 1670:         $currdisp = $lt{'unmark'};
 1671:         $discdisp = 'unmark';
 1672:     }
 1673:     if ($toggchg eq 'toggoff') {
 1674:         $toggchange = $lt{'toggoff'};
 1675:         $currtogg = $lt{'toggon'};
 1676:         $disctogg = 'toggon';
 1677:     }
 1678:     my $html=&Apache::lonxml::xmlbegin();
 1679:     $r->print(<<END);
 1680: $html
 1681: <head>
 1682: <title>$lt{'dido'}</title>
 1683: <meta http-equiv="pragma" content="no-cache" />
 1684: <script>
 1685: function discdispChk(caller) {
 1686:     var disctogg = '$toggchg'
 1687:     if (caller == 0) {
 1688:         if (document.modifydisp.discdisp[0].checked == true) {
 1689:             if (document.modifydisp.discdisp[1].checked == true) {
 1690:                 document.modifydisp.discdisp[1].checked = false
 1691:             }
 1692:         }
 1693:     }
 1694:     if (caller == 1) {
 1695:         if (document.modifydisp.discdisp[1].checked == true) {
 1696:             if (document.modifydisp.discdisp[0].checked == true) {
 1697:                 document.modifydisp.discdisp[0].checked = false
 1698:             }
 1699:             if (disctogg == 'toggon') {
 1700:                 document.modifydisp.disctogg.checked = true
 1701:             }
 1702:             if (disctogg == 'toggoff') {
 1703:                 document.modifydisp.disctogg.checked = false
 1704:             }
 1705:         }
 1706:     }
 1707:     if (caller == 2) {
 1708:         var dispchgB = '$dispchgB'
 1709:         if (disctogg == 'toggoff') {
 1710:             if (document.modifydisp.disctogg.checked == true) {
 1711:                 if (dispchgB == 'onlyunmark') {
 1712:                     document.modifydisp.discdisp[1].checked = false
 1713:                 }
 1714:             }
 1715:         }
 1716:     }  
 1717: }
 1718: 
 1719: function setDisp() {
 1720:     var prev = "$previous"
 1721:     var chktotal = 0
 1722:     if (document.modifydisp.discdisp[0].checked == true) {
 1723:         document.modifydisp.$dispchgA.value = "$symb"
 1724:         chktotal ++
 1725:     }
 1726:     if (document.modifydisp.discdisp[1].checked == true) {
 1727:         document.modifydisp.$dispchgB.value = "$symb"
 1728:         chktotal ++
 1729:     }
 1730:     if (document.modifydisp.discmark.checked == true) {
 1731:         document.modifydisp.$markchg.value = "$symb"
 1732:         chktotal ++
 1733:     }
 1734:     if (document.modifydisp.disctogg.checked == true) {
 1735:         document.modifydisp.$toggchg.value = "$symb"
 1736:         chktotal ++
 1737:     }
 1738:     if (chktotal > 0) { 
 1739:         document.modifydisp.submit()
 1740:     } else {
 1741:         if(confirm("$lt{'yhni'}. \\n$lt{'ywbr'}"))      {
 1742:             if (prev > 0) {
 1743:                 location.href = "$feedurl?previous=$previous"
 1744:             } else {
 1745:                 location.href = "$feedurl"
 1746:             }
 1747:         }
 1748:     }
 1749: }
 1750: </script>
 1751: </head>
 1752: $bodytag
 1753: <form name="modifydisp" method="post" action="/adm/feedback">
 1754: $lt{'sdpf'}<br/> $lt{'prca'}  <ol><li>$lt{'whpo'}</li><li>$lt{'unwh'}</li><li>$lt{'wipa'}</li></ol>
 1755: <br />
 1756: <table border="0" cellpadding="0" cellspacing="0">
 1757:  <tr>
 1758:   <td width="100%" bgcolor="#000000">
 1759:    <table width="100%" border="0" cellpadding="1" cellspacing="0">
 1760:     <tr>
 1761:      <td width="100%" bgcolor="#000000">
 1762:       <table border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
 1763:        <tr bgcolor="$tabcolor">
 1764:         <td><b>$lt{'pref'}</b></td>
 1765:         <td><b>$lt{'curr'}</b></td>
 1766:         <td><b>$lt{'actn'}?</b></td>
 1767:        </tr>
 1768:        <tr bgcolor="#dddddd">
 1769:        <td>$lt{'disa'}</td>
 1770:        <td>$lt{$discdisp}</td>
 1771:        <td><label><input type="checkbox" name="discdisp" onClick="discdispChk('0')" />&nbsp;$lt{'chgt'} "$dispchangeA"</label>
 1772:            <br />
 1773:            <label><input type="checkbox" name="discdisp" onClick="discdispChk('1')" />&nbsp;$lt{'chgt'} "$dispchangeB"</label>
 1774:        </td>
 1775:       </tr><tr bgcolor="#eeeeee">
 1776:        <td>$lt{'npmr'}</td>
 1777:        <td>$lt{$discmark}</td>
 1778:        <td><label><input type="checkbox" name="discmark" />$lt{'chgt'} "$markchange"</label></td>
 1779:       </tr><tr bgcolor="#dddddd">
 1780:        <td>$lt{'dotm'}</td>
 1781:        <td>$lt{$disctogg}</td>
 1782:        <td><label><input type="checkbox" name="disctogg" onClick="discdispChk('2')" />$lt{'chgt'} "$toggchange"</label></td>
 1783:       </tr>
 1784:      </table>
 1785:     </td>
 1786:    </tr>
 1787:   </table>
 1788:  </td>
 1789: </tr>
 1790: </table>
 1791: <br />
 1792: <br />
 1793: <input type="hidden" name="symb" value="$symb" />
 1794: <input type="hidden" name="previous" value="$previous" />
 1795: <input type="hidden" name="$dispchgA" value=""/>
 1796: <input type="hidden" name="$dispchgB" value=""/>
 1797: <input type="hidden" name="$markchg" value=""/>
 1798: <input type="hidden" name="$toggchg" value="" />
 1799: <input type="button" name="sub" value="Store Changes" onClick="javascript:setDisp()" />
 1800: <br />
 1801: <br />
 1802: </form>
 1803: </body>
 1804: </html>
 1805: END
 1806:     return;
 1807: }
 1808: 
 1809: sub print_sortfilter_options {
 1810:     my ($r,$symb,$previous,$feedurl) = @_;
 1811: 
 1812:     &Apache::loncommon::content_type($r,'text/html');
 1813:     $r->send_http_header;
 1814: 
 1815:     &Apache::lonenc::check_encrypt(\$symb);
 1816:     my @sections = ();
 1817:     my $section_sel = '';
 1818:     my $numsections = 0;
 1819:     my $numvisible = 5;
 1820:     my %sectioncount = ();
 1821: 
 1822:     $numsections = &Apache::loncommon::get_sections($env{'course.'.$env{'request.course.id'}.'.domain'},$env{'course.'.$env{'request.course.id'}.'.num'},\%sectioncount);
 1823: 
 1824:     if ($env{'request.course.sec'} !~ /^\s*$/) {  #Restrict section choice to current section 
 1825:         @sections = ('all',$env{'request.course.sec'});
 1826:         $numvisible = 2;
 1827:     } else {
 1828:         @sections = sort {$a cmp $b} keys(%sectioncount);
 1829:         unshift(@sections,'all'); # Put 'all' at the front of the list
 1830:         if ($numsections < 4) {
 1831:             $numvisible = $numsections + 1;
 1832:         }
 1833:     }
 1834:     foreach (@sections) {
 1835:         $section_sel .= "  <option value=\"$_\" />$_\n";
 1836:     }
 1837:                                                                                    
 1838:     my $function = &Apache::loncommon::get_users_function();
 1839:     my $tabcolor = &Apache::loncommon::designparm($function.'.tabbg',
 1840:                                                     $env{'user.domain'});
 1841:     my $bodytag=&Apache::loncommon::bodytag('Discussion options',
 1842:                                           '','');
 1843:     my %lt = &Apache::lonlocal::texthash(
 1844:         'diso' => 'Discussion sorting and filtering options',
 1845:         'diop' => 'Display Options',
 1846:         'curr' => 'Current setting ',
 1847:         'actn' => 'Action',
 1848:         'prca' => 'Set options that control the sort order of posts, and/or which posts are displayed.',
 1849:         'soor' => 'Sort order',
 1850:         'spur' => 'Specific user roles',
 1851:         'sprs' => 'Specific role status',
 1852:         'spse' => 'Specific sections',
 1853:         'psub' => 'Pick specific users (by name)',
 1854:         'shal' => 'Show a list of current posters'
 1855:     );
 1856: 
 1857:     my %sort_types = ();
 1858:     my %role_types = ();
 1859:     my %status_types = ();
 1860:     &sort_filter_names(\%sort_types,\%role_types,\%status_types);
 1861:     my $html=&Apache::lonxml::xmlbegin();
 1862:     $r->print(<<END);
 1863: $html
 1864: <head>
 1865: <title>$lt{'diso'}</title>
 1866: <meta http-equiv="pragma" content="no-cache" />
 1867: <script type="text/javascript">
 1868: function verifyFilter() {
 1869:     var rolenum = 0
 1870:     for (var i=0; i<document.modifyshown.rolefilter.length; i++) {
 1871:         if (document.modifyshown.rolefilter.options[i].selected == true) {
 1872:             rolenum ++
 1873:         }
 1874:     }
 1875:     if (rolenum == 0) {
 1876:         document.modifyshown.rolefilter.options[0].selected = true
 1877:     }
 1878: 
 1879:     var secnum = 0
 1880:     for (var i=0; i<document.modifyshown.sectionpick.length; i++) {
 1881:         if (document.modifyshown.sectionpick.options[i].selected == true) {
 1882:             secnum ++
 1883:         }
 1884:     }
 1885:     if (secnum == 0) {
 1886:         document.modifyshown.sectionpick.options[0].selected = true
 1887:     }
 1888:     document.modifyshown.submit();
 1889: }
 1890: </script>
 1891: </head>
 1892: $bodytag
 1893: <form name="modifyshown" method="post" action="/adm/feedback">
 1894: <b>$lt{'diso'}</b><br/> $lt{'prca'}
 1895: <br /><br />
 1896: <table border="0">
 1897:  <tr>
 1898:   <td><b>$lt{'soor'}</b></td>
 1899:   <td>&nbsp;</td>
 1900:   <td><b>$lt{'sprs'}</b></td>
 1901:   <td>&nbsp;</td>
 1902:   <td><b>$lt{'spur'}</b></td>
 1903:   <td>&nbsp;</td>
 1904:   <td><b>$lt{'spse'}</b></td>
 1905:   <td>&nbsp;</td>
 1906:   <td><b>$lt{'psub'}</b></td>
 1907:  </tr>
 1908:  <tr>
 1909:   <td align="center">
 1910:    <select name="sortposts">
 1911:     <option value="ascdate" selected="selected" />$sort_types{'ascdate'}
 1912:     <option value="descdate" />$sort_types{'descdate'}
 1913:     <option value="thread" />$sort_types{'thread'}
 1914:     <option value="subject" />$sort_types{'subject'}
 1915:     <option value="username" />$sort_types{'username'}
 1916:     <option value="lastfirst" />$sort_types{'lastfirst'}
 1917:    </select>
 1918:   </td>
 1919:   <td>&nbsp;</td>
 1920:   <td align="center">
 1921:    <select name="statusfilter">
 1922:     <option value="all" selected="selected" />$status_types{'all'}
 1923:     <option value="Active" />$status_types{'Active'}
 1924:     <option value="Expired" />$status_types{'Expired'}
 1925:    </select>
 1926:   </td>
 1927:   <td>&nbsp;</td>
 1928:   <td align="center">
 1929:    <select name="rolefilter" multiple="true" size="5">
 1930:     <option value="all" />$role_types{'all'}
 1931:     <option value="st" />$role_types{'st'}
 1932:     <option value="cc" />$role_types{'cc'}
 1933:     <option value="in" />$role_types{'in'}
 1934:     <option value="ta" />$role_types{'ta'}
 1935:     <option value="ep" />$role_types{'ep'}
 1936:     <option value="ad" />$role_types{'ad'}
 1937:     <option value="cr" />$role_types{'cr'}
 1938:    </select>
 1939:   </td>
 1940:   <td>&nbsp;</td>
 1941:   <td align="center">
 1942:    <select name="sectionpick" multiple="true" size="$numvisible">
 1943:     $section_sel
 1944:    </select>
 1945:   </td>
 1946:   <td>&nbsp;</td>
 1947:   <td><label><input type="checkbox" name="posterlist" value="$symb" />$lt{'shal'}</label></td>
 1948:  </tr>
 1949: </table>
 1950: <br />
 1951: <br />
 1952: <input type="hidden" name="previous" value="$previous" />
 1953: <input type="hidden" name="applysort" value="$symb" />
 1954: <input type="button" name="sub" value="Store Changes" onClick="verifyFilter()" />
 1955: <br />
 1956: <br />
 1957: </form>
 1958: </body>
 1959: </html>
 1960: END
 1961: }
 1962: 
 1963: sub print_showposters {
 1964:     my ($r,$symb,$previous,$feedurl,$sortposts) = @_;
 1965: 
 1966:     &Apache::loncommon::content_type($r,'text/html');
 1967:     $r->send_http_header;
 1968: 
 1969:     &Apache::lonenc::check_encrypt(\$symb);
 1970:     my $crs='/'.$env{'request.course.id'};
 1971:     if ($env{'request.course.sec'}) {
 1972:         $crs.='_'.$env{'request.course.sec'};
 1973:     }
 1974:     $crs=~s/\_/\//g;
 1975:     my $seeid=&Apache::lonnet::allowed('rin',$crs);
 1976:     my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 1977:                           $env{'course.'.$env{'request.course.id'}.'.domain'},
 1978:                           $env{'course.'.$env{'request.course.id'}.'.num'});
 1979:     my %namesort = ();
 1980:     my %postcounts = ();
 1981:     my %lt=&Apache::lonlocal::texthash(
 1982:                      'diso' => 'Discussion filtering options',
 1983:     );
 1984:     my $bodytag=&Apache::loncommon::bodytag('Discussion options',
 1985:                                           '','');
 1986:     if ($contrib{'version'}) {
 1987:         for (my $idx=1;$idx<=$contrib{'version'};$idx++) {
 1988:             my $hidden=($contrib{'hidden'}=~/\.$idx\./);
 1989:             my $deleted=($contrib{'deleted'}=~/\.$idx\./);
 1990:             unless ((($hidden) && (!$seeid)) || ($deleted)) {
 1991:                 if ((!$contrib{$idx.':anonymous'}) || ($seeid)) {
 1992:                     my %names = &Apache::lonnet::get('environment',['firstname','lastname'],$contrib{$idx.':senderdomain'},$contrib{$idx.':sendername'});
 1993:                     my $lastname = $names{'lastname'};
 1994:                     my $firstname = $names{'firstname'};
 1995:                     if ($lastname eq '') {
 1996:                         $lastname = '_';
 1997:                     }
 1998:                     if ($firstname eq '') {
 1999:                         $firstname = '_';
 2000:                     }
 2001:                     unless (defined($namesort{$lastname})) {
 2002:                         %{$namesort{$lastname}} = ();
 2003:                     }
 2004:                     my $poster =  $contrib{$idx.':sendername'}.':'.$contrib{$idx.':senderdomain'};
 2005:                     $postcounts{$poster} ++;
 2006:                     if (defined($namesort{$lastname}{$firstname})) {
 2007:                         if (!grep/^$poster$/,@{$namesort{$lastname}{$firstname}}) {
 2008:                             push @{$namesort{$lastname}{$firstname}}, $poster;
 2009:                         }
 2010:                     } else {
 2011:                         @{$namesort{$lastname}{$firstname}} = ("$poster");
 2012:                     }
 2013:                 }
 2014:             }
 2015:         }
 2016:     }
 2017:     my $html=&Apache::lonxml::xmlbegin();
 2018:     $r->print(<<END);
 2019: $html
 2020: <head>
 2021: <title>$lt{'diso'}</title>
 2022: <meta http-equiv="pragma" content="no-cache" />
 2023: </head>
 2024: $bodytag
 2025:  <form name="pickpostersform" method="post">
 2026:   <table border="0">
 2027:    <tr>
 2028:     <td bgcolor="#777777">
 2029:      <table border="0" cellpadding="3">
 2030:       <tr bgcolor="#e6ffff">
 2031:        <td><b>No.</b></td>
 2032:        <td><b>Select</b></td>
 2033:        <td><b>Fullname</b><font color="#999999">(Username/domain)</font></td>
 2034:        <td><b>Posts</td>
 2035:       </tr>
 2036: END
 2037:     my $count = 0;
 2038:     foreach my $last (sort keys %namesort) {
 2039:         foreach my $first (sort keys %{$namesort{$last}}) {
 2040:             foreach (sort @{$namesort{$last}{$first}}) {
 2041:                 my ($uname,$udom) = split/:/,$_;
 2042:                 if (!$uname || !$udom) { 
 2043:                     next;
 2044:                 } else {
 2045:                     $count ++;
 2046:                     $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>');
 2047:                 }
 2048:             }
 2049:         }
 2050:     }
 2051:     $r->print(<<END);
 2052:      </table>
 2053:     </td>
 2054:    </tr>
 2055:   </table>
 2056: <br />
 2057: <input type="hidden" name="sortposts" value="$sortposts" />
 2058: <input type="hidden" name="userpick" value="$symb" />
 2059: <input type="button" name="store" value="Display posts" onClick="javascript:document.pickpostersform.submit()" />
 2060: </form>
 2061: </body>
 2062: </html>
 2063: END
 2064: }
 2065: 
 2066: sub get_post_versions {
 2067:     my ($versions,$incoming,$htmldecode,$numver) = @_;
 2068:     if ($incoming =~ /^<version num="0">/) {
 2069:         my $p = HTML::LCParser->new(\$incoming);
 2070:         my $done = 0;                                                                       
 2071:         while ( (my $token = $p->get_tag("version")) && (!$done)) {
 2072:             my $num = $token->[1]{num};
 2073:             my $text = $p->get_text("/version");
 2074:             if (defined($numver)) {
 2075:                 if ($num == $numver) {
 2076:                     if ($htmldecode) {
 2077:                         $text = &HTML::Entities::decode($text);
 2078:                     }
 2079:                     $$versions{$numver}=$text;
 2080:                     $done = 1;
 2081:                 }
 2082:             } else {
 2083:                 if ($htmldecode) {
 2084:                     $text = &HTML::Entities::decode($text);
 2085:                 }
 2086:                 $$versions{$num}=$text;
 2087:             }
 2088:         }
 2089:     } else {
 2090:         if (!defined($numver)) {
 2091:             $numver = 0;
 2092:         }
 2093:         if ($htmldecode) {
 2094:             $$versions{$numver} = $incoming;
 2095:         } else {
 2096:             $$versions{$numver} = &HTML::Entities::encode($incoming,'<>&"');
 2097:         }
 2098:     }
 2099:     return;
 2100: }
 2101: 
 2102: sub get_post_attachments {
 2103:     my ($attachments,$attachmenturls) = @_;
 2104:     my $num;
 2105:     if ($attachmenturls =~ m/^<attachment id="0">/) {
 2106:         my $p = HTML::LCParser->new(\$attachmenturls);
 2107:         while (my $token = $p->get_tag("attachment","filename","post"))  {
 2108:             if ($token->[0] eq "attachment") {
 2109:                 $num = $token->[1]{id};
 2110:                 %{$$attachments{$num}} =();
 2111:             } elsif ($token->[0] eq "filename") {
 2112:                 $$attachments{$num}{'filename'} = $p->get_text("/filename");
 2113:             } elsif ($token->[0] eq "post") {
 2114:                 my $id = $token->[1]{id};
 2115:                 $$attachments{$num}{$id} = $p->get_text("/post");
 2116:             }
 2117:         }
 2118:     } else {
 2119:         %{$$attachments{'0'}} = ();
 2120:         $$attachments{'0'}{'filename'} = $attachmenturls;
 2121:         $$attachments{'0'}{'0'} = 'n';
 2122:     }
 2123: 
 2124:     return;
 2125: }
 2126: 
 2127: sub fail_redirect {
 2128:   my ($r,$feedurl) = @_;
 2129:   if ($feedurl=~/^\/adm\//) { $feedurl.='?register=1' };
 2130:   my $logo=&Apache::loncommon::lonhttpdurl('/adm/lonIcons/lonlogos.gif');
 2131:   my $html=&Apache::lonxml::xmlbegin();
 2132:   $r->print (<<ENDFAILREDIR);
 2133: $html
 2134: <head>
 2135: <title>Feedback not sent</title>
 2136: <meta http-equiv="pragma" content="no-cache" />
 2137: <meta HTTP-EQUIV="Refresh" CONTENT="2; url=$feedurl" />
 2138: </head>
 2139: <body bgcolor="#FFFFFF">
 2140: <img align="right" src="$logo" />
 2141: <b>Sorry, no recipients  ...</b>
 2142: <br /><a href="$feedurl">Continue</a>
 2143: </body>
 2144: </html>
 2145: ENDFAILREDIR
 2146: }
 2147: 
 2148: sub redirect_back {
 2149:   my ($r,$feedurl,$typestyle,$sendsomething,$sendposts,$blog,$status,$previous,$sort,$rolefilter,$statusfilter,$sectionpick,$numpicks) = @_;
 2150:   my $sorttag = '';
 2151:   my $roletag = '';
 2152:   my $statustag = '';
 2153:   my $sectag = '';
 2154:   my $userpicktag = '';
 2155:   my $qrystr = '';
 2156:   my $prevtag = '';
 2157: 
 2158:   &Apache::loncommon::content_type($r,'text/html');
 2159:   $r->send_http_header;
 2160: 
 2161:   &dewrapper(\$feedurl);
 2162:   if ($feedurl=~/^\/adm\//) { $feedurl.='?register=1' };
 2163:   if ($previous > 0) {
 2164:       $qrystr = 'previous='.$previous;
 2165:       if ($feedurl =~ /\?register=1/) {
 2166:           $feedurl .= '&'.$qrystr;
 2167:       } else {
 2168:           $feedurl .= '?'.$qrystr;
 2169:       }
 2170:       $prevtag = '<input type="hidden" name="previous" value="'.$previous.'" />';
 2171:   }
 2172:   if (defined($sort)) {
 2173:       my $sortqry = 'sortposts='.$sort;
 2174:       if (($feedurl =~ /\?register=1/) || ($feedurl =~ /\?previous=/)) {
 2175:           $feedurl .= '&'.$sortqry;
 2176:       } else {
 2177:           $feedurl .= '?'.$sortqry;
 2178:       }
 2179:       $sorttag = '<input type="hidden" name="sortposts" value="'.$sort.'" />';
 2180:       if (defined($numpicks)) {
 2181:           my $userpickqry = 'totposters='.$numpicks;
 2182:           $feedurl .= '&'.$userpickqry;
 2183:           $userpicktag = '<input type="hidden" name="totposters" value="'.$numpicks.'" />';
 2184:       } else {
 2185:           if (ref($sectionpick) eq 'ARRAY') {
 2186:               $feedurl .= '&sectionpick=';
 2187:               $sectag .=  '<input type="hidden" name="sectionpick" value="';
 2188:               foreach (@{$sectionpick}) {
 2189:                   $feedurl .= $_.',';
 2190:                   $sectag .= $_.',';
 2191:               }
 2192:               $feedurl =~ s/,$//;
 2193:               $sectag =~ s/,$//;
 2194:               $sectag .= '" />';
 2195:           } else {
 2196:               $feedurl .= '&sectionpick='.$sectionpick;
 2197:               $sectag = '<input type="hidden" name="sectionpick" value="'.$sectionpick.'" />';
 2198:           }
 2199:           if (ref($rolefilter) eq 'ARRAY') {
 2200:               $feedurl .= '&rolefilter=';
 2201:               $roletag .=  '<input type="hidden" name="rolefilter" value="';
 2202:               foreach (@{$rolefilter}) {
 2203:                   $feedurl .= $_.',';
 2204:                   $roletag .= $_.',';
 2205:               }
 2206:               $feedurl =~ s/,$//;
 2207:               $roletag =~ s/,$//;
 2208:               $roletag .= '" />';
 2209:           } else {
 2210:               $feedurl .= '&rolefilter='.$rolefilter;
 2211:               $roletag = '<input type="hidden" name="rolefilter" value="'.$rolefilter.'" />';
 2212:           }
 2213:           $feedurl .= '&statusfilter='.$statusfilter;
 2214:           $statustag ='<input type="hidden" name="statusfilter" value="'.$statusfilter.'" />';
 2215:       }
 2216:   }
 2217:   $feedurl=&Apache::lonenc::check_encrypt($feedurl);
 2218:   my $logo=&Apache::loncommon::lonhttpdurl('/adm/lonIcons/lonlogos.gif');
 2219:   my $html=&Apache::lonxml::xmlbegin();
 2220:   $r->print (<<ENDREDIR);
 2221: $html
 2222: <head>
 2223: <title>Feedback sent</title>
 2224: <meta http-equiv="pragma" content="no-cache" />
 2225: <meta HTTP-EQUIV="Refresh" CONTENT="2; url=$feedurl" />
 2226: </head>
 2227: <body bgcolor="#FFFFFF" onLoad='if (window.name!="loncapaclient") { this.document.reldt.submit(); self.close(); }'>
 2228: <img align="right" src="$logo" />
 2229: $typestyle
 2230: <b>Sent $sendsomething message(s), and $sendposts post(s).</b>
 2231: $blog
 2232: <font color="red">$status</font>
 2233: <form name="reldt" action="$feedurl" target="loncapaclient">
 2234: $prevtag
 2235: $sorttag
 2236: $statustag
 2237: $roletag
 2238: $sectag
 2239: $userpicktag
 2240: </form>
 2241: <br /><a href="$feedurl">Continue</a>
 2242: </body>
 2243: </html>
 2244: ENDREDIR
 2245: }
 2246: 
 2247: sub no_redirect_back {
 2248:   my ($r,$feedurl) = @_;
 2249:   my $nofeed=&mt('Sorry, no feedback possible on this resource  ...');
 2250:   my $continue=&mt('Continue');
 2251:   my $html=&Apache::lonxml::xmlbegin();
 2252:   $r->print (<<ENDNOREDIR);
 2253: $html
 2254: <head>
 2255: <title>Feedback not sent</title>
 2256: <meta http-equiv="pragma" content="no-cache" />
 2257: ENDNOREDIR
 2258: 
 2259:   if ($feedurl!~/^\/adm\/feedback/) { 
 2260:       $r->print('<meta HTTP-EQUIV="Refresh" CONTENT="2; url='.
 2261: 		&Apache::lonenc::check_encrypt($feedurl).'">');
 2262:   }
 2263:   $feedurl=&Apache::lonenc::check_encrypt($feedurl);
 2264:   my $logo=&Apache::loncommon::lonhttpdurl('/adm/lonIcons/lonlogos.gif');
 2265:   $r->print (<<ENDNOREDIRTWO);
 2266: </head>
 2267: <body bgcolor="#FFFFFF" onLoad='if (window.name!="loncapaclient") { self.close(); }'>
 2268: <img align="right" src="$logo" />
 2269: <b>$nofeed</b>
 2270: <br /><a href="$feedurl">$continue</a>
 2271: </body>
 2272: </html>
 2273: ENDNOREDIRTWO
 2274: }
 2275: 
 2276: sub screen_header {
 2277:     my ($feedurl,$symb) = @_;
 2278:     my $msgoptions='';
 2279:     my $discussoptions='';
 2280:     unless (($env{'form.replydisc'}) || ($env{'form.editdisc'})) {
 2281: 	if (($feedurl=~/^\/res\//) && ($feedurl!~/^\/res\/adm/) && ($env{'user.adv'})) {
 2282: 	    $msgoptions= 
 2283: 		'<p><label><input type="checkbox" name="author" /> '.
 2284: 		&mt('Feedback to resource author').'</label></p>';
 2285: 	}
 2286: 	if (&feedback_available(1)) {
 2287: 	    $msgoptions.=
 2288: 		'<p><label><input type="checkbox" name="question" /> '.
 2289: 		&mt('Question about resource content').'</label></p>';
 2290: 	}
 2291: 	if (&feedback_available(0,1)) {
 2292: 	    $msgoptions.=
 2293: 		'<p><label><input type="checkbox" name="course" /> '.
 2294: 		&mt('Question/Comment/Feedback about course content').
 2295: 		'</label></p>';
 2296: 	}
 2297: 	if (&feedback_available(0,0,1)) {
 2298: 	    $msgoptions.=
 2299: 		'<p><label><input type="checkbox" name="policy" /> '.
 2300: 		&mt('Question/Comment/Feedback about course policy').
 2301: 		'</label></p>';
 2302: 	}
 2303:     }
 2304:     if ($env{'request.course.id'}) {
 2305: 	if (&discussion_open(undef,$symb) &&
 2306: 	    &Apache::lonnet::allowed('pch',
 2307: 				     $env{'request.course.id'}.
 2308: 				     ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) {
 2309: 	    $discussoptions='<label><input type="checkbox" name="discuss" onClick="this.form.anondiscuss.checked=false;" '.
 2310: 		($env{'form.replydisc'}?' checked="1"':'').' /> '.
 2311: 		&mt('Contribution to course discussion of resource');
 2312: 	    $discussoptions.='</label><br /><label><input type="checkbox" name="anondiscuss" onClick="this.form.discuss.checked=false;" /> '.
 2313: 		&mt('Anonymous contribution to course discussion of resource').
 2314: 		' <i>('.&mt('name only visible to course faculty').')</i></label> '.
 2315: 		'<a href="/adm/preferences?action=changescreenname">'.&mt('Change Screenname').'</a>';
 2316:         }
 2317:         #$discussoptions.='<br /><label><input type="checkbox" name="blog" /> '.
 2318: 	#    &mt('Add to my public course blog').'</label>';
 2319:     }
 2320:     if ($msgoptions) { $msgoptions='<h2><img src="'.&Apache::loncommon::lonhttpdurl('/adm/lonMisc/feedback.gif').'" />'.&mt('Sending Messages').'</h2>'.$msgoptions; }
 2321:     if ($discussoptions) { 
 2322: 	$discussoptions='<h2><img src="'.&Apache::loncommon::lonhttpdurl('/adm/lonMisc/chat.gif').'" />'.&mt('Discussion Contributions').'</h2>'.$discussoptions; }
 2323:     return $msgoptions.$discussoptions;
 2324: }
 2325: 
 2326: sub resource_output {
 2327:   my ($feedurl) = @_;
 2328:   my $usersaw=&Apache::lonnet::ssi_body($feedurl);
 2329:   $usersaw=~s/\<body[^\>]*\>//gi;
 2330:   $usersaw=~s/\<\/body\>//gi;
 2331:   $usersaw=~s/\<html\>//gi;
 2332:   $usersaw=~s/\<\/html\>//gi;
 2333:   $usersaw=~s/\<head\>//gi;
 2334:   $usersaw=~s/\<\/head\>//gi;
 2335:   $usersaw=~s/action\s*\=/would_be_action\=/gi;
 2336:   return $usersaw;
 2337: }
 2338: 
 2339: sub clear_out_html {
 2340:   my ($message,$override)=@_;
 2341:   unless (&Apache::lonhtmlcommon::htmlareablocked()) { return $message; }
 2342: # Always allow the <m>-tag
 2343:   my %html=(M=>1);
 2344: # Check if more is allowed
 2345:   my $cid=$env{'request.course.id'};
 2346:   if (($env{"course.$cid.allow_limited_html_in_feedback"} =~ m/yes/i) ||
 2347:       ($override)) {
 2348:       # allows <B> <I> <P> <A> <LI> <OL> <UL> <EM> <BR> <TT> <STRONG> 
 2349:       # <BLOCKQUOTE> <DIV .*> <DIV> <IMG> <M> <SPAN> <H1> <H2> <H3> <H4> <SUB>
 2350:       # <SUP>
 2351:       %html=(B=>1, I=>1, P=>1, A=>1, LI=>1, OL=>1, UL=>1, EM=>1,
 2352: 	     BR=>1, TT=>1, STRONG=>1, BLOCKQUOTE=>1, DIV=>1, IMG=>1,
 2353: 	     M=>1, ALGEBRA=>1, SUB=>1, SUP=>1, SPAN=>1, 
 2354: 	     H1=>1, H2=>1, H3=>1, H4=>1, H5=>1);
 2355:   }
 2356: # Do the substitution of everything that is not explicitly allowed
 2357:   $message =~ s/\<(\/?\s*(\w+)[^\>\<]*)/
 2358: 	  {($html{uc($2)}&&(length($1)<1000))?"\<$1":"\&lt;$1"}/ge;
 2359:   $message =~ s/(\<?\s*(\w+)[^\<\>]*)\>/
 2360: 	  {($html{uc($2)}&&(length($1)<1000))?"$1\>":"$1\&gt;"}/ge;
 2361:   return $message;
 2362: }
 2363: 
 2364: sub assemble_email {
 2365:   my ($feedurl,$message,$prevattempts,$usersaw,$useranswer)=@_;
 2366:   my $email=<<"ENDEMAIL";
 2367: $message
 2368: ENDEMAIL
 2369:     my $citations=<<"ENDCITE";
 2370: <h2>Previous attempts of student (if applicable)</h2>
 2371: $prevattempts
 2372: <br /><hr />
 2373: <h2>Original screen output (if applicable)</h2>
 2374: $usersaw
 2375: <h2>Correct Answer(s) (if applicable)</h2>
 2376: $useranswer
 2377: ENDCITE
 2378:   return ($email,$citations);
 2379: }
 2380: 
 2381: sub secapply {
 2382:     my $rec=shift;
 2383:     my $defaultflag=shift;
 2384:     $rec=~s/\s+//g;
 2385:     $rec=~s/\@/\:/g;
 2386:     my ($adr,$sections)=($rec=~/^([^\(]+)\(([^\)]+)\)/);
 2387:     if ($sections) {
 2388: 	foreach (split(/\;/,$sections)) {
 2389:             if (($_ eq $env{'request.course.sec'}) ||
 2390:                 ($defaultflag && ($_ eq '*'))) {
 2391:                 return $adr; 
 2392:             }
 2393:         }
 2394:     } else {
 2395:        return $rec;
 2396:     }
 2397:     return '';
 2398: }
 2399: 
 2400: =pod 
 2401: 
 2402: =over 4
 2403: 
 2404: =item *
 2405: 
 2406: decide_receiver($feedurl,$author,$question,$course,$policy,$defaultflag);
 2407: 
 2408: Arguments
 2409:   $feedurl - /res/ url of resource (only need if $author is true)
 2410:   $author,$question,$course,$policy - all true/false parameters
 2411:     if true will attempt to find the addresses of user that should receive
 2412:     this type of feedback (author - feedback to author of resource $feedurl,
 2413:     $question 'Resource Content Questions', $course 'Course Content Question',
 2414:     $policy 'Course Policy')
 2415:     (Additionally it also checks $env for whether the corresponding form.<name>
 2416:     element exists, for ease of use in a html response context)
 2417:    
 2418:   $defaultflag - (internal should be left blank) if true gather addresses 
 2419:                  that aren't for a section even if I have a section
 2420:                  (used for reccursion internally, first we look for
 2421:                  addresses for our specific section then we recurse
 2422:                  and look for non section addresses)
 2423: 
 2424: Returns
 2425:   $typestyle - string of html text, describing what addresses were found
 2426:   %to - a hash, which keys are addresses of users to send messages to
 2427:         the keys will look like   name:domain
 2428: 
 2429: =cut
 2430: 
 2431: sub decide_receiver {
 2432:   my ($feedurl,$author,$question,$course,$policy,$defaultflag) = @_;
 2433:   my $typestyle='';
 2434:   my %to=();
 2435:   if ($env{'form.author'}||$author) {
 2436:     $typestyle.='Submitting as Author Feedback<br />';
 2437:     $feedurl=~/^\/res\/(\w+)\/(\w+)\//;
 2438:     $to{$2.':'.$1}=1;
 2439:   }
 2440:   if ($env{'form.question'}||$question) {
 2441:     $typestyle.='Submitting as Question<br />';
 2442:     foreach (split(/\,/,
 2443: 		   $env{'course.'.$env{'request.course.id'}.'.question.email'})
 2444: 	     ) {
 2445: 	my $rec=&secapply($_,$defaultflag);
 2446:         if ($rec) { $to{$rec}=1; }
 2447:     } 
 2448:   }
 2449:   if ($env{'form.course'}||$course) {
 2450:     $typestyle.='Submitting as Comment<br />';
 2451:     foreach (split(/\,/,
 2452: 		   $env{'course.'.$env{'request.course.id'}.'.comment.email'})
 2453: 	     ) {
 2454: 	my $rec=&secapply($_,$defaultflag);
 2455:         if ($rec) { $to{$rec}=1; }
 2456:     } 
 2457:   }
 2458:   if ($env{'form.policy'}||$policy) {
 2459:     $typestyle.='Submitting as Policy Feedback<br />';
 2460:     foreach (split(/\,/,
 2461: 		   $env{'course.'.$env{'request.course.id'}.'.policy.email'})
 2462: 	     ) {
 2463: 	my $rec=&secapply($_,$defaultflag);
 2464:         if ($rec) { $to{$rec}=1; }
 2465:     } 
 2466:   }
 2467:   if ((scalar(%to) eq '0') && (!$defaultflag)) {
 2468:      ($typestyle,%to)=
 2469: 	 &decide_receiver($feedurl,$author,$question,$course,$policy,1);
 2470:   }
 2471:   return ($typestyle,%to);
 2472: }
 2473: 
 2474: sub feedback_available {
 2475:     my ($question,$course,$policy)=@_;
 2476:     my ($typestyle,%to)=&decide_receiver('',0,$question,$course,$policy);
 2477:     return scalar(%to);
 2478: }
 2479: 
 2480: sub send_msg {
 2481:   my ($feedurl,$email,$citations,$attachmenturl,%to)=@_;
 2482:   my $status='';
 2483:   my $sendsomething=0;
 2484:   foreach (keys %to) {
 2485:     if ($_) {
 2486:       my $declutter=&Apache::lonnet::declutter($feedurl);
 2487:       unless (&Apache::lonmsg::user_normal_msg(split(/\:/,$_),
 2488:                'Feedback ['.$declutter.']',$email,$citations,$feedurl,
 2489:                 $attachmenturl)=~/ok/) {
 2490: 	$status.='<br />'.&mt('Error sending message to').' '.$_.'<br />';
 2491:       } else {
 2492: 	$sendsomething++;
 2493:       }
 2494:     }
 2495:   }
 2496: 
 2497:     my %record=&Apache::lonnet::restore('_feedback');
 2498:     my ($temp)=keys %record;
 2499:     unless ($temp=~/^error\:/) {
 2500:        my %newrecord=();
 2501:        $newrecord{'resource'}=$feedurl;
 2502:        $newrecord{'subnumber'}=$record{'subnumber'}+1;
 2503:        unless (&Apache::lonnet::cstore(\%newrecord,'_feedback') eq 'ok') {
 2504: 	   $status.='<br />'.&mt('Not registered').'<br />';
 2505:        }
 2506:     }
 2507:        
 2508:   return ($status,$sendsomething);
 2509: }
 2510: 
 2511: sub adddiscuss {
 2512:     my ($symb,$email,$anon,$attachmenturl,$subject)=@_;
 2513:     my $status='';
 2514:     my $realsymb;
 2515:     if ($symb=~/^bulletin___/) {
 2516: 	my $filename=(&Apache::lonnet::decode_symb($symb))[2];
 2517: 	$filename=~s|^adm/wrapper/||;
 2518: 	$realsymb=&Apache::lonnet::symbread($filename);
 2519:     }
 2520:     if (&discussion_open(undef,$realsymb) &&
 2521: 	&Apache::lonnet::allowed('pch',$env{'request.course.id'}.
 2522:         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) {
 2523: 
 2524:     my %contrib=('message'      => $email,
 2525:                  'sendername'   => $env{'user.name'},
 2526:                  'senderdomain' => $env{'user.domain'},
 2527:                  'screenname'   => $env{'environment.screenname'},
 2528:                  'plainname'    => $env{'environment.firstname'}.' '.
 2529: 		                   $env{'environment.middlename'}.' '.
 2530:                                    $env{'environment.lastname'}.' '.
 2531:                                    $env{'enrironment.generation'},
 2532:                  'attachmenturl'=> $attachmenturl,
 2533:                  'subject'      => $subject);
 2534:     if ($env{'form.replydisc'}) {
 2535: 	$contrib{'replyto'}=(split(/\:\:\:/,$env{'form.replydisc'}))[1];
 2536:     }
 2537:     if ($anon) {
 2538: 	$contrib{'anonymous'}='true';
 2539:     }
 2540:     if (($symb) && ($email)) {
 2541:         if ($env{'form.editdisc'}) {
 2542:             my %newcontrib = ();
 2543:             $contrib{'ip'}=$ENV{'REMOTE_ADDR'};
 2544:             $contrib{'host'}=$Apache::lonnet::perlvar{'lonHostID'};
 2545:             $contrib{'timestamp'} = time;
 2546:             $contrib{'history'} = '';
 2547:             my $numoldver = 0;
 2548:             my ($oldsymb,$oldidx)=split(/\:\:\:/,$env{'form.editdisc'});
 2549: 	    &Apache::lonenc::check_decrypt(\$oldsymb);
 2550:             $oldsymb=~s|(bulletin___\d+___)adm/wrapper/|$1|;
 2551: # get timestamp for last post and history
 2552:             my %oldcontrib=&Apache::lonnet::restore($oldsymb,$env{'request.course.id'},
 2553:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 2554:                      $env{'course.'.$env{'request.course.id'}.'.num'});
 2555:             if (defined($oldcontrib{$oldidx.':replyto'})) {
 2556:                 $contrib{'replyto'} = $oldcontrib{$oldidx.':replyto'};
 2557:             }
 2558:             if (defined($oldcontrib{$oldidx.':history'})) {
 2559:                 if ($oldcontrib{$oldidx.':history'} =~ /:/) {
 2560:                     my @oldversions = split/:/,$oldcontrib{$oldidx.':history'};
 2561:                     $numoldver = @oldversions;
 2562:                 } else {
 2563:                     $numoldver = 1;
 2564:                 }
 2565:                 $contrib{'history'} = $oldcontrib{$oldidx.':history'}.':';
 2566:             }
 2567:             my $numnewver = $numoldver + 1;
 2568:             if (defined($oldcontrib{$oldidx.':subject'})) {
 2569:                 if ($oldcontrib{$oldidx.':subject'} =~ /^<version num="0">/) {
 2570:                     $contrib{'subject'} = '<version num="'.$numnewver.'">'.&HTML::Entities::encode($contrib{'subject'},'<>&"').'</version>';
 2571:                     $contrib{'subject'} = $oldcontrib{$oldidx.':subject'}.$contrib{'subject'};
 2572:                 } else {
 2573:                     $contrib{'subject'} = '<version num="0">'.&HTML::Entities::encode($oldcontrib{$oldidx.':subject'},'<>&"').'</version><version num="1">'.&HTML::Entities::encode($contrib{'subject'},'<>&"').'</version>';
 2574:                 }
 2575:             } 
 2576:             if (defined($oldcontrib{$oldidx.':message'})) {
 2577:                 if ($oldcontrib{$oldidx.':message'} =~ /^<version num="0">/) {
 2578:                     $contrib{'message'} = '<version num="'.$numnewver.'">'.&HTML::Entities::encode($contrib{'message'},'<>&"').'</version>';
 2579:                     $contrib{'message'} = $oldcontrib{$oldidx.':message'}.$contrib{'message'};
 2580:                 } else {
 2581:                     $contrib{'message'} = '<version num="0">'.&HTML::Entities::encode($oldcontrib{$oldidx.':message'},'<>&"').'</version><version num="1">'.&HTML::Entities::encode($contrib{'message'},'<>&"').'</version>';
 2582:                 }
 2583:             }
 2584:             $contrib{'history'} .= $oldcontrib{$oldidx.':timestamp'};
 2585:             foreach (keys %contrib) {
 2586:                 my $key = $oldidx.':'.&Apache::lonnet::escape($oldsymb).':'.$_;                                                                               
 2587:                 $newcontrib{$key} = $contrib{$_};
 2588:             }
 2589:             my $put_reply = &Apache::lonnet::putstore($env{'request.course.id'},
 2590:                   \%newcontrib,
 2591:                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 2592:                   $env{'course.'.$env{'request.course.id'}.'.num'});
 2593:             $status='Editing class discussion'.($anon?' (anonymous)':'');
 2594:         } else {
 2595:            $status='Adding to class discussion'.($anon?' (anonymous)':'').': '.
 2596:            &Apache::lonnet::store(\%contrib,$symb,$env{'request.course.id'},
 2597:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 2598: 		     $env{'course.'.$env{'request.course.id'}.'.num'});
 2599:         }
 2600:         my %storenewentry=($symb => time);
 2601:         $status.='<br />'.&mt('Updating discussion time').': '.
 2602:         &Apache::lonnet::put('discussiontimes',\%storenewentry,
 2603:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 2604: 		     $env{'course.'.$env{'request.course.id'}.'.num'});
 2605:     }
 2606:     my %record=&Apache::lonnet::restore('_discussion');
 2607:     my ($temp)=keys %record;
 2608:     unless ($temp=~/^error\:/) {
 2609:        my %newrecord=();
 2610:        $newrecord{'resource'}=$symb;
 2611:        $newrecord{'subnumber'}=$record{'subnumber'}+1;
 2612:        $status.='<br />'.&mt('Registering').': '.
 2613:                &Apache::lonnet::cstore(\%newrecord,'_discussion');
 2614:     }
 2615:     } else {
 2616: 	$status.='Failed.';
 2617:     }
 2618:     return $status.'<br />';   
 2619: }
 2620: 
 2621: # ----------------------------------------------------------- Preview function
 2622: 
 2623: sub show_preview {
 2624:     my $r=shift;
 2625:     &Apache::loncommon::content_type($r,'text/html');
 2626:     $r->send_http_header;
 2627:     my $message=&clear_out_html($env{'form.comment'});
 2628:     &newline_to_br(\$message);
 2629:     $message=&Apache::lonspeller::markeduptext($message);
 2630:     $message=&Apache::lontexconvert::msgtexconverted($message);
 2631:     my $subject=&clear_out_html($env{'form.subject'});
 2632:     $subject=~s/\n/\<br \/\>/g;
 2633:     $subject=&Apache::lontexconvert::msgtexconverted($subject);
 2634:     my $html=&Apache::lonxml::xmlbegin();
 2635:     $r->print($html.'<head>'.
 2636: 	      '</head><body><table border="2"><tr><td>'.
 2637: 	      '<b>Subject:</b> '.$subject.'<br /><br />'.
 2638: 	      $message.'</td></tr></table></body></html>');
 2639: }
 2640: 
 2641: 
 2642: sub newline_to_br {
 2643:     my ($message)=@_;
 2644:     my $newmessage;
 2645:     my $parser=HTML::LCParser->new($message);
 2646:     while (my $token=$parser->get_token()) {
 2647: 	if ($token->[0] eq 'T') {
 2648: 	    my $text=$token->[1];
 2649: 	    $text=~s/\n/\<br \/\>/g;
 2650: 	    $newmessage.=$text;
 2651: 	} elsif ($token->[0] eq 'D' || $token->[0] eq 'C') {
 2652: 	    $newmessage.=$token->[1];
 2653: 	} elsif ($token->[0] eq 'PI' || $token->[0] eq 'E') {
 2654: 	    $newmessage.=$token->[2];
 2655: 	} elsif ($token->[0] eq 'S') {
 2656: 	    $newmessage.=$token->[4];
 2657: 	}
 2658: 	    
 2659:     }
 2660:     $$message=$newmessage;
 2661: }
 2662: 
 2663: sub generate_preview_button {
 2664:     my ($formname,$fieldname)=@_;
 2665:     unless ($formname) { $formname='mailform'; }
 2666:     unless ($fieldname) { $fieldname='comment'; }
 2667:     my $pre=&mt("Show Preview and Check Spelling");
 2668:     return(<<ENDPREVIEW);
 2669: <form name="preview" action="/adm/feedback?preview=1" method="post" target="preview">
 2670: <input type="hidden" name="subject">
 2671: <input type="hidden" name="comment" />
 2672: <input type="button" value="$pre"
 2673: 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();" />
 2674: </form>
 2675: ENDPREVIEW
 2676: }
 2677: 
 2678: sub modify_attachments {
 2679:     my ($r,$currnewattach,$currdelold,$symb,$idx,$attachmenturls)=@_;
 2680:     my $orig_subject = &Apache::lonnet::unescape($env{'form.subject'});
 2681:     my $subject=&clear_out_html($orig_subject);
 2682:     $subject=~s/\n/\<br \/\>/g;
 2683:     $subject=&Apache::lontexconvert::msgtexconverted($subject);
 2684:     my $timestamp=$env{'form.timestamp'};
 2685:     my $numoldver=$env{'form.numoldver'};
 2686:     my $bodytag=&Apache::loncommon::bodytag('Discussion Post Attachments',
 2687:                                           '','');
 2688:     my $msg = '';
 2689:     my %attachments = ();
 2690:     my %currattach = ();
 2691:     if ($idx) {
 2692:         &extract_attachments($attachmenturls,$idx,$numoldver,\$msg,\%attachments,\%currattach,$currdelold);
 2693:     }
 2694:     &Apache::lonenc::check_encrypt(\$symb);
 2695:     my $html=&Apache::lonxml::xmlbegin();
 2696:     $r->print(<<END);
 2697: $html
 2698: <head>
 2699: <title>Managing Attachments</title>
 2700: <script>
 2701:  function setAction () {
 2702:    document.modattachments.action = document.modattachments.origpage.value;
 2703:    document.modattachments.submit();
 2704:  }
 2705: </script> 
 2706: </head>
 2707: $bodytag
 2708: <form name="modattachments" method="post" enctype="multipart/form-data" action="/adm/feedback?attach=$symb">
 2709:  <table border="2">
 2710:   <tr>
 2711:    <td>
 2712:     <b>Subject:</b> $subject</b><br /><br />
 2713: END
 2714:     if ($idx) {
 2715:         if ($attachmenturls) {
 2716:             my @currold = keys %currattach;
 2717:             if (@currold > 0) {
 2718:                 $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");  
 2719:                 foreach my $id (@currold) {
 2720:                     my $attachurl = &HTML::Entities::decode($attachments{$id}{'filename'}); 
 2721:                     $attachurl =~ m#/([^/]+)$#;
 2722:                     $r->print('<label><input type="checkbox" name="deloldattach" value="'.$id.'" />&nbsp;'.$1.'</label><br />'."\n");
 2723:                 }
 2724:                 $r->print("<br />");
 2725:             }
 2726:         }
 2727:     }
 2728:     if (@{$currnewattach} > 0) {
 2729:         $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");
 2730:         foreach (@{$currnewattach}) {
 2731:             $_ =~ m#/([^/]+)$#;
 2732:             $r->print('<label><input type="checkbox" name="delnewattach" value="'.$_.'" />&nbsp;'.$1.'</label><br />'."\n");
 2733:         }
 2734:         $r->print("<br />"); 
 2735:     }
 2736:     $r->print(<<END);
 2737:    Add a new attachment to this post.&nbsp;<input type="file" name="addnewattach" /><input type="button" name="upload" value="Upload" onClick="this.form.submit()" />    
 2738:    </td>
 2739:   </tr>
 2740:  </table>
 2741: <input type="hidden" name="subject" value="$env{'form.subject'}" />
 2742: <input type="hidden" name="comment" value="$env{'form.comment'}" />
 2743: <input type="hidden" name="timestamp" value="$env{'form.timestamp'}" />
 2744: <input type="hidden" name="idx" value="$env{'form.idx'}" />
 2745: <input type="hidden" name="numoldver" value="$env{'form.numoldver'}" />
 2746: <input type="hidden" name="origpage" value="$env{'form.origpage'}" />
 2747: <input type="hidden" name="anondiscuss" value="$env{'form.anondiscuss'}" />
 2748: <input type="hidden" name="blog" value="$env{'form.blog'}" />
 2749: <input type="hidden" name="discuss" value="$env{'form.discuss'}" />
 2750: END
 2751:     foreach (@{$currnewattach}) {
 2752:         $r->print('<input type="hidden" name="currnewattach" value="'.$_.'" />'."\n");
 2753:     }
 2754:     foreach (@{$currdelold}) {
 2755:         $r->print('<input type="hidden" name="deloldattach" value="'.$_.'" />'."\n");
 2756:     }
 2757:     $r->print(<<END);
 2758:  <input type="button" name="rtntoedit" value="Store Changes" onClick="setAction()"/>
 2759: </form>
 2760: </body>
 2761: </html>
 2762: END
 2763:     return;
 2764: }
 2765: 
 2766: sub process_attachments {
 2767:     my ($currnewattach,$currdelold,$keepold) = @_;
 2768: 
 2769:     @{$currnewattach}=
 2770: 	&Apache::loncommon::get_env_multiple('form.currnewattach');
 2771:     @{$currdelold}=
 2772: 	&Apache::loncommon::get_env_multiple('form.deloldattach');
 2773:     if (exists($env{'form.delnewattach'})) {
 2774:         my @currdelnew =
 2775: 	    &Apache::loncommon::get_env_multiple('form.delnewattach');
 2776:         my @currnew = ();
 2777:         foreach my $newone (@{$currnewattach}) {
 2778:             my $delflag = 0;
 2779:             foreach (@currdelnew) {
 2780:                 if ($newone eq $_) {
 2781:                     $delflag = 1;
 2782:                     last;
 2783:                 }
 2784:             }
 2785:             unless ($delflag) {
 2786:                 push @currnew, $newone;
 2787:             }
 2788:         }
 2789:         @{$currnewattach} = @currnew;
 2790:     }
 2791:     @{$keepold} = &Apache::loncommon::get_env_multiple('form.keepold');
 2792: }
 2793: 
 2794: sub generate_attachments_button {
 2795:     my ($idx,$attachnum,$ressymb,$now,$currnewattach,$deloldattach,$numoldver,$mode) = @_;
 2796:     my $origpage = $ENV{'REQUEST_URI'};
 2797:     my $att=$attachnum.' '.&mt("attachments");
 2798:     my $response = (<<END);
 2799: <form name="attachment" action="/adm/feedback?attach=$ressymb" method="post">
 2800: Click to add/remove attachments:&nbsp;<input type="button" value="$att"
 2801: 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);
 2802: END
 2803:     unless ($mode eq 'board') {
 2804:         $response .= 'javascript:anonchk();';
 2805:     }
 2806:     $response .= (<<ENDATTACH);
 2807: this.form.submit();" />
 2808: <input type="hidden" name="origpage" value="$origpage" />
 2809: <input type="hidden" name="idx" value="$idx" />
 2810: <input type="hidden" name="timestamp" value="$now" />
 2811: <input type="hidden" name="subject" />
 2812: <input type="hidden" name="comment" />
 2813: <input type="hidden" name="blog" value = "0" />
 2814: <input type="hidden" name="anondiscuss" value = "0" />
 2815: <input type="hidden" name="discuss" value = "0" />
 2816: <input type="hidden" name="numoldver" value="$numoldver" />
 2817: ENDATTACH
 2818:     if (defined($deloldattach)) {
 2819:         if (@{$deloldattach} > 0) {
 2820:             foreach (@{$deloldattach}) {
 2821:                 $response .= '<input type="hidden" name="deloldattach" value="'.$_.'" />'."\n";
 2822:             }
 2823:         }
 2824:     }
 2825:     if (defined($currnewattach)) {
 2826:         if (@{$currnewattach} > 0) {
 2827:             foreach (@{$currnewattach}) {
 2828:                 $response .= '<input type="hidden" name="currnewattach" value="'.$_.'" />'."\n";
 2829:             }
 2830:         }
 2831:     }
 2832:     $response .= '</form>';
 2833:     return $response;
 2834: }
 2835: 
 2836: sub extract_attachments {
 2837:     my ($attachmenturls,$idx,$numoldver,$message,$attachments,$currattach,$currdelold) = @_;
 2838:     %{$attachments}=();
 2839:     &get_post_attachments($attachments,$attachmenturls);
 2840:     foreach my $id (sort keys %{$attachments}) {
 2841:         if (exists($$attachments{$id}{$numoldver})) {
 2842:             if (defined($currdelold)) {
 2843:                 if (@{$currdelold} > 0) {
 2844:                     unless (grep/^$id$/,@{$currdelold}) {
 2845:                         $$currattach{$id} = $$attachments{$id}{$numoldver}; 
 2846:                     }
 2847:                 } else {
 2848:                     $$currattach{$id} = $$attachments{$id}{$numoldver};
 2849:                 }
 2850:             } else {
 2851:                 $$currattach{$id} = $$attachments{$id}{$numoldver};
 2852:             }
 2853:         }
 2854:     }
 2855:     my @attached = (sort { $a <=> $b } keys %{$currattach});
 2856:     if (@attached == 1) {
 2857:         my $id = $attached[0];
 2858:         my $attachurl;
 2859:         if ($attachmenturls =~ m/^<attachment id="0">/) {
 2860:             $attachurl = &HTML::Entities::decode($$attachments{$id}{'filename'});
 2861:         } else {
 2862:             $attachurl = $$attachments{$id}{'filename'};
 2863:         }
 2864:         $attachurl=~m|/([^/]+)$|;
 2865:         $$message.='<br /><a href="'.$attachurl.'"><tt>'.
 2866:         $1.'</tt></a><br />';
 2867:         &Apache::lonnet::allowuploaded('/adm/feedback',
 2868:                                $attachurl);
 2869:     } elsif (@attached > 1) {
 2870:         $$message.='<ol>';
 2871:         foreach (@attached) {
 2872:             my $id = $_;
 2873:             my $attachurl = &HTML::Entities::decode($$attachments{$id}{'filename'});
 2874:             my ($fname)
 2875:               =($attachurl=~m|/([^/]+)$|);
 2876:             $$message .= '<li><a href="'.$attachurl.
 2877:               '"><tt>'.
 2878:               $fname.'</tt></a></li>';
 2879:             &Apache::lonnet::allowuploaded('/adm/feedback',
 2880:                              $attachurl);
 2881:         }
 2882:         $$message .= '</ol>';
 2883:     }
 2884: }
 2885: 
 2886: sub construct_attachmenturl {
 2887:     my ($currnewattach,$keepold,$symb,$idx)=@_;
 2888:     my $oldattachmenturl;
 2889:     my $newattachmenturl;
 2890:     my $startnum = 0;
 2891:     my $currver = 0;
 2892:     if (($env{'form.editdisc'}) && ($idx)) {
 2893:         my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 2894:                        $env{'course.'.$env{'request.course.id'}.'.domain'},
 2895:                        $env{'course.'.$env{'request.course.id'}.'.num'});
 2896:         $oldattachmenturl = $contrib{$idx.':attachmenturl'};
 2897:         if ($contrib{$idx.':history'}) {
 2898:             if ($contrib{$idx.':history'} =~ /:/) {
 2899:                 my @oldversions = split/:/,$contrib{$idx.':history'};
 2900:                 $currver = 1 + scalar(@oldversions);
 2901:             } else {
 2902:                 $currver = 2;
 2903:             }
 2904:         } else {
 2905:             $currver = 1;
 2906:         }
 2907:         if ($oldattachmenturl) {
 2908:             if ($oldattachmenturl =~ m/^<attachment id="0">/) {
 2909:                 my %attachments = ();
 2910:                 my $prevver = $currver-1;
 2911:                 &get_post_attachments(\%attachments,$oldattachmenturl);
 2912:                 my $numattach = scalar(keys %attachments);
 2913:                 $startnum += $numattach;
 2914:                 foreach my $num (sort {$a <=> $b} keys %attachments) {
 2915:                     $newattachmenturl .= '<attachment id="'.$num.'"><filename>'.$attachments{$num}{'filename'}.'</filename>';
 2916:                     foreach $_ (sort {$a <=> $b} keys %{$attachments{$num}}) {
 2917:                         unless ($_ eq 'filename') {
 2918:                             $newattachmenturl .= '<post id="'.$_.'">'.$attachments{$num}{$_}.'</post>';
 2919:                         }
 2920:                     }
 2921:                     if (grep/^$num$/,@{$keepold}) {
 2922:                         $newattachmenturl .= '<post id="'.$currver.'">'.$attachments{$num}{$prevver}.'</post>';
 2923:                     }
 2924:                     $newattachmenturl .= '</attachment>';
 2925:                 }
 2926:             } else {
 2927:                 $newattachmenturl = '<attachment id="0"><filename>'.&HTML::Entities::encode($oldattachmenturl).'</filename><post id="0">n</post>';
 2928:                 unless (grep/^0$/,@{$keepold}) {
 2929:                     $newattachmenturl .= '<post id="1">n</post>';
 2930:                 }
 2931:                 $newattachmenturl .= '</attachment>';
 2932:                 $startnum ++;
 2933:             }
 2934:         }
 2935:     }
 2936:     for (my $i=0; $i<@{$currnewattach}; $i++) {
 2937:         my $attachnum = $startnum + $i;
 2938:         $newattachmenturl .= '<attachment id="'.$attachnum.'"><filename>'.&HTML::Entities::encode($$currnewattach[$i]).'</filename><post id="'.$currver.'">n</post></attachment>';
 2939:     }
 2940:     return $newattachmenturl; 
 2941: }
 2942: 
 2943: sub has_discussion {
 2944:     my $resourcesref = shift;
 2945:     my $navmap = Apache::lonnavmaps::navmap->new();
 2946:     my @allres=$navmap->retrieveResources();
 2947:     foreach my $resource (@allres) {
 2948:         if ($resource->hasDiscussion()) {
 2949:             my $ressymb = $resource->wrap_symb();
 2950:             push @{$resourcesref}, $ressymb;
 2951:         }
 2952:     }
 2953:     return;
 2954: }
 2955: 
 2956: sub sort_filter_names {
 2957:     my ($sort_types,$role_types,$status_types) = @_;
 2958:     %{$sort_types} = (
 2959:                      ascdate => 'Date order - oldest first',
 2960:                      descdate => 'Date order - newest first',
 2961:                      thread => 'Threaded',
 2962:                      subject => 'By subject',
 2963:                      username => 'By domain and username',
 2964:                      lastfirst => 'By last name, first name'
 2965:                    );
 2966:     %{$role_types} = (
 2967:                      all => 'All roles',
 2968:                      st  => 'Students',
 2969:                      cc  => 'Course Coordinators',
 2970:                      in  => 'Instructors',
 2971:                      ta  => 'TAs',
 2972:                      ep  => 'Exam proctors',
 2973:                      ad  => 'Administrators',
 2974:                      cr  => 'Custom roles'
 2975:                    );
 2976:     %{$status_types} = (
 2977:                      all     => 'Roles of any status',
 2978:                      Active => 'Only active roles',
 2979:                      Expired => 'Only inactive roles'
 2980:                    );
 2981: }
 2982:   
 2983: sub handler {
 2984:   my $r = shift;
 2985:   if ($r->header_only) {
 2986:      &Apache::loncommon::content_type($r,'text/html');
 2987:      $r->send_http_header;
 2988:      return OK;
 2989:   }
 2990: 
 2991: # --------------------------- Get query string for limited number of parameters
 2992: 
 2993:   &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 2994:          ['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']);
 2995:   if ($env{'form.editdisc'}) {
 2996:       if (!(&editing_allowed())) {
 2997:           my $symb=(split(/\:\:\:/,$env{'form.editdisc'}))[0];
 2998:           my ($map,$id,$url)=&Apache::lonnet::decode_symb($symb);
 2999:           my $feedurl=&Apache::lonnet::clutter($url);
 3000:           &redirect_back($r,$feedurl,&mt('Editing not permitted').'<br />',                     '0','0','','',$env{'form.previous'},'','','',);
 3001:           return OK;
 3002:       }
 3003:   } 
 3004:   if ($env{'form.discsymb'}) {
 3005:       my ($symb,$feedurl) = &get_feedurl_and_clean_symb($env{'form.discsymb'});
 3006:       my $readkey = $symb.'_read';
 3007:       my $chgcount = 0;
 3008:       my %readinghash = &Apache::lonnet::get('nohist_'.$env{'request.course.id'}.'_discuss',[$readkey],$env{'user.domain'},$env{'user.name'});
 3009:       foreach my $key (keys %env) {
 3010:           if ($key =~ m/^form\.postunread_(\d+)/) {
 3011:               if ($readinghash{$readkey} =~ /\.$1\./) {
 3012:                   $readinghash{$readkey} =~ s/\.$1\.//;
 3013:                   $chgcount ++;
 3014:               }
 3015:           } elsif ($key =~ m/^form\.postread_(\d+)/) {
 3016:               unless ($readinghash{$readkey} =~ /\.$1\./) {
 3017:                   $readinghash{$readkey} .= '.'.$1.'.';
 3018:                   $chgcount ++;
 3019:               }
 3020:           }
 3021:       }
 3022:       if ($chgcount > 0) {
 3023:           &Apache::lonnet::put('nohist_'.$env{'request.course.id'}.'_discuss',
 3024: 			  \%readinghash,$env{'user.domain'},$env{'user.name'});
 3025:       }
 3026:       &redirect_back($r,$feedurl,&mt('Marked postings read/unread').'<br />',
 3027: 		     '0','0','','',$env{'form.previous'},'','','',);
 3028:       return OK;
 3029:   }
 3030:   if ($env{'form.allversions'}) {
 3031:       &Apache::loncommon::content_type($r,'text/html');
 3032:       $r->send_http_header;
 3033:       my $html=&Apache::lonxml::xmlbegin();
 3034:       my $bodytag=&Apache::loncommon::bodytag('Discussion Post Versions');
 3035:       $r->print(<<END);
 3036: $html
 3037: <head>
 3038: <title>Post Versions</title>
 3039: <meta http-equiv="pragma" content="no-cache" />
 3040: </head>
 3041: $bodytag
 3042: END
 3043:       my $crs='/'.$env{'request.course.id'};
 3044:       if ($env{'request.course.sec'}) {
 3045:           $crs.='_'.$env{'request.course.sec'};
 3046:       }
 3047:       $crs=~s|_|/|g;
 3048:       my $seeid=&Apache::lonnet::allowed('rin',$crs);
 3049:       my ($symb,$idx)=split(/\:\:\:/,$env{'form.allversions'});
 3050:       ($symb)=&get_feedurl_and_clean_symb($symb);
 3051:       if ($idx > 0) {
 3052:           my %messages = ();
 3053:           my %subjects = ();
 3054:           my %attachmsgs = ();
 3055:           my %allattachments = ();
 3056:           my %imsfiles = ();
 3057:           my ($screenname,$plainname);
 3058:           my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 3059:                            $env{'course.'.$env{'request.course.id'}.'.domain'},
 3060:                            $env{'course.'.$env{'request.course.id'}.'.num'});
 3061:           $r->print(&get_post_contents(\%contrib,$idx,$seeid,'allversions',\%messages,\%subjects,\%allattachments,\%attachmsgs,\%imsfiles,\$screenname,\$plainname));
 3062:       }
 3063:       return OK;
 3064:   }
 3065:   if ($env{'form.posterlist'}) {
 3066:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.applysort'});
 3067:       &print_showposters($r,$symb,$env{'form.previous'},$feedurl,
 3068: 			 $env{'form.sortposts'});
 3069:       return OK;
 3070:   }
 3071:   if ($env{'form.userpick'}) {
 3072:       my @posters = &Apache::loncommon::get_env_multiple('form.stuinfo');
 3073:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.userpick'});
 3074:       my $numpicks = @posters;
 3075:       my %discinfo;
 3076:       $discinfo{$symb.'_userpick'} = join('&',@posters);
 3077:       &Apache::lonnet::put('nohist_'.$env{'request.course.id'}.'_discuss',
 3078: 			   \%discinfo,$env{'user.domain'},$env{'user.name'});
 3079:       &redirect_back($r,$feedurl,&mt('Changed sort/filter').'<br />','0','0','',
 3080: 		     '',$env{'form.previous'},$env{'form.sortposts'},'','','',
 3081: 		     $numpicks);
 3082:       return OK;
 3083:   }
 3084:   if ($env{'form.applysort'}) {
 3085:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.applysort'});
 3086:       &redirect_back($r,$feedurl,&mt('Changed sort/filter').'<br />','0','0','',
 3087: 		     '',$env{'form.previous'},$env{'form.sortposts'},
 3088: 		     $env{'form.rolefilter'},$env{'form.statusfilter'},
 3089: 		     $env{'form.sectionpick'});
 3090:       return OK;
 3091:   } elsif ($env{'form.cmd'} eq 'sortfilter') {
 3092:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.symb'});
 3093:       &print_sortfilter_options($r,$symb,$env{'form.previous'},$feedurl);
 3094:       return OK;
 3095:   } elsif ($env{'form.navtime'}) {
 3096:       my %discinfo = ();
 3097:       my @resources = ();
 3098:       if (defined($env{'form.navmaps'})) {
 3099:           if ($env{'form.navmaps'} =~ /:/) {
 3100:               @resources = split/:/,$env{'form.navmaps'};
 3101:           } else {
 3102:               @resources = ("$env{'form.navmaps'}");
 3103:           }
 3104:       } else {
 3105:           &has_discussion(\@resources);
 3106:       }
 3107:       my $numitems = @resources;
 3108:       my $feedurl = '/adm/navmaps';
 3109:       if ($env{'form.navurl'}) { $feedurl .= '?'.$env{'form.navurl'}; }
 3110:       my %lt = &Apache::lonlocal::texthash(
 3111:           'mnpa' => 'Marked "New" posts as read in a total of',
 3112:           'robb' => 'resources/bulletin boards.',
 3113:           'twnp' => 'There are currently no resources or bulletin boards with unread discussion postings.'
 3114:       );       
 3115:       foreach (@resources) {
 3116:           my $ressymb=$_;
 3117: 	  &Apache::lonenc::check_decrypt(\$ressymb);
 3118:           my $lastkey = $ressymb.'_lastread';
 3119:           $discinfo{$lastkey} = $env{'form.navtime'};
 3120:       }
 3121:       my $textline = "<b>$lt{'mnpa'} $numitems $lt{'robb'}</b>";
 3122:       if ($numitems > 0) {
 3123:           &Apache::lonnet::put('nohist_'.$env{'request.course.id'}.'_discuss',
 3124: 			     \%discinfo,$env{'user.domain'},$env{'user.name'});
 3125:       } else {
 3126:           $textline = "<b>$lt{'twnp'}</b>";
 3127:       }
 3128:       &Apache::loncommon::content_type($r,'text/html');
 3129:       $r->send_http_header;
 3130:       my $logo=&Apache::loncommon::lonhttpdurl('/adm/lonIcons/lonlogos.gif');
 3131:       my $html=&Apache::lonxml::xmlbegin();
 3132:       $r->print (<<ENDREDIR);
 3133: $html
 3134: <head>
 3135: <title>New posts marked as read</title>
 3136: <meta http-equiv="pragma" content="no-cache" />
 3137: <meta HTTP-EQUIV="Refresh" CONTENT="2; url=$feedurl" />
 3138: </head>
 3139: <body bgcolor="#FFFFFF" onLoad='if (window.name!="loncapaclient") { this.document.reldt.submit(); self.close(); }'>
 3140: <img align="right" src="$logo" />
 3141: $textline
 3142: <form name="reldt" action="$feedurl" target="loncapaclient">
 3143: </form>
 3144: <br /><a href="$feedurl">Continue</a>
 3145: </body>
 3146: </html>
 3147: ENDREDIR
 3148:       return OK;
 3149:   } elsif ($env{'form.modifydisp'}) {
 3150:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.modifydisp'});
 3151:       my ($dispchgA,$dispchgB,$markchg,$toggchg) = 
 3152: 	  split(/_/,$env{'form.changes'});
 3153:       &print_display_options($r,$symb,$env{'form.previous'},$dispchgA,
 3154: 			     $dispchgB,$markchg,$toggchg,$feedurl);
 3155:       return OK;
 3156:   } elsif ($env{'form.markondisp'} || $env{'form.markonread'} ||
 3157: 	   $env{'form.allposts'}   || $env{'form.onlyunread'} ||
 3158: 	   $env{'form.onlyunmark'} || $env{'form.toggoff'}    ||
 3159: 	   $env{'form.toggon'}     || $env{'form.markread'}) {
 3160:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.symb'});
 3161:       my %discinfo;
 3162: # ------------------------ Modify setting for read/unread toggle for each post 
 3163:       if ($env{'form.toggoff'}) { $discinfo{$symb.'_readtoggle'}=0; }
 3164:       if ($env{'form.toggon'})  { $discinfo{$symb.'_readtoggle'}=1; }
 3165: # --------- Modify setting for identification of 'NEW' posts in this discussion
 3166:       if ($env{'form.markondisp'}) {
 3167: 	  $discinfo{$symb.'_lastread'} = time;
 3168: 	  $discinfo{$symb.'_markondisp'} = 1;
 3169:       }
 3170:       if ($env{'form.markonread'}) {
 3171: 	  if ( $env{'form.previous'} > 0 ) {
 3172: 	      $discinfo{$symb.'_lastread'} = $env{'form.previous'};
 3173: 	  }
 3174: 	  $discinfo{$symb.'_markondisp'} = 0;
 3175:       }
 3176: # --------------------------------- Modify display setting for this discussion 
 3177:       if ($env{'form.allposts'}) {
 3178: 	  $discinfo{$symb.'_showonlyunread'} = 0;
 3179: 	  $discinfo{$symb.'_showonlyunmark'} = 0;
 3180:       }
 3181:       if ($env{'form.onlyunread'}) { $discinfo{$symb.'_showonlyunread'} = 1;  }
 3182:       if ($env{'form.onlyunmark'}) { $discinfo{$symb.'_showonlyunmark'} = 1;  }
 3183: # ----------------------------------------------------- Mark new posts not NEW 
 3184:       if ($env{'form.markread'})   { $discinfo{$symb.'_lastread'} = time; }
 3185:       &Apache::lonnet::put('nohist_'.$env{'request.course.id'}.'_discuss',
 3186: 			   \%discinfo,$env{'user.domain'},$env{'user.name'});
 3187:       my $previous=$env{'form.previous'};
 3188:       if ($env{'form.markondisp'}) { $previous=undef; }
 3189:       &redirect_back($r,$feedurl,&mt('Changed display status').'<br />',
 3190: 		     '0','0','','',$previous);
 3191:       return OK;
 3192:   } elsif (($env{'form.hide'}) || ($env{'form.unhide'})) {
 3193: # ----------------------------------------------------------------- Hide/unhide
 3194:       my $entry=$env{'form.hide'}?$env{'form.hide'}:$env{'form.unhide'};
 3195:       my ($symb,$idx)=split(/\:\:\:/,$entry);
 3196:       ($symb,my $feedurl)=&get_feedurl_and_clean_symb($symb);
 3197: 
 3198:       my $crs='/'.$env{'request.course.id'};
 3199:       if ($env{'request.course.sec'}) {
 3200:           $crs.='_'.$env{'request.course.sec'};
 3201:       }
 3202:       $crs=~s/\_/\//g;
 3203:       my $seeid=&Apache::lonnet::allowed('rin',$crs);
 3204: 
 3205:       if ($env{'form.hide'} && !$seeid && !(&editing_allowed())) {
 3206:           &redirect_back($r,$feedurl,&mt('Deletion not permitted').'<br />',                 '0','0','','',$env{'form.previous'},'','','',);
 3207:           return OK;
 3208:       }
 3209: 
 3210:       my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 3211:                           $env{'course.'.$env{'request.course.id'}.'.domain'},
 3212: 		          $env{'course.'.$env{'request.course.id'}.'.num'});
 3213: 
 3214:       my $currenthidden=$contrib{'hidden'};
 3215:       my $currentstudenthidden=$contrib{'studenthidden'};
 3216: 
 3217:       if ($env{'form.hide'}) {
 3218: 	  $currenthidden.='.'.$idx.'.';
 3219: 	  unless ($seeid) {
 3220: 	      $currentstudenthidden.='.'.$idx.'.';
 3221: 	  }
 3222:       } else {
 3223: 	  $currenthidden=~s/\.$idx\.//g;
 3224:       }
 3225:       my %newhash=('hidden' => $currenthidden);
 3226:       if ( ($env{'form.hide'}) && (!$seeid) ) {
 3227: 	  $newhash{'studenthidden'} = $currentstudenthidden;
 3228:       }
 3229: 
 3230:       &Apache::lonnet::store(\%newhash,$symb,$env{'request.course.id'},
 3231:                            $env{'course.'.$env{'request.course.id'}.'.domain'},
 3232: 			   $env{'course.'.$env{'request.course.id'}.'.num'});
 3233: 
 3234:       &redirect_back($r,$feedurl,&mt('Changed discussion status').'<br />',
 3235: 		     '0','0','','',$env{'form.previous'});
 3236:       return OK;
 3237:   } elsif ($env{'form.cmd'}=~/^(threadedoff|threadedon)$/) {
 3238:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.symb'});
 3239:       if ($env{'form.cmd'} eq 'threadedon') {
 3240: 	  &Apache::lonnet::put('environment',{'threadeddiscussion' => 'on'});
 3241: 	  &Apache::lonnet::appenv('environment.threadeddiscussion' => 'on');
 3242:       } else {
 3243:  	  &Apache::lonnet::del('environment',['threadeddiscussion']);
 3244: 	  &Apache::lonnet::delenv('environment\.threadeddiscussion');
 3245:       }
 3246:       &redirect_back($r,$feedurl,&mt('Changed discussion view mode').'<br />',
 3247: 		     '0','0','','',$env{'form.previous'});
 3248:       return OK;
 3249:   } elsif ($env{'form.deldisc'}) {
 3250: # --------------------------------------------------------------- Hide for good
 3251:       my ($symb,$idx)=split(/\:\:\:/,$env{'form.deldisc'});
 3252:       ($symb,my $feedurl)=&get_feedurl_and_clean_symb($symb);
 3253:       my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 3254:                           $env{'course.'.$env{'request.course.id'}.'.domain'},
 3255: 		          $env{'course.'.$env{'request.course.id'}.'.num'});
 3256:       my %newhash=('deleted' => $contrib{'deleted'}.".$idx.");
 3257:       &Apache::lonnet::store(\%newhash,$symb,$env{'request.course.id'},
 3258: 			   $env{'course.'.$env{'request.course.id'}.'.domain'},
 3259: 			   $env{'course.'.$env{'request.course.id'}.'.num'});
 3260:       &redirect_back($r,$feedurl,&mt('Changed discussion status').'<br />',
 3261: 		     '0','0','','',$env{'form.previous'});
 3262:       return OK;
 3263:   } elsif ($env{'form.preview'}) {
 3264: # -------------------------------------------------------- User wants a preview
 3265:       &show_preview($r);
 3266:       return OK;
 3267:   } elsif ($env{'form.attach'}) {
 3268: # -------------------------------------------------------- Work on attachments
 3269:       &Apache::loncommon::content_type($r,'text/html');
 3270:       $r->send_http_header;
 3271:       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['subject','comment','addnewattach','delnewattach','timestamp','numoldver','idx','anondiscuss','discuss','blog']);
 3272:       my (@currnewattach,@currdelold,@keepold);
 3273:       &process_attachments(\@currnewattach,\@currdelold,\@keepold);
 3274:       if (exists($env{'form.addnewattach.filename'})) {
 3275:           unless (length($env{'form.addnewattach'})>131072) {
 3276:               my $subdir = 'feedback/'.$env{'form.timestamp'};
 3277:               my $newattachment=&Apache::lonnet::userfileupload('addnewattach',undef,$subdir);
 3278: 	      push @currnewattach, $newattachment;
 3279:           }
 3280:       }
 3281:       my $attachmenturls;
 3282:       my ($symb) = &get_feedurl_and_clean_symb($env{'form.attach'});
 3283:       my $idx = $env{'form.idx'};
 3284:       if ($idx) {
 3285:           my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 3286:                          $env{'course.'.$env{'request.course.id'}.'.domain'},
 3287:                          $env{'course.'.$env{'request.course.id'}.'.num'});
 3288:           $attachmenturls = $contrib{$idx.':attachmenturl'};
 3289:       }
 3290:       &modify_attachments($r,\@currnewattach,\@currdelold,$symb,$idx,
 3291: 			  $attachmenturls);
 3292:       return OK;
 3293:   } elsif ($env{'form.export'}) {
 3294:       &Apache::loncommon::content_type($r,'text/html');
 3295:       $r->send_http_header;
 3296:       my ($symb,$feedurl) = &get_feedurl_and_clean_symb($env{'form.export'});
 3297:       my $mode='board';
 3298:       my $status='OPEN';
 3299:       my $previous=$env{'form.previous'};
 3300:       if ($feedurl =~ /\.(problem|exam|quiz|assess|survey|form|library|task)$/) {
 3301:           $mode='problem';
 3302:           $status=$Apache::inputtags::status[-1];
 3303:       }
 3304:       my $discussion = &list_discussion($mode,$status,$symb); 
 3305:       my $bodytag=&Apache::loncommon::bodytag('Resource Feedback and Discussion');
 3306:       $r->print($bodytag.$discussion);                                     
 3307:       return OK;
 3308:   } else {
 3309: # ------------------------------------------------------------- Normal feedback
 3310:       my $feedurl=$env{'form.postdata'};
 3311:       $feedurl=~s/^http\:\/\///;
 3312:       $feedurl=~s/^$ENV{'SERVER_NAME'}//;
 3313:       $feedurl=~s/^$ENV{'HTTP_HOST'}//;
 3314:       $feedurl=~s/\?.+$//;
 3315: 
 3316:       my $symb;
 3317:       if ($env{'form.replydisc'}) {
 3318: 	  $symb=(split(/\:\:\:/,$env{'form.replydisc'}))[0];
 3319: 	  my ($map,$id,$url)=&Apache::lonnet::decode_symb($symb);
 3320: 	  $feedurl=&Apache::lonnet::clutter($url);
 3321:       } elsif ($env{'form.editdisc'}) {
 3322: 	  $symb=(split(/\:\:\:/,$env{'form.editdisc'}))[0];
 3323: 	  my ($map,$id,$url)=&Apache::lonnet::decode_symb($symb);
 3324: 	  $feedurl=&Apache::lonnet::clutter($url);
 3325:       } elsif ($env{'form.origpage'}) {
 3326: 	  $symb=""; 
 3327:       } else {
 3328: 	  $symb=&Apache::lonnet::symbread($feedurl);
 3329:       }
 3330:       unless ($symb) {
 3331: 	  $symb=$env{'form.symb'};
 3332: 	  if ($symb) {
 3333: 	      my ($map,$id,$url)=&Apache::lonnet::decode_symb($symb);
 3334: 	      $feedurl=&Apache::lonnet::clutter($url);
 3335: 	  }
 3336:       }
 3337:       &Apache::lonenc::check_decrypt(\$symb);
 3338:       my $goahead=1;
 3339:       if ($feedurl=~/\.(problem|exam|quiz|assess|survey|form|task)$/) {
 3340: 	  unless ($symb) { $goahead=0; }
 3341:       }
 3342:       # backward compatibility (bulletin boards used to be 'wrapped')
 3343:       &dewrapper(\$feedurl);
 3344:       if (!$goahead) {
 3345:           # Ambiguous Problem Resource
 3346: 	  $r->internal_redirect('/adm/ambiguous');
 3347: 	  return OK;
 3348:       }
 3349: # Go ahead with feedback, no ambiguous reference
 3350:       unless (
 3351: 	  (
 3352: 	   ($feedurl=~m:^/res:) && ($feedurl!~m:^/res/adm:)
 3353: 	   ) 
 3354: 	  || 
 3355: 	  ($env{'request.course.id'} && ($feedurl!~m:^/adm:))
 3356: 	  ||
 3357: 	  ($env{'request.course.id'} && ($symb=~/^bulletin\_\_\_/))
 3358: 	  ) {
 3359: 	  &Apache::loncommon::content_type($r,'text/html');
 3360: 	  $r->send_http_header;
 3361: # Unable to give feedback
 3362: 	  &no_redirect_back($r,$feedurl);
 3363: 	  return OK;
 3364:       }
 3365: # --------------------------------------------------- Print login screen header
 3366:       unless ($env{'form.sendit'}) {
 3367: 	  &Apache::loncommon::content_type($r,'text/html');
 3368: 	  $r->send_http_header;
 3369: 	  my $options=&screen_header($feedurl,$symb);
 3370: 	  if ($options) {
 3371: 	      &mail_screen($r,$feedurl,$options);
 3372: 	  } else {
 3373: 	      &fail_redirect($r,$feedurl);
 3374: 	  }
 3375: 	  return OK;
 3376:       }
 3377:       
 3378: # Get previous user input
 3379:       my $prevattempts=&Apache::loncommon::get_previous_attempt(
 3380:                                    $symb,$env{'user.name'},$env{'user.domain'},
 3381: 				   $env{'request.course.id'});
 3382: 
 3383: # Get output from resource
 3384:       my $usersaw=&resource_output($feedurl);
 3385: 
 3386: # Get resource answer (need to allow student to view grades for this to work)
 3387:       &Apache::lonnet::appenv(('allowed.vgr'=>'F'));
 3388:       my $useranswer=&Apache::loncommon::get_student_answers(
 3389:                                    $symb,$env{'user.name'},$env{'user.domain'},
 3390: 		                   $env{'request.course.id'});
 3391:       &Apache::lonnet::delenv('allowed.vgr');
 3392: # Get attachments, if any, and not too large
 3393:       my $attachmenturl='';
 3394:       if (($env{'form.origpage'}) || ($env{'form.editdisc'}) ||
 3395: 	  ($env{'form.replydisc'})) {
 3396: 	  my ($symb,$idx);
 3397: 	  if ($env{'form.replydisc'}) {
 3398: 	      ($symb,$idx)=split(/\:\:\:/,$env{'form.replydisc'});
 3399: 	  } elsif ($env{'form.editdisc'}) {
 3400: 	      ($symb,$idx)=split(/\:\:\:/,$env{'form.editdisc'});
 3401: 	  } elsif ($env{'form.origpage'}) {
 3402: 	      $symb = $env{'form.symb'};
 3403: 	  }
 3404: 	  &Apache::lonenc::check_decrypt(\$symb);
 3405: 	  my @currnewattach = ();
 3406: 	  my @deloldattach = ();
 3407: 	  my @keepold = ();
 3408: 	  &process_attachments(\@currnewattach,\@deloldattach,\@keepold);
 3409: 	  $symb=~s|(bulletin___\d+___)adm/wrapper/|$1|;
 3410: 	  $attachmenturl=&construct_attachmenturl(\@currnewattach,\@keepold,$symb,$idx);
 3411:       } elsif ($env{'form.attachment.filename'}) {
 3412: 	  unless (length($env{'form.attachment'})>131072) {
 3413: 	      $attachmenturl=&Apache::lonnet::userfileupload('attachment',undef,'feedback');
 3414: 	  }
 3415:       }
 3416: # Filter HTML out of message (could be nasty)
 3417:       my $message=&clear_out_html($env{'form.comment'});
 3418: 
 3419: # Assemble email
 3420:       my ($email,$citations)=&assemble_email($feedurl,$message,$prevattempts,
 3421: 					     $usersaw,$useranswer);
 3422:  
 3423: # Who gets this?
 3424:       my ($typestyle,%to) = &decide_receiver($feedurl);
 3425: 
 3426: # Actually send mail
 3427:       my ($status,$numsent)=&send_msg($feedurl,$email,$citations,
 3428: 				      $attachmenturl,%to);
 3429: 
 3430: # Discussion? Store that.
 3431: 
 3432:       my $numpost=0;
 3433:       if ($env{'form.discuss'} || $env{'form.anondiscuss'}) {
 3434: 	  my $subject = &clear_out_html($env{'form.subject'});
 3435: 	  my $anonmode=(defined($env{'form.anondiscuss'}));
 3436: 	  $typestyle.=&adddiscuss($symb,$message,$anonmode,$attachmenturl,
 3437: 				  $subject);
 3438: 	  $numpost++;
 3439:       }
 3440: 
 3441: # Add to blog?
 3442: 
 3443:       my $blog='';
 3444:       if ($env{'form.blog'}) {
 3445: 	  my $subject = &clear_out_html($env{'form.subject'});
 3446: 	  $status.=&Apache::lonrss::addentry($env{'user.name'},
 3447: 				    $env{'user.domain'},
 3448: 				    'CourseBlog_'.$env{'request.course.id'},
 3449: 				    $subject,$message,$feedurl,'public');
 3450: 	  $blog='<br />'.&mt('Added to my course blog').'<br />';
 3451:       }
 3452: 	  
 3453: # Receipt screen and redirect back to where came from
 3454:       &redirect_back($r,$feedurl,$typestyle,$numsent,$numpost,$blog,$status,$env{'form.previous'});
 3455:   }
 3456:   return OK;
 3457: } 
 3458: 
 3459: sub wrap_symb {
 3460:     my ($ressymb)=@_;
 3461:     if ($ressymb =~ /bulletin___\d+___/) {
 3462:         unless ($ressymb =~ m|bulletin___\d+___adm/wrapper|) {
 3463:             $ressymb=~s|(bulletin___\d+___)|$1adm/wrapper|;
 3464:         }
 3465:     }
 3466:     return $ressymb;
 3467: }
 3468: sub dewrapper {
 3469:     my ($feedurl)=@_;
 3470:     if ($$feedurl=~m|^/adm/wrapper/adm/.*/bulletinboard$|) {
 3471:         $$feedurl=~s|^/adm/wrapper||;
 3472:     }
 3473: }
 3474: 
 3475: sub get_feedurl {
 3476:     my ($symb)=@_;
 3477:     my ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);
 3478:     my $feedurl = &Apache::lonnet::clutter($url);
 3479:     &dewrapper(\$feedurl);
 3480:     return $feedurl;
 3481: }
 3482: 
 3483: sub get_feedurl_and_clean_symb {
 3484:     my ($symb)=@_;
 3485:     &Apache::lonenc::check_decrypt(\$symb);
 3486: # backward compatibility (bulletin boards used to be 'wrapped')
 3487:     unless ($symb =~ m|bulletin___\d+___adm/wrapper|) {
 3488: 	$symb=~s|(bulletin___\d+___)|$1adm/wrapper|;
 3489:     }
 3490:     my $feedurl = &get_feedurl($symb);
 3491:     return ($symb,$feedurl);
 3492: }
 3493: 
 3494: sub editing_allowed {
 3495:     my $can_edit = 0;
 3496:     my $cid = $env{'request.course.id'};
 3497:     my $role = (split(/\./,$env{'request.role'}))[0];
 3498:     my $section = $env{'request.course.sec'};
 3499:     my $allow_editing_config = $env{'course.'.$env{'request.course.id'}.
 3500:                                '.allow_discussion_post_editing'};
 3501:     if ($allow_editing_config =~ m/^\s*yes\s*$/i) {
 3502:         $can_edit = 1;
 3503:     } else {
 3504:         my @editor_roles = split(/,/,$allow_editing_config);
 3505:         if (@editor_roles > 0) {
 3506:             foreach my $editor (@editor_roles) {
 3507:                 my ($editor_role,$editor_sec) = split(/:/,$editor);
 3508:                 if ($editor_role eq $role) {
 3509:                     if (defined($editor_sec)) {
 3510:                         if (defined($section)) {
 3511:                             if ($editor_sec eq $section) {
 3512:                                 $can_edit = 1;
 3513:                                 last;
 3514:                             }
 3515:                         }
 3516:                     } else {
 3517:                         $can_edit = 1;
 3518:                         last;
 3519:                     }
 3520:                 }
 3521:             }
 3522:         }
 3523:     }
 3524:     return $can_edit;
 3525: }
 3526: 
 3527: 1;
 3528: __END__

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