File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.290.2.2: download - view: text, annotated - select for diffs
Sat Aug 14 18:14:29 2010 UTC (13 years, 9 months ago) by raeburn
Branches: version_2_10_X
- Backport 1.294, 1.295, 1.296, 1.297, 1.298, 1.299.

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

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