File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.393: download - view: text, annotated - select for diffs
Fri Sep 15 23:00:16 2023 UTC (8 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Bug 6929

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

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