File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.348: download - view: text, annotated - select for diffs
Sat Mar 17 02:55:15 2012 UTC (12 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Fix name of routine in call included in 1.347.

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

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