File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.221: download - view: text, annotated - select for diffs
Wed Nov 29 03:55:15 2006 UTC (17 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Eliminate $_

Style - push() keys() sort() split()

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

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