File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.308: download - view: text, annotated - select for diffs
Sat Dec 10 23:16:36 2011 UTC (12 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #2359: modal windows for feedback

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

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