File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.325: download - view: text, annotated - select for diffs
Fri Jan 6 19:18:11 2012 UTC (12 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Work on likes/unlikes

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

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