File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.306: download - view: text, annotated - select for diffs
Sat Dec 10 01:45:36 2011 UTC (12 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Saving my work: Bug 2359

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

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