File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.256: download - view: text, annotated - select for diffs
Tue Nov 18 19:14:22 2008 UTC (15 years, 6 months ago) by jms
Branches: MAIN
CVS tags: HEAD
Added/updated/converted POD. Many files had their POD redone to new standards.

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

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