File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.293: download - view: text, annotated - select for diffs
Mon May 17 14:22:37 2010 UTC (14 years ago) by wenzelju
Branches: MAIN
CVS tags: HEAD
Consistent icon for feedback.

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

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