File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.273.4.7: download - view: text, annotated - select for diffs
Mon Jan 25 04:34:37 2010 UTC (14 years, 4 months ago) by raeburn
Branches: version_2_9_X
Diff to branchpoint 1.273: preferred, unified
- Backport 1.283, 1.284, 1.285.

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

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