File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.231: download - view: text, annotated - select for diffs
Fri Dec 8 00:28:59 2006 UTC (17 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Bugs 1402 and 4309.

When a discussion posting is hidden or deleted, if that post was the last discussion item, then the entry in discussiontimes.db for the resource is set back to the timestamp of the most recent unhidden or undeleted post.

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

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