File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.298: download - view: text, annotated - select for diffs
Sat Aug 14 15:24:46 2010 UTC (13 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Consistent format for "This discussion is closed".
- If user has advanced role, include not to indicate that discussion is closed for
  non-advanced roles.

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

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