File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.370.2.5.2.2: download - view: text, annotated - select for diffs
Wed Jan 19 18:08:38 2022 UTC (2 years, 9 months ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.370.2.5: preferred, unified
- For 2.11.4 (modified)
  Include changes in 1.388, 1.389, 1.390

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

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