File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.142: download - view: text, annotated - select for diffs
Fri Nov 19 19:43:05 2004 UTC (19 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- er typo?

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

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