File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.290.2.7.2.5: download - view: text, annotated - select for diffs
Tue May 1 15:56:16 2012 UTC (12 years ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.290.2.7: preferred, unified
- Customization for MITrelate.
  - Correction to backports in 1.290.2.7.2.4.

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

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