File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.208: download - view: text, annotated - select for diffs
Mon Jul 17 23:02:33 2006 UTC (17 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Access to edit/hide/delete functionality in discussions in group bulletin boards dependent on group privileges.  Breadcrumbs include link back to all grups list when discussion was accessed via 'Groups' link.  For both bulletin boards and discussion attached to resources, filtered display of posts can now be based on group affiliation. For users with mdg or vcg privileges in the course, selection is from all groups, for others selection is from user's own active groups.

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

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