File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.290.2.1: download - view: text, annotated - select for diffs
Thu May 27 14:34:41 2010 UTC (14 years ago) by raeburn
Branches: version_2_10_X
- Backport 1.292, 1.293.

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

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