File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.273.4.3: download - view: text, annotated - select for diffs
Sun Jan 24 03:13:55 2010 UTC (14 years, 4 months ago) by raeburn
Branches: version_2_9_X
Diff to branchpoint 1.273: preferred, unified
- Backport 1.279.

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

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