File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.346: download - view: text, annotated - select for diffs
Fri Mar 16 02:59:01 2012 UTC (12 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- $group is set to $env{'form.group'} early in &handler() so use it.

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

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