File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.286: download - view: text, annotated - select for diffs
Sun Jan 24 19:58:24 2010 UTC (14 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Simplify regexp in &contains_block_html().
- Coding style - indentation in &contains_block_html().
- Use &contains_block_html() to eliminate unwanted <br /> in display
  of discussion posts composed in Rich Text Editor.
- On post composition page decode() encoded HTML when displaying post
  to which user is replying.

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

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