File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.223: download - view: text, annotated - select for diffs
Wed Nov 29 19:31:48 2006 UTC (17 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Can set blocking of posting to discussion boards in a course, and to a user's course blog via FDBK.

More concise use of &mt() for internationalization.

Ignore the duplication of message in disnew() and disfolder(), for now, because disnew()'s days are numbered.

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

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