File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.282: download - view: text, annotated - select for diffs
Tue Dec 8 13:33:12 2009 UTC (14 years, 5 months ago) by wenzelju
Branches: MAIN
CVS tags: HEAD, GCI_3
Changes for XHTML 1.0 transitional conformity.

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

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