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

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

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