File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.295: download - view: text, annotated - select for diffs
Sat Jun 5 22:07:05 2010 UTC (14 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #6162: some unused phrases in printouts of discussions

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

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