File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.326: download - view: text, annotated - select for diffs
Fri Jan 6 20:05:59 2012 UTC (12 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Like/unlike working

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

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