File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.294: download - view: text, annotated - select for diffs
Wed Jun 2 14:11:15 2010 UTC (13 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #5435: discussend overrides problem open status.

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

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