File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.233: download - view: text, annotated - select for diffs
Fri Dec 8 22:35:56 2006 UTC (17 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
&check_encrypt() is needed in more places.  Work in progress.

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

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