File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.374: download - view: text, annotated - select for diffs
Fri Nov 3 21:36:27 2017 UTC (6 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Sanity checking.

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

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