File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.273.4.9: download - view: text, annotated - select for diffs
Fri Aug 20 04:49:11 2010 UTC (13 years, 9 months ago) by raeburn
Branches: version_2_9_X
Diff to branchpoint 1.273: preferred, unified
- Backport 1.294, 1.298.

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

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