File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.209: download - view: text, annotated - select for diffs
Tue Jul 18 17:20:32 2006 UTC (17 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- style

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

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