File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.269: download - view: text, annotated - select for diffs
Sat Apr 4 21:47:40 2009 UTC (15 years, 2 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
XHTML conform tags (input, br, hr)

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

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