File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.273.4.12: download - view: text, annotated - select for diffs
Sat Nov 20 01:33:04 2010 UTC (13 years, 6 months ago) by raeburn
Branches: version_2_9_X
CVS tags: version_2_9_1
Diff to branchpoint 1.273: preferred, unified
- Backport 1.303, 1.304.

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

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