File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.219: download - view: text, annotated - select for diffs
Tue Nov 28 22:27:56 2006 UTC (17 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
bug 3872.  Deleting a post now requires clicking a confirm button in the case where a user deletes his/her own post, and when a CC deletes another user's post.

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

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