File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.341: download - view: text, annotated - select for diffs
Thu Mar 15 13:27:25 2012 UTC (12 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Reinstating changes in 1.336, 1.337, 1.338 & 1.339 which were removed in 1.340.

    1: # The LearningOnline Network
    2: # Feedback
    3: #
    4: # $Id: lonfeedback.pm,v 1.341 2012/03/15 13:27:25 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:                         if ($showonlyunread && $prevread > $posttime) {
 1337:                             $$notshown{$idx} = 1;
 1338:                         } elsif ($showunmark && $$dischash{$readkey}=~/\.$idx\./) {
 1339:                             $$notshown{$idx} = 1;
 1340:                         } else {
 1341: # apply filters
 1342:                             my $uname = $contrib{$idx.':sendername'};
 1343:                             my $udom = $contrib{$idx.':senderdomain'};
 1344:                             my $poster = $uname.':'.$udom;
 1345:                             if ($env{'form.totposters'} ne '') {
 1346:                                 if ($totposters == 0) {
 1347:                                     $$shown{$idx} = 0;
 1348:                                 } elsif ($totposters > 0) {
 1349:                                     if (grep/^$poster$/,@{$posters}) {
 1350:                                         $$shown{$idx} = 1;
 1351:                                     }
 1352:                                 }
 1353:                             } elsif ($sortposts) {
 1354:                                 if ($skiptest) {
 1355:                                     $$shown{$idx} = 1;
 1356:                                 } else {
 1357:                                     foreach my $role (@{$$roleinfo{$poster}}) {
 1358:                                         if ($role =~ /^cc:/) {
 1359:                                             my $cc_regexp = $roleregexp.':[^:]*:'.$statusregexp;
 1360:                                             if ($role =~ /$cc_regexp/) {
 1361:                                                 $$shown{$idx} = 1;
 1362:                                                 last;
 1363:                                             }
 1364:                                         } elsif ($role =~ /^$rolematch$/) {
 1365:                                             $$shown{$idx} = 1;
 1366:                                             last;
 1367:                                         }
 1368:                                     }
 1369:                                 }
 1370:                                 if ($$shown{$idx} && !$skip_group_check) {
 1371:                                     my $showflag = 0;
 1372:                                     if (ref($$classgroups{$poster}{active}) eq 'HASH') {
 1373:                                         foreach my $grp (@{$grouppick}) {
 1374:                                             if (grep/^\Q$grp\E$/,
 1375:                                  keys(%{$$classgroups{$poster}{active}})) {
 1376:                                                 $showflag = 1;
 1377:                                                 last;
 1378:                                             }
 1379:                                         }
 1380:                                     }
 1381:                                     if ($showflag) {
 1382:                                         $$shown{$idx} = 1;
 1383:                                     } else {
 1384:                                         $$shown{$idx} = 0;
 1385:                                     }
 1386:                                 }
 1387:                             } else {
 1388:                                 $$shown{$idx} = 1;
 1389:                             }
 1390:                         }
 1391:                         unless ($$notshown{$idx} == 1) {
 1392:                             if ($prevread > 0 && $prevread <= $posttime) {
 1393:                                 $$newitem{$idx} = 1;
 1394:                                 $$discussionitems[$idx] .= '<font color="#FF0000"><b>'.&mt('NEW').'&nbsp;&nbsp;</b></font>';
 1395:                             } else {
 1396:                                 $$newitem{$idx} = 0;
 1397:                             }
 1398:                             $$discussionitems[$idx] .= '<b>'.$subject.'</b>&nbsp;&nbsp;'.
 1399:                                 $sender.' '.$vgrlink.' ('.
 1400:                                 &Apache::lonlocal::locallocaltime($posttime).')';
 1401:                             if ($$dischash{$toggkey}) {
 1402:                                 $$discussionitems[$idx].='&nbsp;&nbsp;'.$ctlink;
 1403:                             }
 1404:                             my $thislikes=$likes{$symb.':'.$idx.':likes'};
 1405:                             my $likesize="100";
 1406:                             if ($seeid || $canvote) {
 1407: # Figure out size based on likes
 1408:                                 my $thislikes=$likes{$symb.':'.$idx.':likes'};
 1409:                                 if ($thislikes>$twoplus) {
 1410:                                     $likesize="200";
 1411:                                 } elsif ($thislikes>$oneplus) {
 1412:                                     $likesize="150";
 1413:                                 }
 1414:                                 if ($thislikes<$twominus) {
 1415:                                     $likesize="50";
 1416:                                 } elsif ($thislikes<$oneminus) {
 1417:                                     $likesize="75";
 1418:                                 }
 1419:                             }
 1420: # Actually glue in the message itself
 1421:                             $$discussionitems[$idx].= '<br /><blockquote>'.
 1422:                                     "<div style='font-size:$likesize%'>".
 1423:                                     $message.
 1424:                                     '</div></blockquote>';
 1425:                             if ($canvote) {
 1426: # Put in the like and unlike buttons
 1427:                                 if ($userlikes{$idx}) {
 1428:                                     $$discussionitems[$idx].='<img border="0" src="/res/adm/pages/thumbsup_gray.png" alt="'.&mt('You like this posting').'" />';
 1429:                                 } else {
 1430:                                     $$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"));
 1431:                                 }
 1432:                                 if ($userunlikes{$idx}) {
 1433:                                     $$discussionitems[$idx].='<img border="0" src="/res/adm/pages/thumbsdown_gray.png" alt="'.&mt('You unlike this posting').'" />';
 1434:                                 } else {
 1435:                                     $$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"));
 1436:                                 }
 1437:                             }
 1438:                             if ($seeid || $canvote) {
 1439:                                 my $thislikes=$likes{$symb.':'.$idx.':likes'};
 1440:                                 if ($thislikes>0) {
 1441:                                     $$discussionitems[$idx].='&nbsp;('.&mt("[_1] likes",$thislikes).')';
 1442:                                 } elsif ($thislikes<0) {
 1443:                                     $$discussionitems[$idx].='&nbsp;('.&mt("[_1] unlikes",abs($thislikes)).')';
 1444:                                 }
 1445:                             }
 1446: # If there is any history to this post, inform the reader
 1447:                             if ($contrib{$idx.':history'}) {
 1448:                                 my @postversions = ();
 1449:                                 $$discussionitems[$idx] .= '&nbsp;&nbsp;'.&mt('This post has been edited by the author.');
 1450:                                 if ($seeid) {
 1451:                                     $$discussionitems[$idx] .= '&nbsp;&nbsp;'.
 1452:                                          &discussion_link($symb,&mt('Display all versions'),'allversions',$idx,$$newpostsflag,$prevread,&group_args($group));
 1453:                                 }
 1454:                                 $$discussionitems[$idx].='<br/>'.&mt('Earlier version(s) were posted on: ');
 1455:                                 if ($contrib{$idx.':history'} =~ m/:/) {
 1456:                                     @postversions = split(/:/,$contrib{$idx.':history'});
 1457:                                 } else {
 1458:                                     @postversions = ("$contrib{$idx.':history'}");
 1459:                                 }
 1460:                                 for (my $i=0; $i<@postversions; $i++) {
 1461:                                     my $version = $i+1;
 1462:                                     $$discussionitems[$idx] .= '<b>'.$version.'.</b> - '.&Apache::lonlocal::locallocaltime($postversions[$i]).'  ';
 1463:                                 }
 1464:                             }
 1465: # end of unless ($$notshown ...)
 1466:                         }
 1467: # end of if ($message) ...
 1468:                     }
 1469: # end of the else-branch of target being export
 1470:                 }
 1471: # end of unless hidden or deleted
 1472:             }
 1473: # end of the loop over all discussion entries
 1474: 	}
 1475: # end of "if there actually are any discussions
 1476:     }
 1477: # end of subroutine "build_posting_display" 
 1478: }
 1479: 
 1480: sub filter_regexp {
 1481:     my ($rolefilter,$sectionpick,$statusfilter) = @_;
 1482:     my ($roleregexp,$secregexp,$statusregexp);
 1483:     my $skiptest = 1;
 1484:     if (@{$rolefilter} > 0) {
 1485:         my @okrolefilter = ();
 1486:         foreach my $role (@{$rolefilter}) {
 1487:             unless ($role eq '') {
 1488:                 push(@okrolefilter, $role);
 1489:             }
 1490:         }
 1491:         if (@okrolefilter > 0) {
 1492:             if (grep/^all$/,@okrolefilter) {
 1493:                 $roleregexp='[^:]+';
 1494:             } else {
 1495:                 if (@okrolefilter == 1) {
 1496:                     $roleregexp=$okrolefilter[0];
 1497:                 } else {
 1498:                     $roleregexp='('.join('|',@okrolefilter).')';
 1499:                 }
 1500:                 $skiptest = 0;
 1501:             }
 1502:         }
 1503:     }
 1504:     if (@{$sectionpick} > 0) {
 1505:         my @oksectionpick = ();
 1506:         foreach my $sec (@{$sectionpick}) {
 1507:             unless ($sec eq '') {
 1508:                  push(@oksectionpick, $sec);
 1509:             }
 1510:         }
 1511:         if ((@oksectionpick > 0) && (!grep/^all$/,@oksectionpick)) {
 1512:             if (@oksectionpick == 1) {
 1513:                 $secregexp = $oksectionpick[0];
 1514:             } else {
 1515:                 $secregexp .= '('.join('|',@oksectionpick).')';
 1516:             }
 1517:             $skiptest = 0;
 1518:         } else {
 1519:             $secregexp .= '[^:]*';
 1520:         }
 1521:     }
 1522: 
 1523:     if (defined($statusfilter) && $statusfilter ne '') {
 1524:         if ($statusfilter eq 'all') {
 1525:             $statusregexp = '[^:]+';
 1526:         } else {
 1527:             $statusregexp = $statusfilter;
 1528:             $skiptest = 0;
 1529:         }
 1530:     }
 1531:     return ($skiptest,$roleregexp,$secregexp,$statusregexp);
 1532: }
 1533: 
 1534: 
 1535: sub get_post_contents {
 1536:     my ($contrib,$idx,$seeid,$type,$messages,$subjects,$allattachments,$attachtxt,$imsfiles,$screenname,$plainname,$showaboutme,$numver) = @_;
 1537:     my $discussion = '';
 1538:     my $start=$numver;
 1539:     my $end=$numver + 1;
 1540:     %{$$imsfiles{$idx}}=();
 1541:     if ($type eq 'allversions') {
 1542:        unless($seeid) {
 1543:            $discussion=&mt('You do not have privileges to view all versions of posts.').' '.&mt('Please select a different role.');
 1544:            return $discussion;
 1545:        } 
 1546:     }
 1547: #    $$screenname=&Apache::loncommon::screenname(
 1548: #                                        $$contrib{$idx.':sendername'},
 1549: #                                        $$contrib{$idx.':senderdomain'});
 1550:     $$plainname=&Apache::loncommon::nickname(
 1551:                                         $$contrib{$idx.':sendername'},
 1552:                                         $$contrib{$idx.':senderdomain'});
 1553:     $$screenname=$$contrib{$idx.':screenname'};
 1554:     $$showaboutme = &Apache::lonnet::usertools_access($$contrib{$idx.':sendername'},
 1555:                                                       $$contrib{$idx.':senderdomain'},
 1556:                                                       'aboutme');
 1557:     my $sender = $$plainname;
 1558:     if ($$showaboutme) {
 1559:         $sender = &Apache::loncommon::aboutmewrapper(
 1560:                                  $$plainname,
 1561:                                  $$contrib{$idx.':sendername'},
 1562:                                  $$contrib{$idx.':senderdomain'});
 1563:     }
 1564:     if ($seeid) {
 1565:         $sender .= ' ('.$$contrib{$idx.':sendername'}.':'.
 1566:                    $$contrib{$idx.':senderdomain'}.')';
 1567:     }
 1568:     my $attachmenturls = $$contrib{$idx.':attachmenturl'};
 1569:     my @postversions = ();
 1570:     if ($type eq 'allversions' || $type eq 'export') {
 1571:         $start = 0;
 1572:         if ($$contrib{$idx.':history'}) {
 1573: 	    @postversions = split(/:/,$$contrib{$idx.':history'});
 1574:         }
 1575:         &get_post_versions($messages,$$contrib{$idx.':message'},1);
 1576:         &get_post_versions($subjects,$$contrib{$idx.':subject'},1);
 1577:         push(@postversions,$$contrib{$idx.':timestamp'});
 1578:         $end = @postversions;
 1579:     } else {
 1580:         &get_post_versions($messages,$$contrib{$idx.':message'},1,$numver);
 1581:         &get_post_versions($subjects,$$contrib{$idx.':subject'},1,$numver);
 1582:     }
 1583: 
 1584:     if ($$contrib{$idx.':anonymous'}) {
 1585:         $sender.=' ['.&mt('anonymous').'] '.$$screenname;
 1586:     }
 1587:     if ($type eq 'allversions') {
 1588:         $discussion=('<b>'.$sender.'</b><br /><ul>');
 1589:     }
 1590:     for (my $i=$start; $i<$end; $i++) {
 1591:         my ($timesent,$attachmsg);
 1592:         my %currattach = ();
 1593:         $timesent = &Apache::lonlocal::locallocaltime($postversions[$i]);
 1594:         unless (&contains_block_html($messages->{$i})) {
 1595:             &newline_to_br(\$messages->{$i});
 1596:         }
 1597:         $$messages{$i}=&Apache::lontexconvert::msgtexconverted($$messages{$i});
 1598:         $$subjects{$i}=~s/\n/\<br \/\>/g;
 1599:         $$subjects{$i}=&Apache::lontexconvert::msgtexconverted($$subjects{$i});
 1600:         if ($attachmenturls) {
 1601:             &extract_attachments($attachmenturls,$idx,$i,\$attachmsg,$allattachments,\%currattach);
 1602:         }
 1603:         if ($type eq 'export') {
 1604:             $$imsfiles{$idx}{$i} = '';
 1605:             if ($attachmsg) {
 1606:                 $$attachtxt{$i} = '<br />'.&mt('Attachments').':<br />';
 1607:                 foreach my $key (sort(keys(%currattach))) {
 1608:                     if ($$allattachments{$key}{'filename'} =~ m-^/uploaded/([^/]+/[^/]+)(/feedback)?(/?\d*)/([^/]+)$-) {
 1609:                         my $fname = $1.$3.'/'.$4;
 1610:                         $$imsfiles{$idx}{$i} .= '<file href="'.$fname.'" />'."\n";
 1611:                         $$attachtxt{$i}.= '<a href="'.$fname.'">'.$4.'</a><br />';
 1612:                     }
 1613:                 }
 1614:             }
 1615:         } else {
 1616:             if ($attachmsg) {
 1617:                 $$attachtxt{$i} = '<br />'.&mt('Attachments').':'.$attachmsg.'<br />';
 1618:             } else {
 1619:                 $$attachtxt{$i} = '';
 1620:             }
 1621:         }
 1622:         if ($type eq 'allversions') {
 1623:             $discussion.= <<"END";
 1624: <li><b>$$subjects{$i}</b>, $timesent<br />
 1625: $$messages{$i}<br />
 1626: $$attachtxt{$i}</li>
 1627: END
 1628:         }
 1629:     }
 1630:     if ($type eq 'allversions') {
 1631:         $discussion.='</ul>';
 1632:         return $discussion;
 1633:     } else {
 1634:         return;
 1635:     }
 1636: }
 1637: 
 1638: sub replicate_attachments {
 1639:     my ($attachrefs,$tempexport) = @_;
 1640:     my $response;
 1641:     foreach my $id (keys(%{$attachrefs})) {
 1642:         if ($$attachrefs{$id}{'filename'} =~ m-^/uploaded/([^/]+)/([^/]+)(/feedback)?(/?\d*)/([^/]+)$-) {
 1643:             my $path = $tempexport;
 1644:             my $tail = $1.'/'.$2.$4;
 1645:             my @extras = split(/\//,$tail);
 1646:             my $destination = $tempexport.'/'.$1.'/'.$2.$4.'/'.$5;
 1647:             if (!-e $destination) {
 1648:                 my $i= 0;
 1649:                 while ($i<@extras) {
 1650:                     $path .= '/'.$extras[$i];
 1651:                     if (!-e $path) {
 1652:                         mkdir($path,0700);
 1653:                     }
 1654:                     $i ++;
 1655:                 }
 1656:                 my ($content,$rtncode);
 1657:                 my $uploadreply = &Apache::lonnet::getuploaded('GET',$$attachrefs{$id}{'filename'},$1,$2,$content,$rtncode);
 1658:                 if ($uploadreply eq 'ok') {
 1659:                     my $attachcopy;
 1660:                     if ($attachcopy = Apache::File->new('>'.$destination)) {
 1661:                         print $attachcopy $content;
 1662:                         close($attachcopy);
 1663:                     } else {
 1664:                         $response .= &mt('Error copying file attachment - [_1] to IMS package',$5).': '.$!.'<br />'."\n";
 1665:                     }
 1666:                 } else {
 1667:                     &Apache::lonnet::logthis("Replication of attachment failed when building IMS export of discussion posts - domain: $1, course: $2, file: $$attachrefs{$id}{'filename'} -error: $rtncode");
 1668:                     $response .= &mt('Error copying file attachment - [_1] to IMS package: ',$5).$rtncode.'<br />'."\n";
 1669:                 }
 1670:             }
 1671:         }
 1672:     }
 1673:     return $response;
 1674: }
 1675: 
 1676: sub mail_screen {
 1677:   my ($r,$feedurl,$options,$caller_symb,$attachmaxtext) = @_;
 1678:   if (exists($env{'form.origpage'})) {
 1679:       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['subject','comment','currnewattach','addnewattach','deloldattach','delnewattach','timestamp','idx','anondiscuss','discuss','blog','group','ref']);
 1680:   }
 1681: 
 1682:   my %lt = &Apache::lonlocal::texthash(
 1683:             'myqu' => 'Question/comment/feedback:',
 1684:             'title' => 'Title',
 1685:             'reta' => 'Retained attachments',
 1686:             'atta' => 'Attachment',
 1687:            );
 1688:   if($env{'form.editdisc'} || $env{'form.replydisc'}){
 1689:     %lt = &Apache::lonlocal::texthash(
 1690:             'myqu' => 'Post Discussion',
 1691:     );
 1692:   }
 1693:   my $restitle = &get_resource_title($caller_symb,$feedurl);
 1694:   my $quote='';
 1695:   my $subject = '';
 1696:   my $comment = '';
 1697:   my $prevtag = '';
 1698:   my $parentmsg = '';
 1699:   my ($symb,$idx,$attachmenturls);
 1700:   my $numoldver = 0;
 1701:   my $attachmsg = '';
 1702:   my $newattachmsg = '';
 1703:   my @currnewattach = ();
 1704:   my @currdelold = ();
 1705:   my @keepold = ();
 1706:   my %attachments = ();
 1707:   my %currattach = ();
 1708:   my $attachnum = 0;
 1709:   my $anonchk = (<<END);
 1710:   function anonchk() {
 1711:       for (var i=0; i < document.mailform.discuss.length; i++) {
 1712: 	  if (document.mailform.discuss[i].checked) {
 1713: 	      document.attachment.discuss.value = 
 1714: 		  document.mailform.discuss[i].value;
 1715: 	  }
 1716:       }
 1717:       if (document.mailform.blog.checked) {
 1718: 	  document.attachment.blog.value = 1;
 1719:       }
 1720:      return
 1721:    }
 1722: END
 1723:   my $anonscript;
 1724:   if (exists($env{'form.origpage'})) {
 1725:       $anonscript = (<<END);
 1726:   function setposttype() {
 1727:       var disc = "$env{'form.discuss'}";
 1728:       for (var i=0; i < document.mailform.discuss.length; i++) {
 1729: 	  if (disc == document.mailform.discuss[i].value) {
 1730: 	      document.mailform.discuss[i].checked = 1;
 1731: 	  }
 1732:       }
 1733:       var blog = "$env{'form.blog'}";
 1734:       if (blog == 1) {
 1735:           document.mailform.blog.checked=1;
 1736:       }
 1737:       return
 1738:   }
 1739: END
 1740:   } else {
 1741:       $anonscript = (<<END);
 1742:   function setposttype() {
 1743:       return
 1744:   }
 1745: END
 1746:   }
 1747:   if (($env{'form.replydisc'}) || ($env{'form.editdisc'})) {
 1748:       if ($env{'form.replydisc'}) {
 1749:           ($symb,$idx)=split(/\:\:\:/,$env{'form.replydisc'});
 1750:       } else {
 1751:           ($symb,$idx)=split(/\:\:\:/,$env{'form.editdisc'});
 1752:       }
 1753:       my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 1754: 					   $env{'course.'.$env{'request.course.id'}.'.domain'},
 1755: 					   $env{'course.'.$env{'request.course.id'}.'.num'});
 1756:       unless (($contrib{'hidden'}=~/\.$idx\./) || ($contrib{'deleted'}=~/\.$idx\./)) {
 1757:           if ($contrib{$idx.':history'}) {
 1758:               if ($contrib{$idx.':history'} =~ /:/) {
 1759:                   my @oldversions = split(/:/,$contrib{$idx.':history'});
 1760:                   $numoldver = @oldversions;
 1761:               } else {
 1762:                   $numoldver = 1;
 1763:               }
 1764:           }
 1765:           if ($env{'form.replydisc'}) {
 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 ($idx > 0) {
 1775:                   my %msgversions = ();
 1776:                   &get_post_versions(\%msgversions,$contrib{$idx.':message'},0,$numoldver);
 1777:                   $quote = $msgversions{$numoldver};
 1778:               }
 1779:               if ($idx > 0) {
 1780:                   my %subversions = ();
 1781:                   &get_post_versions(\%subversions,$contrib{$idx.':subject'},1,$numoldver);
 1782:                   $subject = &mt('Re: ').$subversions{$numoldver};
 1783:               }
 1784:               $subject = &HTML::Entities::encode($subject,'<>&"');
 1785:           } else {
 1786:               $attachmenturls = $contrib{$idx.':attachmenturl'};
 1787:               if ($idx > 0) {
 1788:                   my %msgversions = ();
 1789:                   &get_post_versions(\%msgversions,$contrib{$idx.':message'},0,$numoldver);
 1790:                   $comment = $msgversions{$numoldver};
 1791:                   my %subversions = ();
 1792:                   &get_post_versions(\%subversions,$contrib{$idx.':subject'},0,$numoldver);
 1793:                   $subject = $subversions{$numoldver}; 
 1794:               }
 1795:               if (defined($contrib{$idx.':replyto'})) {
 1796:                   $parentmsg = $contrib{$idx.':replyto'};
 1797:               }
 1798:               unless (exists($env{'form.origpage'})) {
 1799:                   my $anonflag = 'nonanon';
 1800:                   if ($contrib{$idx.':anonymous'}) {
 1801:                       $anonflag = 'anon';
 1802:                   }
 1803:                   $anonscript = (<<END);
 1804:   function setposttype () {
 1805:       var currtype = "$anonflag";
 1806:       for (var i=0; i<document.mailform.discuss.length; i++) {
 1807: 	  if (document.mailform.elements.discuss[i].value == currtype ) {
 1808: 	      document.mailform.elements.discuss[i].checked=1;
 1809: 	  } 
 1810:       }
 1811:       return
 1812:   }
 1813: END
 1814:               }
 1815:           }
 1816:       }
 1817:       if ($env{'form.previous'}) {
 1818:           $prevtag = '<input type="hidden" name="previous" value="'.$env{'form.previous'}.'" />';
 1819:       }
 1820:   }
 1821: 
 1822:   if ($env{'form.origpage'}) {
 1823:       $subject = &unescape($env{'form.subject'});
 1824:       $comment = &unescape($env{'form.comment'});
 1825:       &process_attachments(\@currnewattach,\@currdelold,\@keepold);
 1826:   }
 1827:   my $latexHelp=&Apache::loncommon::helpLatexCheatsheet(undef,undef,1,($env{'form.modal'}?'popup':0));
 1828:   my $send=&mt('Send');
 1829:   my $alert = &mt('Please select a feedback type.');
 1830:   my $js= <<END;
 1831: <script type="text/javascript">
 1832: //<!--
 1833:     function gosubmit() {
 1834:         var rec=0;
 1835:         if (typeof(document.mailform.elements.discuss)!="undefined") {
 1836: 	    if (typeof(document.mailform.elements.discuss.length) == "undefined") {
 1837: 		if (document.mailform.elements.discuss.checked ) {
 1838: 		    rec=1;
 1839: 		}
 1840: 	    } else {
 1841: 		for (var i=0; i<document.mailform.elements.discuss.length; i++) {
 1842: 		    if (document.mailform.elements.discuss[i].checked ) {
 1843: 			rec=1;
 1844: 		    } 
 1845: 		}
 1846: 	    }
 1847: 	}
 1848:         if (typeof(document.mailform.elements.blog)!="undefined") {
 1849:           if (document.mailform.elements.blog.checked) {
 1850:              rec=1;
 1851:           } 
 1852:         }
 1853: 
 1854:         if (rec) {
 1855:             if (typeof(document.mailform.onsubmit)=='function') {
 1856: 		document.mailform.onsubmit();
 1857: 	    }
 1858: 	    document.mailform.submit();
 1859:         } else {
 1860:             alert('$alert');
 1861: 	}
 1862:     }
 1863:     $anonchk
 1864:     $anonscript
 1865: //-->
 1866: </script>
 1867: END
 1868: 
 1869:   my ($textareaheader,$textareaclass);
 1870:   if (&Apache::lonhtmlcommon::htmlareabrowser()) {
 1871:       $textareaheader = &Apache::lonhtmlcommon::htmlareaselectactive();
 1872:       $textareaclass = 'class="LC_richDefaultOff"';
 1873:       if ($env{'request.course.id'}) {
 1874:           unless (($env{'course.'.$env{'request.course.id'}.'.allow_limited_html_in_feedback'} =~ /^\s*yes\s*$/i) || ($env{'form.sendmessageonly'})) {
 1875:               undef($textareaclass);
 1876:           }
 1877:       }
 1878:   }
 1879: 
 1880:   # Breadcrumbs
 1881:   my $brcrum = [{'href' => '',
 1882:                  'text' => 'Resource Feedback and Discussion'}];
 1883: 
 1884:   my %onload = ('onload' => 'window.focus();setposttype();');
 1885:   my %parms=('add_entries' => \%onload);
 1886:   if ($env{'form.modal'} ne 'yes') { 'bread_crumbs' => $brcrum }
 1887:   my $start_page=
 1888:       &Apache::loncommon::start_page('Resource Feedback and Discussion',$js,\%parms);
 1889: 
 1890:   if ($quote ne '') {
 1891:       $quote = &HTML::Entities::decode($quote);
 1892:       unless (&contains_block_html($quote)) {
 1893:           &newline_to_br(\$quote);
 1894:       }
 1895:       $quote='<blockquote>'.&Apache::lontexconvert::msgtexconverted($quote).'</blockquote>';
 1896:   }
 1897:   my $header='';
 1898:   unless ($env{'form.modal'}) {
 1899:      $header="<h2><tt>$restitle</tt></h2>";
 1900:   }
 1901:   $r->print(<<END);
 1902: $start_page
 1903: <h1>$lt{'myqu'}</h1>
 1904: $header
 1905: <form action="/adm/feedback" method="post" name="mailform"
 1906: enctype="multipart/form-data">
 1907: $prevtag
 1908: <input type="hidden" name="postdata" value="$feedurl" />
 1909: <input type="hidden" name="modal" value="$env{'form.modal'}" />
 1910: END
 1911:   if ($env{'form.replydisc'}) {
 1912:       $r->print(<<END);
 1913: <input type="hidden" name="replydisc" value="$env{'form.replydisc'}" />
 1914: END
 1915:   } elsif ($env{'form.editdisc'}) {
 1916:      $r->print(<<END);
 1917: <input type="hidden" name="editdisc" value="$env{'form.editdisc'}" />
 1918: <input type="hidden" name="parentmsg" value="$parentmsg" />
 1919: END
 1920:   }
 1921:   $r->print(<<END);
 1922: $options
 1923: $quote
 1924: <p>
 1925: $textareaheader
 1926: </p>
 1927: <br>
 1928: <p>
 1929: $latexHelp
 1930: </p>
 1931: <p>
 1932: END
 1933: 
 1934: $r->print(&Apache::lonhtmlcommon::start_pick_box());
 1935: $r->print(&Apache::lonhtmlcommon::row_title(&mt('Subject')));
 1936: $r->print('<input type="text" name="subject" size="30" value="'."$subject".'" /></p>');
 1937: $r->print(&Apache::lonhtmlcommon::row_closure());
 1938: $r->print(&Apache::lonhtmlcommon::row_title(&mt('Message')));
 1939: $r->print('<textarea name="comment" id="comment" cols="60" rows="10" $textareaclass>'."$comment".
 1940: '</textarea>');
 1941: $r->print(&Apache::lonhtmlcommon::row_closure(1));
 1942: $r->print(&Apache::lonhtmlcommon::end_pick_box());
 1943: 
 1944:     if ( ($env{'form.editdisc'}) || ($env{'form.replydisc'}) ) {
 1945:         if ($env{'form.origpage'}) {
 1946:             foreach my $attach (@currnewattach) {
 1947:                 $r->print('<input type="hidden" name="currnewattach" value="'.$attach.'" />'."\n");
 1948:             }
 1949:             foreach my $oldatt (@currdelold) {
 1950:                 $r->print('<input type="hidden" name="deloldattach" value="'.$oldatt.'" />'."\n");
 1951:             }
 1952:         }
 1953:         if ($env{'form.editdisc'}) {
 1954:             if ($attachmenturls) {
 1955:                 &extract_attachments($attachmenturls,$idx,$numoldver,\$attachmsg,\%attachments,\%currattach,\@currdelold);
 1956:                 $attachnum = scalar(keys(%currattach));
 1957:                 foreach my $key (keys(%currattach)) {
 1958:                     $r->print('<input type="hidden" name="keepold" value="'.$key.'" />'."\n");
 1959:                 }
 1960:             }
 1961:         }
 1962:     } else {
 1963:         $r->print(<<END);
 1964: <p>
 1965: $lt{'atta'} $attachmaxtext: <input type="file" name="attachment" />
 1966: </p>
 1967: END
 1968:     }
 1969:     if (exists($env{'form.group'})) {
 1970:         $r->print('<input type="hidden" name="group" value="'.$env{'form.group'}.'" />');
 1971:     }
 1972:     if (exists($env{'form.ref'})) {
 1973:         $r->print('<input type="hidden" name="ref" value="'.$env{'form.ref'}.'" />');
 1974:     }
 1975:     $r->print(<<END);
 1976: <p>
 1977: <input type="hidden" name="sendit" value="1" />
 1978: <input type="button" value="$send" onclick='gosubmit();' />
 1979: </p>
 1980: </form>
 1981: END
 1982:     if ($env{'form.editdisc'} || $env{'form.replydisc'}) {
 1983:         my $now = time;
 1984:         my $ressymb = $symb;
 1985:         &Apache::lonenc::check_encrypt(\$ressymb);
 1986:         my $postidx = '';
 1987:         if ($env{'form.editdisc'}) {
 1988:             $postidx = $idx;
 1989:         }
 1990:         if (@currnewattach > 0) {
 1991:             $attachnum += @currnewattach;
 1992:         }
 1993:         my $blockblog = &Apache::loncommon::blocking_status('blogs');
 1994:         $r->print(&generate_attachments_button($postidx,$attachnum,$ressymb,$now,\@currnewattach,\@currdelold,$numoldver,'',$blockblog));
 1995:         if ($attachnum > 0) {
 1996:             if (@currnewattach > 0) {
 1997:                 $newattachmsg .= '<br /><b>'.&mt('New attachments').'</b><br />';
 1998:                 if (@currnewattach > 1) {
 1999:                     $newattachmsg .= '<ol>';
 2000:                     foreach my $item (@currnewattach) {
 2001:                         $item =~ m#.*/([^/]+)$#;
 2002:                         $newattachmsg .= '<li><a href="'.$item.'">'.$1.'</a></li>'."\n";
 2003:                     }
 2004:                     $newattachmsg .= '</ol>'."\n";
 2005:                 } else {
 2006:                     $currnewattach[0] =~ m#.*/([^/]+)$#;
 2007:                     $newattachmsg .= '<a href="'.$currnewattach[0].'">'.$1.'</a><br />'."\n";
 2008:                 }
 2009:             }
 2010:             if ($attachmsg) {
 2011:                 $r->print("<br /><b>$lt{'reta'}</b>:$attachmsg<br />\n");
 2012:             }
 2013:             if ($newattachmsg) {
 2014:                 $r->print("$newattachmsg<br />");
 2015:             }
 2016:         }
 2017:     }
 2018:     $r->print(&generate_preview_button().
 2019: 	      &Apache::loncommon::end_page());
 2020: 
 2021: }
 2022: 
 2023: sub print_display_options {
 2024:     my ($r,$symb,$previous,$dispchgA,$dispchgB,$markchg,$toggchg,$feedurl) = @_;
 2025:     &Apache::loncommon::content_type($r,'text/html');
 2026:     $r->send_http_header;
 2027: 
 2028:     my $function = &Apache::loncommon::get_users_function();
 2029:     my $tabcolor = &Apache::loncommon::designparm($function.'.tabbg',
 2030:                                                     $env{'user.domain'});
 2031: 
 2032:     my %lt = &Apache::lonlocal::texthash(
 2033:         'pref' => 'Display Preference',
 2034:         'curr' => 'Current setting ',
 2035:         'actn' => 'Action',
 2036:         'deff' => 'Default for all discussions',
 2037:         'prca' => 'Preferences can be set for this discussion that determine ....',
 2038:         'whpo' => 'Which posts are displayed when you display this discussion board or resource, and',
 2039:         'unwh' => 'Under what circumstances posts are identified as "NEW", and',
 2040:         'wipa' => 'Whether individual posts can be marked as read/unread',
 2041:         'allposts' => 'All posts',
 2042:         'unread' => 'New posts only',
 2043:         'unmark' => 'Posts not marked read',
 2044:         'ondisp' => 'Once displayed',
 2045:         'onmark' => 'Once marked not NEW',
 2046:         'toggon' => 'Shown',
 2047:         'toggoff' => 'Not shown',
 2048:         'disa' => 'Posts displayed?',
 2049:         'npmr' => 'New posts cease to be identified as "NEW"?',
 2050:         'dotm' => 'Option to mark each post as read/unread?',  
 2051:         'chgt' => 'Change to ',
 2052:         'mkdf' => 'Set to ',
 2053:         'yhni' => 'You have not indicated that you wish to change any of the discussion settings',
 2054:         'ywbr' => 'You will be returned to the previous page if you click OK.'
 2055:     );
 2056: 
 2057:     my $dispchangeA = $lt{'unread'};
 2058:     my $dispchangeB = $lt{'unmark'};
 2059:     my $markchange = $lt{'ondisp'};
 2060:     my $toggchange = $lt{'toggon'};
 2061:     my $currdisp = $lt{'allposts'};
 2062:     my $currmark = $lt{'onmark'};
 2063:     my $discdisp = 'allposts';
 2064:     my $discmark = 'onmark';
 2065:     my $currtogg = $lt{'toggoff'};
 2066:     my $disctogg = 'toggoff';
 2067:                                                                                       
 2068:     if ($dispchgA eq 'allposts') {
 2069:         $dispchangeA = $lt{'allposts'};
 2070:         $currdisp = $lt{'unread'};
 2071:         $discdisp = 'unread';
 2072:     }
 2073: 
 2074:     if ($markchg eq 'markonread') {
 2075:         $markchange = $lt{'onmark'};
 2076:         $currmark = $lt{'ondisp'};
 2077:         $discmark = 'ondisp';
 2078:     }
 2079: 
 2080:     if ($dispchgB eq 'onlyunread') {
 2081:         $dispchangeB = $lt{'unread'};
 2082:         $currdisp = $lt{'unmark'};
 2083:         $discdisp = 'unmark';
 2084:     }
 2085:     if ($toggchg eq 'toggoff') {
 2086:         $toggchange = $lt{'toggoff'};
 2087:         $currtogg = $lt{'toggon'};
 2088:         $disctogg = 'toggon';
 2089:     }
 2090: 
 2091:     my $js = <<END;
 2092: <script type="text/javascript">
 2093: function discdispChk(caller) {
 2094:     var disctogg = '$toggchg'
 2095:     if (caller == 0) {
 2096:         if (document.modifydisp.discdisp[0].checked == true) {
 2097:             if (document.modifydisp.discdisp[1].checked == true) {
 2098:                 document.modifydisp.discdisp[1].checked = false
 2099:             }
 2100:         }
 2101:     }
 2102:     if (caller == 1) {
 2103:         if (document.modifydisp.discdisp[1].checked == true) {
 2104:             if (document.modifydisp.discdisp[0].checked == true) {
 2105:                 document.modifydisp.discdisp[0].checked = false
 2106:             }
 2107:             if (disctogg == 'toggon') {
 2108:                 document.modifydisp.disctogg.checked = true
 2109:             }
 2110:             if (disctogg == 'toggoff') {
 2111:                 document.modifydisp.disctogg.checked = false
 2112:             }
 2113:         }
 2114:     }
 2115:     if (caller == 2) {
 2116:         var dispchgB = '$dispchgB'
 2117:         if (disctogg == 'toggoff') {
 2118:             if (document.modifydisp.disctogg.checked == true) {
 2119:                 if (dispchgB == 'onlyunmark') {
 2120:                     document.modifydisp.discdisp[1].checked = false
 2121:                 }
 2122:             }
 2123:         }
 2124:     }  
 2125: }
 2126: 
 2127: function setDisp() {
 2128:     var prev = "$previous"
 2129:     var chktotal = 0
 2130:     if (document.modifydisp.discdisp[0].checked == true) {
 2131:         document.modifydisp.$dispchgA.value = "$symb"
 2132:         chktotal ++
 2133:     }
 2134:     if (document.modifydisp.discdisp[1].checked == true) {
 2135:         document.modifydisp.$dispchgB.value = "$symb"
 2136:         chktotal ++
 2137:     }
 2138:     if (document.modifydisp.discmark.checked == true) {
 2139:         document.modifydisp.$markchg.value = "$symb"
 2140:         chktotal ++
 2141:     }
 2142:     if (document.modifydisp.disctogg.checked == true) {
 2143:         document.modifydisp.$toggchg.value = "$symb"
 2144:         chktotal ++
 2145:     }
 2146:     if (chktotal > 0) { 
 2147:         document.modifydisp.submit()
 2148:     } else {
 2149:         if(confirm("$lt{'yhni'}. \\n$lt{'ywbr'}"))      {
 2150:             if (prev > 0) {
 2151:                 location.href = "$feedurl?previous=$previous"
 2152:             } else {
 2153:                 location.href = "$feedurl"
 2154:             }
 2155:         }
 2156:     }
 2157: }
 2158: </script>
 2159: END
 2160: 
 2161: 
 2162:     my $start_page =
 2163: 	&Apache::loncommon::start_page('Discussion display options',$js);
 2164:     my $end_page =
 2165: 	&Apache::loncommon::end_page();
 2166:     $r->print(<<END);
 2167: $start_page
 2168: <form name="modifydisp" method="post" action="/adm/feedback">
 2169: $lt{'sdpf'}<br/> $lt{'prca'}  <ol><li>$lt{'whpo'}</li><li>$lt{'unwh'}</li><li>$lt{'wipa'}</li></ol>
 2170: <br />
 2171: END
 2172:     $r->print(&Apache::loncommon::start_data_table());
 2173:     $r->print(<<END);
 2174:        <tr>
 2175:         <th>$lt{'pref'}</td>
 2176:         <th>$lt{'curr'}</td>
 2177:         <th>$lt{'actn'}?</td>
 2178:        </tr>
 2179: END
 2180:     $r->print(&Apache::loncommon::start_data_table_row());
 2181:     $r->print(<<END);
 2182:        <td>$lt{'disa'}</td>
 2183:        <td>$lt{$discdisp}</td>
 2184:        <td><label><input type="checkbox" name="discdisp" onclick="discdispChk('0')" />&nbsp;$lt{'chgt'} "$dispchangeA"</label>
 2185:            <br />
 2186:            <label><input type="checkbox" name="discdisp" onclick="discdispChk('1')" />&nbsp;$lt{'chgt'} "$dispchangeB"</label>
 2187:        </td>
 2188: END
 2189:     $r->print(&Apache::loncommon::end_data_table_row());
 2190:     $r->print(&Apache::loncommon::start_data_table_row());
 2191:     $r->print(<<END);
 2192:        <td>$lt{'npmr'}</td>
 2193:        <td>$lt{$discmark}</td>
 2194:        <td><label><input type="checkbox" name="discmark" />$lt{'chgt'} "$markchange"</label></td>
 2195: END
 2196:     $r->print(&Apache::loncommon::end_data_table_row());
 2197:     $r->print(&Apache::loncommon::start_data_table_row());
 2198:     $r->print(<<END);
 2199:        <td>$lt{'dotm'}</td>
 2200:        <td>$lt{$disctogg}</td>
 2201:        <td><label><input type="checkbox" name="disctogg" onclick="discdispChk('2')" />$lt{'chgt'} "$toggchange"</label></td>
 2202: END
 2203:     my $save = &mt('Save');
 2204:     $r->print(&Apache::loncommon::end_data_table_row());
 2205:     $r->print(&Apache::loncommon::end_data_table());
 2206:     $r->print(<<END);
 2207: <br />
 2208: <br />
 2209: <input type="hidden" name="symb" value="$symb" />
 2210: <input type="hidden" name="previous" value="$previous" />
 2211: <input type="hidden" name="$dispchgA" value="" />
 2212: <input type="hidden" name="$dispchgB" value="" />
 2213: <input type="hidden" name="$markchg" value="" />
 2214: <input type="hidden" name="$toggchg" value="" />
 2215: <input type="button" name="sub" value="$save" onclick="javascript:setDisp()" />
 2216: END
 2217:     if (exists($env{'form.group'})) {
 2218:         $r->print('<input type="hidden" name="group" value="'.$env{'form.group'}.'" />');
 2219:     }
 2220:     if (exists($env{'form.ref'})) {
 2221:         $r->print('<input type="hidden" name="ref" value="'.$env{'form.ref'}.'" />');
 2222:     }
 2223:     $r->print("
 2224: <br />
 2225: <br />
 2226: </form>
 2227: $end_page
 2228:     ");
 2229:     return;
 2230: }
 2231: 
 2232: sub print_sortfilter_options {
 2233:     my ($r,$symb,$previous,$feedurl) = @_;
 2234: 
 2235:     &Apache::loncommon::content_type($r,'text/html');
 2236:     $r->send_http_header;
 2237: 
 2238:     &Apache::lonenc::check_encrypt(\$symb);
 2239:     my @sections;
 2240:     my $section_sel = '';
 2241:     my $numvisible = 5;
 2242:     my @groups;
 2243:     my $group_sel = '';
 2244:     my $numgroupvis = 5;
 2245:     my %sectioncount = &Apache::loncommon::get_sections();
 2246:     my @courseroles = qw(st ad ep ta in);
 2247:     my $crstype = &Apache::loncommon::course_type();
 2248:     my $ccrole = 'cc';
 2249:     if ($crstype eq 'Community') {
 2250:         $ccrole = 'co';
 2251:     }
 2252:     push(@courseroles,$ccrole);
 2253:     
 2254:     if ($env{'request.course.sec'} !~ /^\s*$/) {  #Restrict section choice to current section 
 2255:         @sections = ('all',$env{'request.course.sec'});
 2256:         $numvisible = 2;
 2257:     } else {
 2258:         @sections = sort {$a cmp $b} keys(%sectioncount);
 2259:         if (scalar(@sections) < 4) {
 2260:             $numvisible = scalar(@sections) + 1;
 2261:         }
 2262:         unshift(@sections,'all'); # Put 'all' at the front of the list
 2263: 
 2264:     }
 2265:     foreach my $sec (@sections) {
 2266:         $section_sel .= "  <option value=\"$sec\">$sec</option>\n";
 2267:     }
 2268: 
 2269:     if (&check_group_priv() eq 'ok') {
 2270:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2271:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'}; 
 2272:         my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 2273:         @groups = sort {$a cmp $b} keys(%curr_groups);
 2274:         if (scalar(@groups) < 4) {
 2275:             $numgroupvis = scalar(@groups) + 1;
 2276:         }
 2277:         unshift(@groups,'all'); # Put 'all' at the front of the list
 2278:     } else { 
 2279:         my @coursegroups = split(/:/,$env{'request.course.groups'});
 2280:         if (@coursegroups > 0) {
 2281:             @coursegroups = sort {$a cmp $b} @coursegroups;
 2282:             @groups = ('all',@coursegroups);
 2283:             if (scalar(@groups) < 4) {
 2284:                 $numgroupvis = scalar(@groups) + 1;
 2285:             }
 2286:         } else {
 2287:             @groups = ('all');
 2288:             $numgroupvis = 1;
 2289:         }
 2290:     }
 2291:     foreach my $group (@groups) {
 2292:         $group_sel .= "  <option value=\"$group\">$group</option>\n";
 2293:     }
 2294: 
 2295:     my $function = &Apache::loncommon::get_users_function();
 2296:     my $tabcolor = &Apache::loncommon::designparm($function.'.tabbg',
 2297:                                                     $env{'user.domain'});
 2298:     my %lt = &Apache::lonlocal::texthash(
 2299:         'diop' => 'Display Options',
 2300:         'curr' => 'Current setting ',
 2301:         'actn' => 'Action',
 2302:         'prca' => 'Set options that control the sort order of posts, and/or which posts are displayed.',
 2303:         'soor' => 'Sort order',
 2304:         'spur' => 'Specific user roles',
 2305:         'sprs' => 'Specific role status',
 2306:         'spse' => 'Specific sections',
 2307:         'spgr' => 'Specific groups',
 2308:         'psub' => 'Pick specific users (by name)',
 2309:         'shal' => 'Show a list of current posters',
 2310:         'stor' => 'Save changes',
 2311:     );
 2312: 
 2313:     my %sort_types = ();
 2314:     my %role_types = ();
 2315:     my %status_types = ();
 2316:     &sort_filter_names(\%sort_types,\%role_types,\%status_types,$crstype);
 2317: 
 2318:     my $js = <<END;
 2319: <script type="text/javascript">
 2320: function verifyFilter() {
 2321:     var rolenum = 0
 2322:     for (var i=0; i<document.modifyshown.rolefilter.length; i++) {
 2323:         if (document.modifyshown.rolefilter.options[i].selected == true) {
 2324:             rolenum ++
 2325:         }
 2326:     }
 2327:     if (rolenum == 0) {
 2328:         document.modifyshown.rolefilter.options[0].selected = true
 2329:     }
 2330: 
 2331:     var secnum = 0
 2332:     for (var i=0; i<document.modifyshown.sectionpick.length; i++) {
 2333:         if (document.modifyshown.sectionpick.options[i].selected == true) {
 2334:             secnum ++
 2335:         }
 2336:     }
 2337:     if (secnum == 0) {
 2338:         document.modifyshown.sectionpick.options[0].selected = true
 2339:     }
 2340: 
 2341:     var grpnum = 0
 2342:     for (var i=0; i<document.modifyshown.grouppick.length; i++) {
 2343:         if (document.modifyshown.grouppick.options[i].selected == true) {
 2344:             grpnum ++
 2345:         }
 2346:     }
 2347:     if (grpnum == 0) {
 2348:         document.modifyshown.grouppick.options[0].selected = true
 2349:     }
 2350: 
 2351:     document.modifyshown.submit();
 2352: }
 2353: </script>
 2354: END
 2355: 
 2356:     my $start_page=
 2357: 	&Apache::loncommon::start_page('Discussion options',$js);
 2358:     my $end_page=
 2359: 	&Apache::loncommon::end_page();
 2360: 
 2361:     $r->print(<<END);
 2362: $start_page
 2363: <form name="modifyshown" method="post" action="/adm/feedback">
 2364: <b>$lt{'diso'}</b><br/> $lt{'prca'}
 2365: <br />
 2366: <table border="0">
 2367:  <tr>
 2368:   <th>$lt{'soor'}</th>
 2369:   <th>&nbsp;</th>
 2370:   <th>$lt{'sprs'}</th>
 2371:   <th>&nbsp;</th>
 2372:   <th>$lt{'spur'}</th>
 2373:   <th>&nbsp;</th>
 2374:   <th>$lt{'spse'}</th>
 2375:   <th>&nbsp;</th>
 2376:   <th>$lt{'spgr'}</th>
 2377:   <th>&nbsp;</th>
 2378:   <th>$lt{'psub'}</th>
 2379:  </tr>
 2380:  <tr>
 2381:   <td align="center" valign="top">
 2382:    <select name="sortposts">
 2383:     <option value="ascdate" selected="selected">$sort_types{'ascdate'}</option>
 2384:     <option value="descdate">$sort_types{'descdate'}</option>
 2385:     <option value="thread">$sort_types{'thread'}</option>
 2386:     <option value="subject">$sort_types{'subject'}</option>
 2387:     <option value="username">$sort_types{'username'}</option>
 2388:     <option value="lastfirst">$sort_types{'lastfirst'}</option>
 2389:    </select>
 2390:   </td>
 2391:   <td>&nbsp;</td>
 2392:   <td align="center" valign="top">
 2393:    <select name="statusfilter">
 2394:     <option value="all" selected="selected">$status_types{'all'}</option>
 2395:     <option value="Active">$status_types{'Active'}</option>
 2396:     <option value="Expired">$status_types{'Expired'}</option>
 2397:     <option value="Future">$status_types{'Future'}</option>
 2398:    </select>
 2399:   </td>
 2400:   <td>&nbsp;</td>
 2401:   <td align="center" valign="top">
 2402:    <select name="rolefilter" multiple="multiple" size="5">
 2403:     <option value="all">$role_types{'all'}</option>
 2404:     <option value="st">$role_types{'st'}</option>
 2405:     <option value="$ccrole">$role_types{$ccrole}</option>
 2406:     <option value="in">$role_types{'in'}</option>
 2407:     <option value="ta">$role_types{'ta'}</option>
 2408:     <option value="ep">$role_types{'ep'}</option>
 2409:     <option value="ad">$role_types{'ad'}</option>
 2410:     <option value="cr">$role_types{'cr'}</option>
 2411:    </select>
 2412:   </td>
 2413:   <td>&nbsp;</td>
 2414:   <td align="center" valign="top">
 2415:    <select name="sectionpick" multiple="multiple" size="$numvisible">
 2416:     $section_sel
 2417:    </select>
 2418:   </td>
 2419:   <td>&nbsp;</td>
 2420:   <td align="center" valign="top">
 2421:    <select name="grouppick" multiple="multiple" size="$numvisible">
 2422:     $group_sel
 2423:    </select>
 2424:   </td>
 2425:   <td>&nbsp;</td>
 2426:   <td valign="top"><label><input type="checkbox" name="posterlist" value="$symb" />$lt{'shal'}</label></td>
 2427:  </tr>
 2428: </table>
 2429: <br />
 2430: <input type="hidden" name="inhibitmenu" value="$env{'form.inhibitmenu'}" />
 2431: <input type="hidden" name="modal" value="$env{'form.modal'}" />
 2432: <input type="hidden" name="previous" value="$previous" />
 2433: <input type="hidden" name="applysort" value="$symb" />
 2434: <input type="button" name="sub" value="$lt{'stor'}" onclick="verifyFilter()" />
 2435: END
 2436:     if (exists($env{'form.group'})) {
 2437:         $r->print('<input type="hidden" name="group" value="'.$env{'form.group'}.'" />');
 2438:     }
 2439:     if (exists($env{'form.ref'})) {
 2440:         $r->print('<input type="hidden" name="ref" value="'.$env{'form.ref'}.'" />');
 2441:     }
 2442:     $r->print("
 2443: <br />
 2444: <br />
 2445: </form>
 2446: $end_page
 2447: ");
 2448: }
 2449: 
 2450: sub print_showposters {
 2451:     my ($r,$symb,$previous,$feedurl,$sortposts) = @_;
 2452: 
 2453:     &Apache::loncommon::content_type($r,'text/html');
 2454:     $r->send_http_header;
 2455: 
 2456:     &Apache::lonenc::check_encrypt(\$symb);
 2457:     my $crs='/'.$env{'request.course.id'};
 2458:     if ($env{'request.course.sec'}) {
 2459:         $crs.='_'.$env{'request.course.sec'};
 2460:     }
 2461:     $crs=~s/\_/\//g;
 2462:     my $seeid;
 2463:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2464:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2465:     my $group = $env{'form.group'};
 2466:     my $ressymb = &wrap_symb($symb);
 2467:     if (($group ne '') &&
 2468:         ($ressymb =~ m|^bulletin___\d+___adm/wrapper/adm/\Q$cdom\E/\Q$cnum\E/\d+/bulletinboard$|)) {
 2469:         if (&check_group_priv($group,'dgp') eq 'ok') {
 2470:             $seeid = 1;
 2471:         }
 2472:     } else {
 2473:         $seeid=&Apache::lonnet::allowed('rin',$crs);
 2474:     }
 2475:     my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 2476:                                          $cdom,$cnum);
 2477:     my %namesort = ();
 2478:     my %postcounts = ();
 2479: 
 2480:     my %lt = &Apache::lonlocal::texthash(
 2481:                                           sele => 'Select',
 2482:                                           full => 'Fullname',
 2483:                                           usdo => 'Username:domain',
 2484:                                           post => 'Posts',
 2485:                                         );
 2486:     if ($contrib{'version'}) {
 2487:         for (my $idx=1;$idx<=$contrib{'version'};$idx++) {
 2488:             my $hidden=($contrib{'hidden'}=~/\.$idx\./);
 2489:             my $deleted=($contrib{'deleted'}=~/\.$idx\./);
 2490:             unless ((($hidden) && (!$seeid)) || ($deleted)) {
 2491:                 if ((!$contrib{$idx.':anonymous'}) || (&Apache::lonnet::allowed('rin',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 2492:                     my %names = &Apache::lonnet::get('environment',['firstname','lastname'],$contrib{$idx.':senderdomain'},$contrib{$idx.':sendername'});
 2493:                     my $lastname = $names{'lastname'};
 2494:                     my $firstname = $names{'firstname'};
 2495:                     if ($lastname eq '') {
 2496:                         $lastname = '_';
 2497:                     }
 2498:                     if ($firstname eq '') {
 2499:                         $firstname = '_';
 2500:                     }
 2501:                     unless (defined($namesort{$lastname})) {
 2502:                         %{$namesort{$lastname}} = ();
 2503:                     }
 2504:                     my $poster =  $contrib{$idx.':sendername'}.':'.$contrib{$idx.':senderdomain'};
 2505:                     $postcounts{$poster} ++;
 2506:                     if (defined($namesort{$lastname}{$firstname})) {
 2507:                         if (!grep/^$poster$/,@{$namesort{$lastname}{$firstname}}) {
 2508:                             push(@{$namesort{$lastname}{$firstname}}, $poster);
 2509:                         }
 2510:                     } else {
 2511:                         @{$namesort{$lastname}{$firstname}} = ("$poster");
 2512:                     }
 2513:                 }
 2514:             }
 2515:         }
 2516:     }
 2517: 
 2518:     my $start_page = &Apache::loncommon::start_page('Discussion options');
 2519:     my $table_start =&Apache::loncommon::start_data_table();
 2520:     $r->print(<<END);
 2521: $start_page
 2522:  <form name="pickpostersform" method="post">
 2523:  <br />
 2524:     $table_start
 2525:       <tr>
 2526:        <th>#</th>
 2527:        <th>$lt{'sele'}</th>
 2528:        <th>$lt{'full'} <font color="#999999">($lt{'usdo'})</font></th>
 2529:        <th>$lt{'post'}</th>
 2530:       </tr>
 2531: END
 2532:     my $count = 0;
 2533:     foreach my $last (sort(keys(%namesort))) {
 2534:         foreach my $first (sort(keys(%{$namesort{$last}}))) {
 2535:             foreach my $user (sort(@{$namesort{$last}{$first}})) {
 2536:                 my ($uname,$udom) = split(/:/,$user);
 2537:                 if (!$uname || !$udom) { 
 2538:                     next;
 2539:                 } else {
 2540:                     $count ++;
 2541:                     $r->print(&Apache::loncommon::start_data_table_row().
 2542: 			      '<td align="right">'.$count.'</td>
 2543:                                <td align="center"><label><input name="stuinfo" type="checkbox" value="'.$user.'" /></td>
 2544:                                <td>'.$last.', '.$first.' ('.$uname.':'.$udom.')</label></td>
 2545:                                <td>'.$postcounts{$user}.'</td>'.
 2546: 			      &Apache::loncommon::end_data_table_row());
 2547:                 }
 2548:             }
 2549:         }
 2550:     }
 2551:     $r->print(&Apache::loncommon::end_data_table());
 2552:     my $end_page   = &Apache::loncommon::end_page();
 2553:     $r->print(<<END);
 2554: <br />
 2555: <input type="hidden" name="sortposts" value="$sortposts" />
 2556: <input type="hidden" name="modal" value="$env{'form.modal'}" />
 2557: <input type="hidden" name="userpick" value="$symb" />
 2558: <input type="button" name="store" value="Display posts" onclick="javascript:document.pickpostersform.submit()" />
 2559: </form>
 2560: $end_page
 2561: END
 2562: }
 2563: 
 2564: sub get_post_versions {
 2565:     my ($versions,$incoming,$htmldecode,$numver) = @_;
 2566:     if ($incoming =~ /^<version num="0">/) {
 2567:         my $p = HTML::LCParser->new(\$incoming);
 2568:         my $done = 0; 
 2569: 
 2570:         while ( (my $token = $p->get_tag("version")) && (!$done)) {
 2571:             my $num = $token->[1]{num};
 2572:             my $text = $p->get_text("/version");
 2573:             if (defined($numver)) {
 2574:                 if ($num == $numver) {
 2575:                     if ($htmldecode) {
 2576:                         $text = &HTML::Entities::decode($text);
 2577:                     }
 2578:                     $$versions{$numver}=$text;
 2579:                     $done = 1;
 2580:                 }
 2581:             } else {
 2582:                 if ($htmldecode) {
 2583:                     $text = &HTML::Entities::decode($text);
 2584:                 }
 2585:                 $$versions{$num}=$text;
 2586:             }
 2587:         }
 2588:     } else {
 2589:         if (!defined($numver)) {
 2590:             $numver = 0;
 2591:         }
 2592:         if ($htmldecode) {
 2593:             $$versions{$numver} = $incoming;
 2594:         } else {
 2595:             $$versions{$numver} = &HTML::Entities::encode($incoming,'<>&"');
 2596:         }
 2597:     }
 2598:     return;
 2599: }
 2600: 
 2601: sub get_post_attachments {
 2602:     my ($attachments,$attachmenturls) = @_;
 2603:     my $num;
 2604:     if ($attachmenturls =~ m/^<attachment id="0">/) {
 2605:         my $p = HTML::LCParser->new(\$attachmenturls);
 2606:         while (my $token = $p->get_tag("attachment","filename","post"))  {
 2607:             if ($token->[0] eq "attachment") {
 2608:                 $num = $token->[1]{id};
 2609:                 %{$$attachments{$num}} =();
 2610:             } elsif ($token->[0] eq "filename") {
 2611:                 $$attachments{$num}{'filename'} = $p->get_text("/filename");
 2612:             } elsif ($token->[0] eq "post") {
 2613:                 my $id = $token->[1]{id};
 2614:                 $$attachments{$num}{$id} = $p->get_text("/post");
 2615:             }
 2616:         }
 2617:     } else {
 2618:         %{$$attachments{'0'}} = ();
 2619:         $$attachments{'0'}{'filename'} = $attachmenturls;
 2620:         $$attachments{'0'}{'0'} = 'n';
 2621:     }
 2622: 
 2623:     return;
 2624: }
 2625: 
 2626: sub fail_redirect {
 2627:   my ($r,$feedurl) = @_;
 2628:   if ($feedurl=~/^\/adm\//) { $feedurl.='?register=1' };
 2629:   my %lt = &Apache::lonlocal::texthash(
 2630:                  'sorr' => 'Sorry, no recipients ...',
 2631:   );
 2632:   my $logo=&Apache::loncommon::lonhttpdurl('/adm/lonIcons/lonlogos.gif');
 2633:   $r->print(&Apache::loncommon::start_page('Feedback not sent',undef,
 2634: 					   {'redirect'  => [2,$feedurl],
 2635: 					    'only_body' => 1,}));
 2636:   $r->print(<<ENDFAILREDIR);
 2637: <img align="right" src="$logo" />
 2638: <b>$lt{'sorr'}</b>
 2639: ENDFAILREDIR
 2640:   $r->print(&Apache::loncommon::end_page());
 2641: }
 2642: 
 2643: sub redirect_back {
 2644:   my ($r,$feedurl,$typestyle,$sendsomething,$sendposts,$blog,$status,$previous,$sort,$rolefilter,$statusfilter,$sectionpick,$grouppick,$numpicks,$group,$toolarge) = @_;
 2645:   my $sorttag = '';
 2646:   my $roletag = '';
 2647:   my $statustag = '';
 2648:   my $sectag = '';
 2649:   my $grptag = '';
 2650:   my $userpicktag = '';
 2651:   my $qrystr = '';
 2652:   my $prevtag = '';
 2653: 
 2654:   &Apache::loncommon::content_type($r,'text/html');
 2655:   $r->send_http_header;
 2656:   &dewrapper(\$feedurl);
 2657:   if ($feedurl=~/^\/adm\//) { $feedurl.='?register=1' };
 2658:   if ($previous > 0) {
 2659:       $qrystr = 'previous='.$previous;
 2660:       if ($feedurl =~ /\?register=1/) {
 2661:           $feedurl .= '&amp;'.$qrystr;
 2662:       } else {
 2663:           $feedurl .= '?'.$qrystr;
 2664:       }
 2665:       $prevtag = '<input type="hidden" name="previous" value="'.$previous.'" />';
 2666:   }
 2667:   if (defined($sort)) {
 2668:       my $sortqry = 'sortposts='.$sort;
 2669:       if (($feedurl =~ /\?register=1/) || ($feedurl =~ /\?previous=/)) {
 2670:           $feedurl .= '&amp;'.$sortqry;
 2671:       } else {
 2672:           $feedurl .= '?'.$sortqry;
 2673:       }
 2674:       $sorttag = '<input type="hidden" name="sortposts" value="'.$sort.'" />';
 2675:       if (defined($numpicks)) {
 2676:           my $userpickqry = 'totposters='.$numpicks;
 2677:           $feedurl .= '&amp;'.$userpickqry;
 2678:           $userpicktag = '<input type="hidden" name="totposters" value="'.$numpicks.'" />';
 2679:       } else {
 2680:           if (ref($sectionpick) eq 'ARRAY') {
 2681:               $feedurl .= '&amp;sectionpick=';
 2682:               $sectag .=  '<input type="hidden" name="sectionpick" value="';
 2683:               foreach my $sec (@{$sectionpick}) {
 2684:                   $feedurl .= $sec.',';
 2685:                   $sectag .= $sec.',';
 2686:               }
 2687:               $feedurl =~ s/,$//;
 2688:               $sectag =~ s/,$//;
 2689:               $sectag .= '" />';
 2690:           } else {
 2691:               $feedurl .= '&amp;sectionpick='.$sectionpick;
 2692:               $sectag = '<input type="hidden" name="sectionpick" value="'.$sectionpick.'" />';
 2693:           }
 2694:           if (ref($grouppick) eq 'ARRAY') {
 2695:               $feedurl .= '&amp;grouppick=';
 2696:               $sectag .=  '<input type="hidden" name="grouppick" value="';
 2697:               foreach my $grp (@{$grouppick}) {
 2698:                   $feedurl .= $grp.',';
 2699:                   $grptag .= $grp.',';
 2700:               }
 2701:               $feedurl =~ s/,$//;
 2702:               $grptag =~ s/,$//;
 2703:               $grptag .= '" />';
 2704:           } else {
 2705:               $feedurl .= '&amp;grouppick='.$grouppick;
 2706:               $grptag = '<input type="hidden" name="grouppick" value="'.$grouppick.'" />';
 2707:           }
 2708:           if (ref($rolefilter) eq 'ARRAY') {
 2709:               $feedurl .= '&amp;rolefilter=';
 2710:               $roletag .=  '<input type="hidden" name="rolefilter" value="';
 2711:               foreach my $role (@{$rolefilter}) {
 2712:                   $feedurl .= $role.',';
 2713:                   $roletag .= $role.',';
 2714:               }
 2715:               $feedurl =~ s/,$//;
 2716:               $roletag =~ s/,$//;
 2717:               $roletag .= '" />';
 2718:           } else {
 2719:               $feedurl .= '&amp;rolefilter='.$rolefilter;
 2720:               $roletag = '<input type="hidden" name="rolefilter" value="'.$rolefilter.'" />';
 2721:           }
 2722:           $feedurl .= '&amp;statusfilter='.$statusfilter;
 2723:           $statustag ='<input type="hidden" name="statusfilter" value="'.$statusfilter.'" />';
 2724:       }
 2725:   }
 2726:   my $grouptag;
 2727:   if ($group ne '') {
 2728:       $grouptag = '<input type="hidden" name="group" value="'.$group.'" />';
 2729:       my $refarg;
 2730:       if (exists($env{'form.ref'})) {
 2731:           $refarg = '&amp;ref='.$env{'form.ref'};
 2732:           $grouptag .= '<input type="hidden" name="ref" value="'.$env{'form.ref'}.'" />';
 2733:       }
 2734:       if ($feedurl =~ /\?/) {
 2735:           $feedurl .= '&amp;group='.$group.$refarg;
 2736:       } else {
 2737:           $feedurl .= '?group='.$group.$refarg;
 2738:       }
 2739:   } 
 2740:   &Apache::lonenc::check_encrypt(\$feedurl);
 2741:   my $logo=&Apache::loncommon::lonhttpdurl('/adm/lonIcons/lonlogos.gif');
 2742:   my %parms=('only_body'   => 1);
 2743:   if ($env{'form.modal'}) {
 2744:       $parms{'add_entries'}={'onLoad' => 'document.forms.reldt.submit()'};
 2745:   } else {
 2746:       $parms{'redirect'}=[0,$feedurl];
 2747:   }
 2748:   my $start_page=
 2749:       &Apache::loncommon::start_page('Feedback sent',undef,\%parms);
 2750:   my $end_page = &Apache::loncommon::end_page();
 2751:   $r->print(<<ENDREDIR);
 2752: $start_page
 2753: <img align="right" src="$logo" />
 2754: $typestyle
 2755: <b>Sent $sendsomething message(s), and $sendposts post(s).</b>
 2756: $blog
 2757: $toolarge
 2758: <font color="red">$status</font>
 2759: <form name="reldt" action="$feedurl" target="loncapaclient">
 2760: $prevtag
 2761: $sorttag
 2762: $statustag
 2763: $roletag
 2764: $sectag
 2765: $grptag
 2766: $userpicktag
 2767: $grouptag
 2768: </form>
 2769: $end_page
 2770: ENDREDIR
 2771: }
 2772: 
 2773: sub no_redirect_back {
 2774:   my ($r,$feedurl) = @_;
 2775:   my $nofeed=&mt('Sorry, no feedback possible on this resource ...');
 2776:  
 2777:   my %onload;
 2778: 
 2779:   my %body_options = ('only_body'   => 1,
 2780: 		      'bgcolor'     => '#FFFFFF',
 2781: 		      'add_entries' => \%onload,);
 2782: 
 2783:   if ($feedurl !~ m{^/adm/feedback}) { 
 2784:       $body_options{'redirect'} = [2,$feedurl];
 2785:   }
 2786:   my $start_page=
 2787:       &Apache::loncommon::start_page('Feedback not sent',undef,
 2788: 				     \%body_options);
 2789: 				      
 2790:   my $end_page = &Apache::loncommon::end_page();
 2791: 
 2792:   &Apache::lonenc::check_encrypt(\$feedurl);
 2793:   my $logo=&Apache::loncommon::lonhttpdurl('/adm/lonIcons/lonlogos.gif');
 2794:   $r->print (<<ENDNOREDIRTWO);
 2795: $start_page
 2796: <img align="right" src="$logo" />
 2797: <b>$nofeed</b>
 2798: <br />
 2799: $end_page
 2800: ENDNOREDIRTWO
 2801: }
 2802: 
 2803: sub screen_header {
 2804:     my ($feedurl,$symb,$group) = @_;
 2805:     my $crscontent = &mt('Question/Comment/Feedback about course content');
 2806:     my $crspolicy = &mt('Question/Comment/Feedback about course policy');
 2807:     my $contribdisc = &mt('Contribution to course discussion of resource');
 2808:     my $anoncontrib = &mt('Anonymous contribution to course discussion of resource');
 2809:     my $namevis = &mt('name only visible to course faculty');
 2810:     my $crstype;
 2811:     if ($env{'request.course.id'}) {
 2812:         $crstype = &Apache::loncommon::course_type();
 2813:         if ($crstype eq 'Community') {
 2814:             $crscontent = &mt('Question/Comment/Feedback about community content');
 2815:             $crspolicy = &mt('Question/Comment/Feedback about community policy');
 2816:             $contribdisc = &mt('Contribution to community discussion of resource');
 2817:             $anoncontrib = &mt('Anonymous contribution to community discussion of resource');
 2818:             $namevis = &mt('name only visible to community facilitators');
 2819:         }
 2820:     }
 2821:     my $msgoptions='';
 2822:     my $discussoptions='';
 2823:     unless (($env{'form.replydisc'}) || ($env{'form.editdisc'})) {
 2824: 	if (($feedurl=~/^\/res\//) && ($feedurl!~/^\/res\/adm/) && ($env{'user.adv'})) {
 2825: 	    $msgoptions= 
 2826: 		'<label><input type="radio" name="discuss" value="author" /> '.
 2827: 		&mt('Feedback to resource author').'</label><br />';
 2828: 	}
 2829:         my %optionhash=();
 2830:         foreach my $type ('question','comment','policy') {
 2831: 	    $optionhash{$type}=$env{'course.'.$env{'request.course.id'}.'.'.$type.'.email.text'};
 2832: 	}
 2833: 	if (&feedback_available(1)) {
 2834: 	    $msgoptions.=
 2835: 		'<label><input type="radio" name="discuss" value="question" /> '.
 2836: 		($optionhash{'question'}?$optionhash{'question'}:&mt('Question about resource content')).'</label><br />';
 2837: 	}
 2838: 	if (&feedback_available(0,1)) {
 2839: 	    $msgoptions.=
 2840: 		'<label><input type="radio" name="discuss" value="course" /> '.
 2841: 		($optionhash{'comment'}?$optionhash{'comment'}:$crscontent).
 2842: 		'</label><br />';
 2843: 	}
 2844: 	if (&feedback_available(0,0,1)) {
 2845: 	    $msgoptions.=
 2846: 		'<label><input type="radio" name="discuss" value="policy" /> '.
 2847: 		($optionhash{'policy'}?$optionhash{'policy'}:$crspolicy).
 2848: 		'</label><br />';
 2849: 	}
 2850:     }
 2851:     if (($env{'request.course.id'}) && (!$env{'form.sendmessageonly'})) {
 2852:         my ($blocked,$blocktext) = &Apache::loncommon::blocking_status('boards');
 2853:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2854:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2855:         my $realsymb = &get_realsymb($symb);
 2856:         if (!$blocked && &discussion_open(undef,$realsymb) && 
 2857: 	    (&Apache::lonnet::allowed('pch',
 2858: 				      $env{'request.course.id'}.
 2859: 				      ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')) || 
 2860:             (($group ne '') && ($symb =~ m{^bulletin___\d+___adm/wrapper/adm/\Q$cdom\E/\Q$cnum\E/\d+/bulletinboard$}) && (&check_group_priv($group,'pgd') eq 'ok')))) {
 2861: 	    $discussoptions='<label><input type="radio" name="discuss" value="nonanon" checked="checked" /> '.
 2862: 		$contribdisc.
 2863: 	        '</label><br /><label><input type="radio" name="discuss" value="anon" /> '.
 2864: 		$anoncontrib.
 2865: 		' <i>('.$namevis.')</i></label> '.
 2866: 		'<a href="/adm/preferences?action=changescreenname">'.&mt('Change Screenname').'</a>';
 2867:             my $blockblog = &Apache::loncommon::blocking_status('blogs');
 2868:             if (!$blockblog) {
 2869:                 $discussoptions.= &add_blog_checkbox($crstype);
 2870:             }
 2871:         }
 2872:     }
 2873:     if ($msgoptions) {
 2874:         $msgoptions='<tr><th><img src="'.&Apache::loncommon::lonhttpdurl('/res/adm/pages/feedback.png').'" />'
 2875:                    .'<br />'.&mt('Send Feedback').'<br />'.&Apache::lonhtmlcommon::coursepreflink(&mt('Feedback Settings'),'feedback').'</th>'.
 2876:                    '<td>'.$msgoptions.'</td></tr>';
 2877:     }
 2878:     if ($discussoptions) { 
 2879: 	$discussoptions='<tr><th><img src="'.&Apache::loncommon::lonhttpdurl('/adm/lonMisc/chat.gif').'" alt="" />'
 2880:                         .'<br />'.&mt('Discussion Contributions').'<br />'.&Apache::lonhtmlcommon::coursepreflink(&mt('Discussion Settings'),'discussion').'</th>'.
 2881:                         '<td>'.$discussoptions.'</td></tr>';
 2882:     }
 2883:     return  &Apache::loncommon::start_data_table().$msgoptions.$discussoptions.&Apache::loncommon::end_data_table();
 2884: }
 2885: 
 2886: sub resource_output {
 2887:   my ($feedurl) = @_;
 2888:   my $usersaw=&Apache::lonnet::ssi_body($feedurl);
 2889:   $usersaw=~s/\<body[^\>]*\>//gi;
 2890:   $usersaw=~s/\<\/body\>//gi;
 2891:   $usersaw=~s/\<html\>//gi;
 2892:   $usersaw=~s/\<\/html\>//gi;
 2893:   $usersaw=~s/\<head\>//gi;
 2894:   $usersaw=~s/\<\/head\>//gi;
 2895:   $usersaw=~s/action\s*\=/would_be_action\=/gi;
 2896:   return $usersaw;
 2897: }
 2898: 
 2899: sub clear_out_html {
 2900:   my ($message,$override)=@_;
 2901: # Always allow the <m>-tag
 2902:   my %html=(M=>1);
 2903: # Check if more is allowed
 2904:   my $cid=$env{'request.course.id'};
 2905:   if (($env{"course.$cid.allow_limited_html_in_feedback"} =~ m/yes/i) ||
 2906:       ($override)) {
 2907:       # allows <B> <I> <P> <A> <LI> <OL> <UL> <EM> <BR> <TT> <STRONG> 
 2908:       # <BLOCKQUOTE> <DIV .*> <DIV> <IMG> <M> <SPAN> <H1> <H2> <H3> <H4> <SUB>
 2909:       # <SUP> <TABLE> <TR> <TD> <TH> <TBODY>
 2910:       %html=(B=>1, I=>1, P=>1, A=>1, LI=>1, OL=>1, UL=>1, EM=>1,
 2911: 	     BR=>1, TT=>1, STRONG=>1, BLOCKQUOTE=>1, PRE=>1, DIV=>1, IMG=>1,
 2912: 	     M=>1, CHEM=>1, ALGEBRA=>1, SUB=>1, SUP=>1, SPAN=>1,  
 2913: 	     H1=>1, H2=>1, H3=>1, H4=>1, H5=>1, H6=>1, 
 2914: 	     TABLE=>1, TR=>1, TD=>1, TH=>1, TBODY=>1);
 2915:   }
 2916: # Do the substitution of everything that is not explicitly allowed
 2917:   $message =~ s/\<(\/?\s*(\w+)[^\>\<]*)/
 2918: 	  {($html{uc($2)}&&(length($1)<1000))?"\<$1":"\&lt;$1"}/ge;
 2919:   $message =~ s/(\<?\s*(\w+)[^\<\>]*)\>/
 2920: 	  {($html{uc($2)}&&(length($1)<1000))?"$1\>":"$1\&gt;"}/ge;
 2921:   return $message;
 2922: }
 2923: 
 2924: sub assemble_email {
 2925:   my ($message,$prevattempts,$usersaw,$useranswer)=@_;
 2926:   my %lt = &Apache::lonlocal::texthash(
 2927:              'prev' => 'Previous attempts of student (if applicable)',
 2928:              'orig' => 'Original screen output (if applicable)',
 2929:              'corr' => 'Correct Answer(s) (if applicable)',
 2930:   );
 2931:   if (&Apache::loncommon::course_type() eq 'Community') {
 2932:       $lt{'prev'} = &mt('Previous attempts of member (if applicable)');
 2933:   }
 2934:   my $email=<<"ENDEMAIL";
 2935: $message
 2936: ENDEMAIL
 2937:     my $citations=<<"ENDCITE";
 2938: <h2>$lt{'prev'}</h2>
 2939: $prevattempts
 2940: <br /><hr />
 2941: <h2>$lt{'orig'}</h2>
 2942: $usersaw
 2943: <h2>$lt{'corr'}</h2>
 2944: $useranswer
 2945: ENDCITE
 2946:   return ($email,$citations);
 2947: }
 2948: 
 2949: 
 2950: sub feedback_available {
 2951:     my ($question,$course,$policy)=@_;
 2952:     my ($typestyle,%to)=&Apache::lonmsg::decide_receiver('',0,$question,
 2953: 							 $course,$policy);
 2954:     return scalar(%to);
 2955: }
 2956: 
 2957: sub send_msg {
 2958:     my ($title,$feedurl,$email,$citations,$attachmenturl,$symb,%to)=@_;
 2959:     my $status='';
 2960:     my $sendsomething=0;
 2961:     my $restitle = &get_resource_title($symb,$feedurl);
 2962:     if ($title=~/^Error/) { $title=&mt('Feedback').': '.$title; }
 2963:     unless ($title=~/\w/) { $title=&mt('Feedback'); }
 2964:     foreach my $key (keys(%to)) {
 2965: 	if ($key) {
 2966: 	    my ($user,$domain) = split(/\:/,$key,2);
 2967: 	    if (!defined($user)) {
 2968: 		$status.='<br />'.&mt('Error sending message to [_1], no user specified.',$key);
 2969: 	    } elsif (!defined($domain)) {
 2970: 		$status.='<br />'.&mt('Error sending message to [_1], no domain specified.',$key);
 2971: 	    } else {
 2972: 		unless (&Apache::lonmsg::user_normal_msg($user,$domain,
 2973: 							 $title.' ['.$restitle.']',$email,$citations,$feedurl,
 2974: 							 $attachmenturl,undef,undef,$symb,$restitle)=~/ok/) {
 2975: 		    $status.='<br />'.&mt('Error sending message to').' '.$key.'<br />';
 2976: 		} else {
 2977: 		    $sendsomething++;
 2978: 		}
 2979: 	    }
 2980: 	}
 2981:     }
 2982: 
 2983: # Records of number of feedback messages are kept under the "symb" called "_feedback"
 2984: # There are two entries within the framework of a course:
 2985: # - the URLs for which feedback was provided
 2986: # - the total number of contributions
 2987:     if ($sendsomething) {
 2988:         my %record=&getfeedbackrecords();
 2989:         my ($temp)=keys(%record);
 2990:         unless ($temp=~/^error\:/) {
 2991: 	    my %newrecord=();
 2992: 	    $newrecord{'resource'}=$feedurl;
 2993: 	    $newrecord{'subnumber'}=$record{'subnumber'}+1;
 2994: 	    unless (&Apache::lonnet::cstore(\%newrecord,'_feedback') eq 'ok') {
 2995: 	        $status.='<br />'.&mt('Not registered').'<br />';
 2996: 	    }
 2997:         }
 2998:     }
 2999:     return ($status,$sendsomething);
 3000: }
 3001: 
 3002: # Routine to get the complete feedback records
 3003: 
 3004: sub getfeedbackrecords {
 3005:     my ($uname,$udom,$course)=@_;
 3006:     unless ($uname) { $uname=$env{'user.name'}; }
 3007:     unless ($udom)  { $udom=$env{'user.domain'}; }
 3008:     unless ($course) { $course=$env{'request.course.id'}; }
 3009:     my %record=&Apache::lonnet::restore('_feedback',$course,$udom,$uname);
 3010:     return %record;
 3011: }
 3012: 
 3013: # Routine to get feedback statistics
 3014: 
 3015: sub getfeedbackstats {
 3016:     my %record=&getfeedbackrecords(@_);
 3017:     return ($record{'subnumber'},$record{'points'},$record{'totallikes'});
 3018: }
 3019: 
 3020: # Store feedback credit
 3021: 
 3022: sub storefeedbackpoints {
 3023:     my ($points,$uname,$udom,$course)=@_;
 3024:     unless ($points) { $points=0; }
 3025:     unless ($uname) { $uname=$env{'user.name'}; }
 3026:     unless ($udom)  { $udom=$env{'user.domain'}; }
 3027:     unless ($course) { $course=$env{'request.course.id'}; }
 3028:     my %record=('grader_user'   => $env{'user.name'},
 3029:                 'grader_domain' => $env{'user.domain'},
 3030:                 'points' => $points);
 3031:     return &Apache::lonnet::cstore(\%record,'_feedback',$course,$udom,$uname);
 3032: }
 3033: 
 3034: # Store feedback "likes"
 3035: 
 3036: sub storefeedbacklikes {
 3037:     my ($likes,$uname,$udom,$course)=@_;
 3038:     unless ($likes) { $likes=0; }
 3039:     if ($likes>0) { $likes=1; }
 3040:     if ($likes<0) { $likes=-1; }
 3041:     unless ($uname) { $uname=$env{'user.name'}; }
 3042:     unless ($udom)  { $udom=$env{'user.domain'}; }
 3043:     unless ($course) { $course=$env{'request.course.id'}; }
 3044:     my %record=&getfeedbackrecords($uname,$udom,$course);
 3045:     my $totallikes=$record{'totallikes'};
 3046:     $totallikes+=$likes;
 3047:     my %newrecord=('likes_user'   => $env{'user.name'},
 3048:                    'likes_domain' => $env{'user.domain'},
 3049:                    'likes' => $likes,
 3050:                    'totallikes' => $totallikes);
 3051:     return &Apache::lonnet::cstore(\%newrecord,'_feedback',$course,$udom,$uname);
 3052: }
 3053: 
 3054: 
 3055: sub adddiscuss {
 3056:     my ($symb,$email,$anon,$attachmenturl,$subject,$group)=@_;
 3057:     my $status='';
 3058:     my $realsymb = &get_realsymb($symb);
 3059:     my ($cnum,$cdom);
 3060:     if ($env{'request.course.id'}) {
 3061:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3062:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3063:     }
 3064:     if (&discussion_open(undef,$realsymb) &&
 3065: 	(&Apache::lonnet::allowed('pch',$env{'request.course.id'}.
 3066:          ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')) || 
 3067:          (($group ne '') && (&check_group_priv($group,'pgd') eq 'ok') && 
 3068:          ($symb =~ m{^bulletin___\d+___adm/wrapper/adm/\Q$cdom\E/\Q$cnum\E/\d+/bulletinboard$})))) {
 3069: 
 3070:     my %contrib=('message'      => $email,
 3071:                  'sendername'   => $env{'user.name'},
 3072:                  'senderdomain' => $env{'user.domain'},
 3073:                  'screenname'   => $env{'environment.screenname'},
 3074:                  'plainname'    => $env{'environment.firstname'}.' '.
 3075: 		                   $env{'environment.middlename'}.' '.
 3076:                                    $env{'environment.lastname'}.' '.
 3077:                                    $env{'enrironment.generation'},
 3078:                  'attachmenturl'=> $attachmenturl,
 3079:                  'subject'      => $subject);
 3080:     if ($env{'form.replydisc'}) {
 3081: 	$contrib{'replyto'}=(split(/\:\:\:/,$env{'form.replydisc'}))[1];
 3082:     }
 3083:     if ($anon) {
 3084: 	$contrib{'anonymous'}='true';
 3085:     }
 3086:     if (($symb) && ($email)) {
 3087:         my $now = time;
 3088:         if ($env{'form.editdisc'}) {
 3089:             $contrib{'ip'}=$ENV{'REMOTE_ADDR'};
 3090:             $contrib{'host'}=$Apache::lonnet::perlvar{'lonHostID'};
 3091:             $contrib{'timestamp'} = $now;
 3092:             $contrib{'history'} = '';
 3093:             my $numoldver = 0;
 3094:             my ($oldsymb,$oldidx)=split(/\:\:\:/,$env{'form.editdisc'});
 3095: 	    &Apache::lonenc::check_decrypt(\$oldsymb);
 3096:             $oldsymb=~s|(bulletin___\d+___)adm/wrapper/|$1|;
 3097: # get timestamp for last post and history
 3098:             my %oldcontrib=&Apache::lonnet::restore($oldsymb,$env{'request.course.id'},
 3099:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 3100:                      $env{'course.'.$env{'request.course.id'}.'.num'});
 3101:             if (defined($oldcontrib{$oldidx.':replyto'})) {
 3102:                 $contrib{'replyto'} = $oldcontrib{$oldidx.':replyto'};
 3103:             }
 3104:             if (defined($oldcontrib{$oldidx.':history'})) {
 3105:                 if ($oldcontrib{$oldidx.':history'} =~ /:/) {
 3106:                     my @oldversions = split(/:/,$oldcontrib{$oldidx.':history'});
 3107:                     $numoldver = @oldversions;
 3108:                 } else {
 3109:                     $numoldver = 1;
 3110:                 }
 3111:                 $contrib{'history'} = $oldcontrib{$oldidx.':history'}.':';
 3112:             }
 3113:             my $numnewver = $numoldver + 1;
 3114:             if (defined($oldcontrib{$oldidx.':subject'})) {
 3115:                 if ($oldcontrib{$oldidx.':subject'} =~ /^<version num="0">/) {
 3116:                     $contrib{'subject'} = '<version num="'.$numnewver.'">'.&HTML::Entities::encode($contrib{'subject'},'<>&"').'</version>';
 3117:                     $contrib{'subject'} = $oldcontrib{$oldidx.':subject'}.$contrib{'subject'};
 3118:                 } else {
 3119:                     $contrib{'subject'} = '<version num="0">'.&HTML::Entities::encode($oldcontrib{$oldidx.':subject'},'<>&"').'</version><version num="1">'.&HTML::Entities::encode($contrib{'subject'},'<>&"').'</version>';
 3120:                 }
 3121:             } 
 3122:             if (defined($oldcontrib{$oldidx.':message'})) {
 3123:                 if ($oldcontrib{$oldidx.':message'} =~ /^<version num="0">/) {
 3124:                     $contrib{'message'} = '<version num="'.$numnewver.'">'.&HTML::Entities::encode($contrib{'message'},'<>&"').'</version>';
 3125:                     $contrib{'message'} = $oldcontrib{$oldidx.':message'}.$contrib{'message'};
 3126:                 } else {
 3127:                     $contrib{'message'} = '<version num="0">'.&HTML::Entities::encode($oldcontrib{$oldidx.':message'},'<>&"').'</version><version num="1">'.&HTML::Entities::encode($contrib{'message'},'<>&"').'</version>';
 3128:                 }
 3129:             }
 3130:             $contrib{'history'} .= $oldcontrib{$oldidx.':timestamp'};
 3131:             my $put_reply = &Apache::lonnet::putstore($env{'request.course.id'},
 3132:                   $oldsymb,$oldidx,\%contrib,
 3133:                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 3134:                   $env{'course.'.$env{'request.course.id'}.'.num'});
 3135:             $status='Editing class discussion'.($anon?' (anonymous)':'');
 3136:         } else {
 3137:            $status='Adding to class discussion'.($anon?' (anonymous)':'').': '.
 3138:            &Apache::lonnet::store(\%contrib,$symb,$env{'request.course.id'},
 3139:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 3140: 		     $env{'course.'.$env{'request.course.id'}.'.num'});
 3141:         }
 3142:         my %storenewentry=($symb => $now);
 3143:         $status.='<br />'.&mt('Updating discussion time').': '.
 3144:         &Apache::lonnet::put('discussiontimes',\%storenewentry,
 3145:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 3146: 		     $env{'course.'.$env{'request.course.id'}.'.num'});
 3147:     }
 3148:     my %record=&getdiscussionrecords();
 3149:     my ($temp)=keys(%record);
 3150:     unless ($temp=~/^error\:/) {
 3151:        my %newrecord=();
 3152:        $newrecord{'resource'}=$symb;
 3153:        $newrecord{'subnumber'}=$record{'subnumber'}+1;
 3154:        $status.='<br />'.&mt('Registering').': '.
 3155:                &Apache::lonnet::cstore(\%newrecord,'_discussion');
 3156:        &updatekarma();
 3157:     }
 3158:     } else {
 3159: 	$status.='Failed.';
 3160:     }
 3161:     return $status.'<br />';   
 3162: }
 3163: 
 3164: 
 3165: # Routine to get the complete discussion records
 3166: 
 3167: sub getdiscussionrecords {
 3168:     my ($uname,$udom,$course)=@_;
 3169:     unless ($uname) { $uname=$env{'user.name'}; }
 3170:     unless ($udom)  { $udom=$env{'user.domain'}; }
 3171:     unless ($course) { $course=$env{'request.course.id'}; }
 3172:     my %record=&Apache::lonnet::restore('_discussion',$course,$udom,$uname);
 3173:     return %record;
 3174: }
 3175: 
 3176: # Routine to get discussion statistics
 3177: 
 3178: sub getdiscussionstats {
 3179:     my %record=&getdiscussionrecords(@_);
 3180:     return ($record{'subnumber'},$record{'points'},$record{'totallikes'},$record{'totalvotes'});
 3181: }
 3182: 
 3183: # Calculate discussion karma
 3184: 
 3185: sub calcdiscussionkarma {    
 3186:     my ($subs,$pts,$likes,$votes)=&getdiscussionstats(@_);
 3187:     my $karma=0;
 3188:     if ($votes>0) {
 3189:         $karma=int(.1+5.*(1.-exp(-$subs/10.))*$likes/$votes);
 3190:         if ($karma<0) { $karma=0; }
 3191:         if ($karma>5) { $karma=5; }
 3192:     }
 3193:     return $karma;
 3194: }
 3195: 
 3196: # Update karma
 3197: 
 3198: sub updatekarma {
 3199:     my ($uname,$udom,$course)=@_;
 3200:     unless ($uname) { $uname=$env{'user.name'}; }
 3201:     unless ($udom)  { $udom=$env{'user.domain'}; }
 3202:     unless ($course) { $course=$env{'request.course.id'}; }
 3203:     my $karma=&calcdiscussionkarma($uname,$udom,$course);
 3204:     &Apache::lonnet::cstore({ 'karma' => $karma },'_discussion',$course,$udom,$uname);
 3205:     &Apache::lonnet::do_cache_new('karma',$uname.':'.$udom.':'.$course,$karma,3600);
 3206:     return $karma;
 3207: }
 3208: 
 3209: # Retrieve karma
 3210: 
 3211: sub userkarma {
 3212:     my ($uname,$udom,$course)=@_;
 3213:     unless ($uname) { $uname=$env{'user.name'}; }
 3214:     unless ($udom)  { $udom=$env{'user.domain'}; }
 3215:     unless ($course) { $course=$env{'request.course.id'}; }
 3216:     my $hashkey=$uname.':'.$udom.':'.$course;
 3217:     my ($karma,$cached)=&Apache::lonnet::is_cached_new('karma',$hashkey);
 3218:     if ($cached) {
 3219:         return $karma;
 3220:     }
 3221:     my %userdisc=&getdiscussionrecords($uname,$udom,$course);
 3222:     $karma=$userdisc{'karma'};
 3223:     &Apache::lonnet::do_cache_new('karma',$hashkey,$karma,3600);
 3224:     return $karma;
 3225: }
 3226: 
 3227: # Store discussion credit
 3228: 
 3229: sub storediscussionpoints {
 3230:     my ($points,$uname,$udom,$course)=@_;
 3231:     unless ($points) { $points=0; }
 3232:     unless ($uname) { $uname=$env{'user.name'}; }
 3233:     unless ($udom)  { $udom=$env{'user.domain'}; }
 3234:     unless ($course) { $course=$env{'request.course.id'}; }
 3235:     my %record=('grader_user'   => $env{'user.name'},
 3236:                 'grader_domain' => $env{'user.domain'},
 3237:                 'points' => $points);
 3238:     return &Apache::lonnet::cstore(\%record,'_discussion',$course,$udom,$uname);
 3239: }
 3240: 
 3241: # Store discussion "likes"
 3242: 
 3243: sub storediscussionlikes {
 3244:     my ($likes,$uname,$udom,$course)=@_;
 3245:     unless ($likes) { $likes=0; }
 3246:     if ($likes>0) { $likes=1; }
 3247:     if ($likes<0) { $likes=-1; }
 3248:     unless ($uname) { $uname=$env{'user.name'}; }
 3249:     unless ($udom)  { $udom=$env{'user.domain'}; }
 3250:     unless ($course) { $course=$env{'request.course.id'}; }
 3251:     my %record=&getdiscussionrecords($uname,$udom,$course);
 3252:     my $totallikes=$record{'totallikes'};
 3253:     my $totalvotes=$record{'totalvotes'};
 3254:     $totallikes+=$likes;
 3255:     $totalvotes++;
 3256:     my %newrecord=('likes_user'   => $env{'user.name'},
 3257:                    'likes_domain' => $env{'user.domain'},
 3258:                    'likes' => $likes,
 3259:                    'totallikes' => $totallikes,
 3260:                    'totalvotes' => $totalvotes);
 3261:     my $status=&Apache::lonnet::cstore(\%newrecord,'_discussion',$course,$udom,$uname);
 3262:     if ($status eq 'ok') {
 3263:         &updatekarma($uname,$udom,$course);
 3264:     }
 3265:     return $status;
 3266: }
 3267: 
 3268: sub get_discussion_info {
 3269:     my ($idx,%contrib) = @_;
 3270:     my $changelast = 0;
 3271:     my $count = 0;
 3272:     my $hiddenflag = 0;
 3273:     my $deletedflag = 0;
 3274:     my ($hidden,$deleted,%info,$newlastdisc);
 3275:     my $version = $contrib{'version'};
 3276:     if ($version) {
 3277:         for (my $id=$version; $id>0; $id--) {
 3278:             my $vkeys=$contrib{$id.':keys'};
 3279:             my @keys=split(/:/,$vkeys);
 3280:             if (grep(/^hidden$/,@keys)) {
 3281:                 if (!$hiddenflag) {
 3282:                     $hidden = $contrib{$id.':hidden'};
 3283:                     $hiddenflag = 1;
 3284:                 }
 3285:             } elsif (grep(/^deleted$/,@keys)) {
 3286:                 if (!$deletedflag) {
 3287:                     $deleted = $contrib{$id.':deleted'};
 3288:                     $deletedflag = 1;
 3289:                 }
 3290:             } else {
 3291:                 if (($hidden !~/\.$id\./) && ($deleted !~/\.$id\./)) {
 3292:                     $count++;
 3293:                     $info{$count}{'id'} = $id;
 3294:                     $info{$count}{'timestamp'}=$contrib{$id.':timestamp'}; 
 3295:                 }
 3296:             }
 3297:         }
 3298:         if ($info{'1'}{'id'} == $idx) {
 3299:             $changelast = 1;
 3300:             if ($count > 1) { 
 3301:                 $newlastdisc =  $info{'2'}{'timestamp'};
 3302:             } else {
 3303:                 $newlastdisc = 0;
 3304:             }
 3305:         }
 3306:     }
 3307:     return ($changelast,$newlastdisc);
 3308: }
 3309: 
 3310: # ----------------------------------------------------------- Preview function
 3311: 
 3312: sub show_preview {
 3313:     my ($r) = @_;
 3314:     &Apache::loncommon::content_type($r,'text/html');
 3315:     $r->send_http_header;
 3316:     my $start_page=
 3317: 	&Apache::loncommon::start_page('Preview',undef,
 3318: 				       {'only_body'   => 1,});
 3319: 
 3320:     my $message=&clear_out_html($env{'form.comment'});
 3321:     &newline_to_br(\$message);
 3322:     $message=&Apache::lonspeller::markeduptext($message);
 3323:     $message=&Apache::lontexconvert::msgtexconverted($message);
 3324:     my $subject=&clear_out_html($env{'form.subject'});
 3325:     $subject=~s/\n/\<br \/\>/g;
 3326:     $subject=&Apache::lontexconvert::msgtexconverted($subject);
 3327: 					
 3328:     my $end_page = &Apache::loncommon::end_page();
 3329: 
 3330:     $r->print($start_page
 3331:              .'<h1>'.&mt('Preview').'</h1>'
 3332:              .&Apache::lonhtmlcommon::start_pick_box()
 3333:              .&Apache::lonhtmlcommon::row_title(&mt('Subject'))
 3334:              .$subject
 3335:              .&Apache::lonhtmlcommon::row_closure()
 3336:              .&Apache::lonhtmlcommon::row_title(&mt('Message'))
 3337:              .$message
 3338:              .&Apache::lonhtmlcommon::row_closure(1)
 3339:              .&Apache::lonhtmlcommon::end_pick_box()
 3340:              .$end_page
 3341:     );
 3342: }
 3343: 
 3344: sub contains_block_html {
 3345:     my ($message)=@_;
 3346:     return ($message =~ m{
 3347:         <(br|h1|h2|h3|h4|h5|h6|p|ol|ul|table|pre|address|blockquote|center|div) 
 3348: 	  \s*
 3349: 	 (\w+\=['"]\w+['"])*
 3350: 	  \s*
 3351: 	(
 3352: 	  \s*/>|
 3353: 	  >.*</\1\s*>
 3354: 	)}xs 
 3355:     );
 3356: }
 3357: 
 3358: sub tidy_html {
 3359: 	my ($message)=@_;
 3360: # 	my $tidy = HTML::Tidy::libXML->new();
 3361: # 	my $xhtml = $tidy->clean($message, 'utf-8', 1);
 3362: # 	$xhtml =~ m/<body>(.*)<\/body>/is;
 3363: # 	my $clean = $1;
 3364: # 	# remove any empty block-level tags
 3365: # 	$clean =~ s/<(table|p|div|tbody|blockquote|m|pre|algebra|center|ol|ul|span|h1|h2|h3|h4|h5|h6)\s*\/>//i;
 3366: # 	$message=$clean;
 3367: 	return $message;
 3368: }
 3369: 
 3370: sub newline_to_br {
 3371:     my ($message)=@_;
 3372:     my $newmessage;
 3373:     my $parser=HTML::LCParser->new($message);
 3374:     while (my $token=$parser->get_token()) {
 3375: 	if ($token->[0] eq 'T') {
 3376: 	    my $text=$token->[1];
 3377: 	    $text=~s/\n/\<br \/\>/g;
 3378: 	    $newmessage.=$text;
 3379: 	} elsif ($token->[0] eq 'D' || $token->[0] eq 'C') {
 3380: 	    $newmessage.=$token->[1];
 3381: 	} elsif ($token->[0] eq 'PI' || $token->[0] eq 'E') {
 3382: 	    $newmessage.=$token->[2];
 3383: 	} elsif ($token->[0] eq 'S') {
 3384: 	    $newmessage.=$token->[4];
 3385: 	}
 3386: 	    
 3387:     }
 3388:     $$message=$newmessage;
 3389: }
 3390: 
 3391: sub generate_preview_button {
 3392:     my ($formname,$fieldname)=@_;
 3393:     unless ($formname) { $formname='mailform'; }
 3394:     unless ($fieldname) { $fieldname='comment'; }
 3395:     my $pre=&mt("Show Preview and Check Spelling");
 3396:     return(<<ENDPREVIEW);
 3397: <br />
 3398: <form name="preview" action="/adm/feedback?preview=1" method="post" target="preview">
 3399: <input type="hidden" name="subject" />
 3400: <input type="hidden" name="comment" />
 3401: <input type="button" value="$pre"
 3402: 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();" />
 3403: </form>
 3404: ENDPREVIEW
 3405: }
 3406: 
 3407: sub modify_attachments {
 3408:     my ($r,$currnewattach,$currdelold,$symb,$idx,$attachmenturls,
 3409:         $attachmaxtext,$toolarge)=@_;
 3410: 
 3411:     my %lt = &Apache::lonlocal::texthash(
 3412:                'subj' => 'Subject',
 3413:                'chth' => 'Check the checkboxes for any you wish to remove.',
 3414:                'thef' => 'The following attachments have been uploaded for inclusion with this posting.',
 3415:                'adda' => 'Add a new attachment to this post',
 3416:                'stch' => 'Save Changes',
 3417:                'clic' => 'Add/remove attachments',
 3418:              );
 3419:     my $js = <<END;
 3420: <script type="text/javascript">
 3421:  function setAction () {
 3422:    document.modattachments.action = document.modattachments.origpage.value;
 3423:    document.modattachments.submit();
 3424:  }
 3425: </script> 
 3426: END
 3427: 
 3428:     # Breadcrumbs
 3429:     my $brcrum = [{'href' => '',
 3430:                    'text' => 'Discussion Post Attachments'}];
 3431:     my %parms=('only_body' => 1);
 3432:     if ($env{'form.modal'} ne 'yes') { 'bread_crumbs' => $brcrum }
 3433: 
 3434:     my $start_page = 
 3435: 	&Apache::loncommon::start_page('Discussion Post Attachments',$js,\%parms);
 3436: 
 3437:     my $orig_subject = &unescape($env{'form.subject'});
 3438:     my $subject=&clear_out_html($orig_subject);
 3439:     $subject=~s/\n/\<br \/\>/g;
 3440:     $subject=&Apache::lontexconvert::msgtexconverted($subject);
 3441:     my $timestamp=$env{'form.timestamp'};
 3442:     my $numoldver=$env{'form.numoldver'};
 3443: 
 3444:     my $msg = '';
 3445:     my %attachments = ();
 3446:     my %currattach = ();
 3447:     if ($idx) {
 3448:         &extract_attachments($attachmenturls,$idx,$numoldver,\$msg,\%attachments,\%currattach,$currdelold);
 3449:     }
 3450:     &Apache::lonenc::check_encrypt(\$symb);
 3451: 
 3452:     my $end_page = 
 3453: 	&Apache::loncommon::end_page();
 3454: 				       
 3455:     $r->print(<<END);
 3456: $start_page
 3457: $toolarge
 3458: <form name="modattachments" method="post" enctype="multipart/form-data" action="/adm/feedback?attach=$symb">
 3459:  <br />
 3460:  <h1>$lt{'clic'}</h1>
 3461: END
 3462:     $r->print(&Apache::lonhtmlcommon::start_pick_box());
 3463:     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Subject')));
 3464:     $r->print('<b>'.$subject.'</b>');
 3465:     $r->print(&Apache::lonhtmlcommon::row_closure());
 3466:     $r->print(&Apache::lonhtmlcommon::row_title($lt{'adda'}));
 3467:     $r->print('<input type="file" name="addnewattach" /><input type="button" name="upload" value="Upload" onclick="this.form.submit()" />  '.$attachmaxtext);
 3468:     if(($idx)||(ref($currnewattach) eq 'ARRAY') && (@{$currnewattach} > 0)){
 3469:         $r->print(&Apache::lonhtmlcommon::row_closure());
 3470:         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Attachments')));
 3471:         if ($idx) {
 3472:             if ($attachmenturls) {
 3473:                 my @currold = keys(%currattach);
 3474:                 if (@currold > 0) {
 3475:                     $r->print($lt{'thfo'}.'<br />'.$lt{'chth'}.'<br />'."\n");
 3476:                     foreach my $id (@currold) {
 3477:                         my $attachurl = &HTML::Entities::decode($attachments{$id}{'filename'});
 3478:                         $attachurl =~ m#/([^/]+)$#;
 3479:                         $r->print('<label><input type="checkbox" name="deloldattach" value="'.$id.'" />&nbsp;'.$1.'</label><br />'."\n");
 3480:                     }
 3481:                     $r->print("<br />");
 3482:                 }
 3483:             }
 3484:         }
 3485:     }
 3486:     $r->print(&Apache::lonhtmlcommon::row_closure(1));
 3487:     $r->print(&Apache::lonhtmlcommon::end_pick_box());
 3488:     $r->print(<<END);
 3489: <input type="hidden" name="subject" value="$env{'form.subject'}" />
 3490: <input type="hidden" name="comment" value="$env{'form.comment'}" />
 3491: <input type="hidden" name="timestamp" value="$env{'form.timestamp'}" />
 3492: <input type="hidden" name="idx" value="$env{'form.idx'}" />
 3493: <input type="hidden" name="numoldver" value="$env{'form.numoldver'}" />
 3494: <input type="hidden" name="origpage" value="$env{'form.origpage'}" />
 3495: <input type="hidden" name="blog" value="$env{'form.blog'}" />
 3496: <input type="hidden" name="discuss" value="$env{'form.discuss'}" />
 3497: END
 3498:     foreach my $item (@{$currnewattach}) {
 3499:         $r->print('<input type="hidden" name="currnewattach" value="'.$item.'" />'."\n");
 3500:     }
 3501:     foreach my $item (@{$currdelold}) {
 3502:         $r->print('<input type="hidden" name="deloldattach" value="'.$item.'" />'."\n");
 3503:     }
 3504:     $r->print(<<END);
 3505:  <input type="button" name="rtntoedit" value="$lt{'stch'}" onclick="setAction()" />
 3506: </form>
 3507: $end_page
 3508: END
 3509:     return;
 3510: }
 3511: 
 3512: sub process_attachments {
 3513:     my ($currnewattach,$currdelold,$keepold) = @_;
 3514: 
 3515:     @{$currnewattach}=
 3516: 	&Apache::loncommon::get_env_multiple('form.currnewattach');
 3517:     @{$currdelold}=
 3518: 	&Apache::loncommon::get_env_multiple('form.deloldattach');
 3519:     if (exists($env{'form.delnewattach'})) {
 3520:         my @currdelnew =
 3521: 	    &Apache::loncommon::get_env_multiple('form.delnewattach');
 3522:         my @currnew = ();
 3523:         foreach my $newone (@{$currnewattach}) {
 3524:             my $delflag = 0;
 3525:             foreach my $item (@currdelnew) {
 3526:                 if ($newone eq $item) {
 3527:                     $delflag = 1;
 3528:                     last;
 3529:                 }
 3530:             }
 3531:             unless ($delflag) {
 3532:                 push(@currnew, $newone);
 3533:             }
 3534:         }
 3535:         @{$currnewattach} = @currnew;
 3536:     }
 3537:     @{$keepold} = &Apache::loncommon::get_env_multiple('form.keepold');
 3538: }
 3539: 
 3540: sub generate_attachments_button {
 3541:     my ($idx,$attachnum,$ressymb,$now,$currnewattach,$deloldattach,
 3542:         $numoldver,$mode,$blockblog) = @_;
 3543:     my $origpage = $ENV{'REQUEST_URI'};
 3544:     my $att=$attachnum.' '.&mt("attachments");
 3545:     my %lt = &Apache::lonlocal::texthash(
 3546:                 'clic' => 'Add/remove attachments',
 3547:     ); 
 3548:     my $response = (<<END);
 3549: <br />
 3550: <form name="attachment" action="/adm/feedback?attach=$ressymb" method="post">
 3551: <input type="button" value="$lt{'clic'}"
 3552: 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);
 3553: END
 3554:     if (!$blockblog) {
 3555:         $response .= 'setblogvalue();';
 3556:     }
 3557:     unless ($mode eq 'board') {
 3558:         $response .= 'javascript:anonchk();';
 3559:     }
 3560:     $response .= (<<ENDATTACH);
 3561: this.form.submit();" />
 3562: <input type="hidden" name="origpage" value="$origpage" />
 3563: <input type="hidden" name="idx" value="$idx" />
 3564: <input type="hidden" name="timestamp" value="$now" />
 3565: <input type="hidden" name="subject" />
 3566: <input type="hidden" name="comment" />
 3567: <input type="hidden" name="blog" value="0" />
 3568: <input type="hidden" name="discuss" value="0" />
 3569: <input type="hidden" name="numoldver" value="$numoldver" />
 3570: ENDATTACH
 3571:     if (defined($deloldattach)) {
 3572:         if (@{$deloldattach} > 0) {
 3573:             foreach my $delatt (@{$deloldattach}) {
 3574:                 $response .= '<input type="hidden" name="deloldattach" value="'.$delatt.'" />'."\n";
 3575:             }
 3576:         }
 3577:     }
 3578:     if (defined($currnewattach)) {
 3579:         if (@{$currnewattach} > 0) {
 3580:             foreach my $attach (@{$currnewattach}) {
 3581:                 $response .= '<input type="hidden" name="currnewattach" value="'.$attach.'" />'."\n";
 3582:             }
 3583:         }
 3584:     }
 3585:     $response .= '</form>';
 3586:     return $response;
 3587: }
 3588: 
 3589: sub extract_attachments {
 3590:     my ($attachmenturls,$idx,$numoldver,$message,$attachments,$currattach,$currdelold) = @_;
 3591:     %{$attachments}=();
 3592:     &get_post_attachments($attachments,$attachmenturls);
 3593:     foreach my $id (sort(keys(%{$attachments}))) {
 3594:         if (exists($$attachments{$id}{$numoldver})) {
 3595:             if (defined($currdelold)) {
 3596:                 if (@{$currdelold} > 0) {
 3597:                     unless (grep/^$id$/,@{$currdelold}) {
 3598:                         $$currattach{$id} = $$attachments{$id}{$numoldver}; 
 3599:                     }
 3600:                 } else {
 3601:                     $$currattach{$id} = $$attachments{$id}{$numoldver};
 3602:                 }
 3603:             } else {
 3604:                 $$currattach{$id} = $$attachments{$id}{$numoldver};
 3605:             }
 3606:         }
 3607:     }
 3608:     my @attached = (sort { $a <=> $b } keys(%{$currattach}));
 3609:     if (@attached == 1) {
 3610:         my $id = $attached[0];
 3611:         my $attachurl;
 3612:         if ($attachmenturls =~ m/^<attachment id="0">/) {
 3613:             $attachurl = &HTML::Entities::decode($$attachments{$id}{'filename'});
 3614:         } else {
 3615:             $attachurl = $$attachments{$id}{'filename'};
 3616:         }
 3617:         $attachurl=~m|/([^/]+)$|;
 3618:         $$message.='<br /><a href="'.$attachurl.'"><tt>'.
 3619:         $1.'</tt></a><br />';
 3620:         &Apache::lonnet::allowuploaded('/adm/feedback',
 3621:                                $attachurl);
 3622:     } elsif (@attached > 1) {
 3623:         $$message.='<ol>';
 3624:         foreach my $attach (@attached) {
 3625:             my $id = $attach;
 3626:             my $attachurl = &HTML::Entities::decode($$attachments{$id}{'filename'});
 3627:             my ($fname)
 3628:               =($attachurl=~m|/([^/]+)$|);
 3629:             $$message .= '<li><a href="'.$attachurl.
 3630:               '"><tt>'.
 3631:               $fname.'</tt></a></li>';
 3632:             &Apache::lonnet::allowuploaded('/adm/feedback',
 3633:                              $attachurl);
 3634:         }
 3635:         $$message .= '</ol>';
 3636:     }
 3637: }
 3638: 
 3639: sub construct_attachmenturl {
 3640:     my ($currnewattach,$keepold,$symb,$idx)=@_;
 3641:     my $oldattachmenturl;
 3642:     my $newattachmenturl;
 3643:     my $startnum = 0;
 3644:     my $currver = 0;
 3645:     if (($env{'form.editdisc'}) && ($idx)) {
 3646:         my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 3647:                        $env{'course.'.$env{'request.course.id'}.'.domain'},
 3648:                        $env{'course.'.$env{'request.course.id'}.'.num'});
 3649:         $oldattachmenturl = $contrib{$idx.':attachmenturl'};
 3650:         if ($contrib{$idx.':history'}) {
 3651:             if ($contrib{$idx.':history'} =~ /:/) {
 3652:                 my @oldversions = split(/:/,$contrib{$idx.':history'});
 3653:                 $currver = 1 + scalar(@oldversions);
 3654:             } else {
 3655:                 $currver = 2;
 3656:             }
 3657:         } else {
 3658:             $currver = 1;
 3659:         }
 3660:         if ($oldattachmenturl) {
 3661:             if ($oldattachmenturl =~ m/^<attachment id="0">/) {
 3662:                 my %attachments = ();
 3663:                 my $prevver = $currver-1;
 3664:                 &get_post_attachments(\%attachments,$oldattachmenturl);
 3665:                 my $numattach = scalar(keys(%attachments));
 3666:                 $startnum += $numattach;
 3667:                 foreach my $num (sort {$a <=> $b} keys(%attachments)) {
 3668:                     $newattachmenturl .= '<attachment id="'.$num.'"><filename>'.$attachments{$num}{'filename'}.'</filename>';
 3669:                     foreach my $item (sort {$a <=> $b} keys(%{$attachments{$num}})) {
 3670:                         unless ($item eq 'filename') {
 3671:                             $newattachmenturl .= '<post id="'.$item.'">'.$attachments{$num}{$item}.'</post>';
 3672:                         }
 3673:                     }
 3674:                     if (grep/^$num$/,@{$keepold}) {
 3675:                         $newattachmenturl .= '<post id="'.$currver.'">'.$attachments{$num}{$prevver}.'</post>';
 3676:                     }
 3677:                     $newattachmenturl .= '</attachment>';
 3678:                 }
 3679:             } else {
 3680:                 $newattachmenturl = '<attachment id="0"><filename>'.&HTML::Entities::encode($oldattachmenturl).'</filename><post id="0">n</post>';
 3681:                 unless (grep/^0$/,@{$keepold}) {
 3682:                     $newattachmenturl .= '<post id="1">n</post>';
 3683:                 }
 3684:                 $newattachmenturl .= '</attachment>';
 3685:                 $startnum ++;
 3686:             }
 3687:         }
 3688:     }
 3689:     for (my $i=0; $i<@{$currnewattach}; $i++) {
 3690:         my $attachnum = $startnum + $i;
 3691:         $newattachmenturl .= '<attachment id="'.$attachnum.'"><filename>'.&HTML::Entities::encode($$currnewattach[$i]).'</filename><post id="'.$currver.'">n</post></attachment>';
 3692:     }
 3693:     return $newattachmenturl; 
 3694: }
 3695: 
 3696: sub add_blog_checkbox {
 3697:     my ($crstype) = @_;
 3698:     my $checkstatus;
 3699:     if ($env{'form.blog'}) {
 3700:         $checkstatus = 'checked="checked"';
 3701:     }
 3702:     my $output = '
 3703: <script type="text/javascript">
 3704: function setblogvalue() {
 3705:     if (document.mailform.blog.checked) {
 3706:         document.attachment.blog.value = 1;
 3707:     } else {
 3708:         document.attachment.blog.value = 0;
 3709:     }
 3710: }
 3711: </script><br />
 3712: <label><input type="checkbox" name="blog" '.$checkstatus.' /> ';
 3713:     if ($crstype eq 'Community') {
 3714:         $output .= &mt('Add to my public community blog');
 3715:     } else {
 3716:         $output .= &mt('Add to my public course blog');
 3717:     } 
 3718:     $output .= '</label><br />'."\n";
 3719:     return $output;
 3720: }
 3721: 
 3722: sub has_discussion {
 3723:     my $resourcesref = shift;
 3724:     my $navmap = Apache::lonnavmaps::navmap->new();
 3725:     if (defined($navmap)) {
 3726:         my @allres=$navmap->retrieveResources();
 3727:         foreach my $resource (@allres) {
 3728:             if ($resource->hasDiscussion()) {
 3729:                 my $ressymb = $resource->wrap_symb();
 3730:                 if (ref($resourcesref) eq 'ARRAY') {
 3731:                     push(@{$resourcesref}, $ressymb);
 3732:                 }
 3733:             }
 3734:         }
 3735:     } else {
 3736:         &Apache::lonnet::logthis('Has discussion check failed - could not create navmap object.');
 3737:     }
 3738:     return;
 3739: }
 3740: 
 3741: sub sort_filter_names {
 3742:     my ($sort_types,$role_types,$status_types,$crstype) = @_;
 3743:     if (ref($sort_types) eq 'HASH') {
 3744:         %{$sort_types} = (
 3745:                      ascdate => 'Date order - oldest first',
 3746:                      descdate => 'Date order - newest first',
 3747:                      thread => 'Threaded',
 3748:                      subject => 'By subject',
 3749:                      username => 'By domain and username',
 3750:                      lastfirst => 'By last name, first name'
 3751:                    );
 3752:     }
 3753:     my @courseroles = qw(st in ta ep ad);
 3754:     if ($crstype eq 'Community') {
 3755:         push(@courseroles,'co');
 3756:     } else {
 3757:         push(@courseroles,'cc');
 3758:     }
 3759:     if (ref($role_types) eq 'HASH') {
 3760:         foreach my $role (@courseroles) {
 3761:             $role_types->{$role} = &Apache::lonnet::plaintext($role,$crstype);
 3762:         }
 3763:         $role_types->{'all'} = 'All roles';
 3764:         $role_types->{'cr'} = 'Custom role';
 3765:     }
 3766:     if (ref($status_types) eq 'HASH') {
 3767:         %{$status_types} = (
 3768:                      all     => 'Roles of any status',
 3769:                      Active  => 'Only active roles',
 3770:                      Expired => 'Only past roles',
 3771:                      Future  => 'Only future roles',
 3772:                    );
 3773:     }
 3774: }
 3775:   
 3776: sub handler {
 3777:   my $r = shift;
 3778:   if ($r->header_only) {
 3779:      &Apache::loncommon::content_type($r,'text/html');
 3780:      $r->send_http_header;
 3781:      return OK;
 3782:   }
 3783: 
 3784: # --------------------------- Get query string for limited number of parameters
 3785: 
 3786:   &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 3787:          ['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']);
 3788:   my $group = $env{'form.group'};
 3789:   my %attachmax = (
 3790:                     text => &mt('(128 KB max size)'),
 3791:                     num  => 131072,
 3792:                   );
 3793:   if ($env{'form.editdisc'}) {
 3794:       if (!(&editing_allowed($env{'form.editdisc'},$env{'form.group'}))) {
 3795:           my $symb=(split(/\:\:\:/,$env{'form.editdisc'}))[0];
 3796:           my ($map,$id,$url)=&Apache::lonnet::decode_symb($symb);
 3797:           my $feedurl=&Apache::lonnet::clutter($url);
 3798:           &redirect_back($r,$feedurl,&mt('Editing not permitted').'<br />',                     '0','0','','',$env{'form.previous'},undef,undef,undef,
 3799:                     undef,undef,undef,$group);
 3800:           return OK;
 3801:       }
 3802:   } 
 3803:   if ($env{'form.discsymb'}) {
 3804:       my ($symb,$feedurl) = &get_feedurl_and_clean_symb($env{'form.discsymb'});
 3805:       my $readkey = $symb.'_read';
 3806:       my $chgcount = 0;
 3807:       my %readinghash = &Apache::lonnet::get('nohist_'.$env{'request.course.id'}.'_discuss',[$readkey],$env{'user.domain'},$env{'user.name'});
 3808:       foreach my $key (keys(%env)) {
 3809:           if ($key =~ m/^form\.postunread_(\d+)/) {
 3810:               if ($readinghash{$readkey} =~ /\.$1\./) {
 3811:                   $readinghash{$readkey} =~ s/\.$1\.//;
 3812:                   $chgcount ++;
 3813:               }
 3814:           } elsif ($key =~ m/^form\.postread_(\d+)/) {
 3815:               unless ($readinghash{$readkey} =~ /\.$1\./) {
 3816:                   $readinghash{$readkey} .= '.'.$1.'.';
 3817:                   $chgcount ++;
 3818:               }
 3819:           }
 3820:       }
 3821:       if ($chgcount > 0) {
 3822:           &Apache::lonnet::put('nohist_'.$env{'request.course.id'}.'_discuss',
 3823: 			  \%readinghash,$env{'user.domain'},$env{'user.name'});
 3824:       }
 3825:       &redirect_back($r,$feedurl,&mt('Marked postings read/unread').'<br />',
 3826: 		     '0','0','','',$env{'form.previous'},'','','',
 3827:                      undef,undef,undef,$group);
 3828:       return OK;
 3829:   }
 3830:   if ($env{'form.allversions'}) {
 3831:       &Apache::loncommon::content_type($r,'text/html');
 3832:       &Apache::loncommon::no_cache($r);
 3833:       $r->send_http_header;
 3834: 
 3835:       # Breadcrumbs
 3836:       my $brcrum = [{'href' => '',
 3837:                      'text' => 'Discussion Post Versions'}];
 3838:       
 3839:       my %parms=();
 3840:       if ($env{'form.modal'} ne 'yes') { 'bread_crumbs' => $brcrum }
 3841: 
 3842:       $r->print(&Apache::loncommon::start_page('Discussion Post Versions',undef,\%parms));
 3843: 
 3844:       my $crs='/'.$env{'request.course.id'};
 3845:       if ($env{'request.course.sec'}) {
 3846:           $crs.='_'.$env{'request.course.sec'};
 3847:       }
 3848:       $crs=~s|_|/|g;
 3849:       my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3850:       my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3851:       my ($symb,$idx)=split(/\:\:\:/,$env{'form.allversions'});
 3852:       ($symb)=&get_feedurl_and_clean_symb($symb);
 3853:       my $ressymb = &wrap_symb($symb);
 3854:       my $group = $env{'form.group'};
 3855:       my $seeid;
 3856:       if (($group ne '') && (($ressymb =~ m|^bulletin___\d+___adm/wrapper/adm/\Q$cdom\E/\Q$cnum\E/\d+/bulletinboard$|))) {
 3857:           if (&check_group_priv($group,'dgp') eq 'ok') {
 3858:               $seeid = 1;
 3859:           }
 3860:       } else {
 3861:           $seeid = &Apache::lonnet::allowed('rin',$crs);
 3862:       }
 3863:       if ($idx > 0) {
 3864:           my %messages = ();
 3865:           my %subjects = ();
 3866:           my %attachmsgs = ();
 3867:           my %allattachments = ();
 3868:           my %imsfiles = ();
 3869:           my ($screenname,$plainname,$showaboutme);
 3870:           my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 3871:                            $env{'course.'.$env{'request.course.id'}.'.domain'},
 3872:                            $env{'course.'.$env{'request.course.id'}.'.num'});
 3873:           $r->print(&get_post_contents(\%contrib,$idx,$seeid,'allversions',\%messages,\%subjects,\%allattachments,\%attachmsgs,\%imsfiles,\$screenname,\$plainname,\$showaboutme));
 3874:       }
 3875:       $r->print(&Apache::loncommon::end_page());
 3876:       return OK;
 3877:   }
 3878:   if ($env{'form.posterlist'}) {
 3879:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.applysort'});
 3880:       &print_showposters($r,$symb,$env{'form.previous'},$feedurl,
 3881: 			 $env{'form.sortposts'});
 3882:       return OK;
 3883:   }
 3884:   if ($env{'form.userpick'}) {
 3885:       my @posters = &Apache::loncommon::get_env_multiple('form.stuinfo');
 3886:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.userpick'});
 3887:       my $numpicks = @posters;
 3888:       my %discinfo;
 3889:       $discinfo{$symb.'_userpick'} = join('&',@posters);
 3890:       &Apache::lonnet::put('nohist_'.$env{'request.course.id'}.'_discuss',
 3891: 			   \%discinfo,$env{'user.domain'},$env{'user.name'});
 3892:       &redirect_back($r,$feedurl,&mt('Changed sort/filter').'<br />','0','0','',
 3893: 		     '',$env{'form.previous'},$env{'form.sortposts'},'','','',
 3894: 		     '',$numpicks,$group);
 3895:       return OK;
 3896:   }
 3897:   if ($env{'form.applysort'}) {
 3898:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.applysort'});
 3899:       &redirect_back($r,$feedurl,&mt('Changed sort/filter').'<br />','0','0','',
 3900: 		     '',$env{'form.previous'},$env{'form.sortposts'},
 3901: 		     $env{'form.rolefilter'},$env{'form.statusfilter'},
 3902: 		     $env{'form.sectionpick'},$env{'form.grouppick'},
 3903:                      undef,$group);
 3904:       return OK;
 3905:   } elsif ($env{'form.cmd'} eq 'sortfilter') {
 3906:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.symb'});
 3907:       &print_sortfilter_options($r,$symb,$env{'form.previous'},$feedurl);
 3908:       return OK;
 3909:   } elsif ($env{'form.navtime'}) {
 3910:       my %discinfo = ();
 3911:       my @resources = ();
 3912:       if (defined($env{'form.navmaps'})) {
 3913:           if ($env{'form.navmaps'} =~ /:/) {
 3914:               @resources = split(/:/,$env{'form.navmaps'});
 3915:           } else {
 3916:               @resources = ("$env{'form.navmaps'}");
 3917:           }
 3918:       } else {
 3919:           &has_discussion(\@resources);
 3920:       }
 3921:       my $numitems = @resources;
 3922:       my $feedurl = '/adm/navmaps';
 3923:       if ($env{'form.navurl'}) { $feedurl .= '?'.$env{'form.navurl'}; }
 3924:       my %lt = &Apache::lonlocal::texthash(
 3925:           'mnpa' => 'Marked "New" posts as read in a total of',
 3926:           'robb' => 'resources/bulletin boards.',
 3927:           'twnp' => 'There are currently no resources or discussion boards with unread discussion postings.'
 3928:       );       
 3929:       foreach my $res (@resources) {
 3930:           my $ressymb=$res;
 3931: 	  &Apache::lonenc::check_decrypt(\$ressymb);
 3932:           my $lastkey = $ressymb.'_lastread';
 3933:           $discinfo{$lastkey} = $env{'form.navtime'};
 3934:       }
 3935:       my $textline = "<b>$lt{'mnpa'} $numitems $lt{'robb'}</b>";
 3936:       if ($numitems > 0) {
 3937:           &Apache::lonnet::put('nohist_'.$env{'request.course.id'}.'_discuss',
 3938: 			     \%discinfo,$env{'user.domain'},$env{'user.name'});
 3939:       } else {
 3940:           $textline = "<b>$lt{'twnp'}</b>";
 3941:       }
 3942:       &Apache::loncommon::content_type($r,'text/html');
 3943:       $r->send_http_header;
 3944:       my $logo=&Apache::loncommon::lonhttpdurl('/adm/lonIcons/lonlogos.gif');
 3945:       my %onload;
 3946: 
 3947:       my $start_page=
 3948: 	  &Apache::loncommon::start_page('New posts marked as read',undef,
 3949: 					 {'redirect'    => [2,$feedurl],
 3950: 					  'only_body'   => 1,
 3951: 					  'add_entries' => \%onload});
 3952:       my $end_page = &Apache::loncommon::end_page();
 3953:       $r->print (<<ENDREDIR);
 3954: $start_page
 3955: <img align="right" src="$logo" />
 3956: $textline
 3957: <form name="reldt" action="$feedurl" target="loncapaclient">
 3958: </form>
 3959: <br />
 3960: $end_page
 3961: ENDREDIR
 3962:       return OK;
 3963:   } elsif ($env{'form.modifydisp'}) {
 3964:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.modifydisp'});
 3965:       my ($dispchgA,$dispchgB,$markchg,$toggchg) = 
 3966: 	  split(/_/,$env{'form.changes'});
 3967:       &print_display_options($r,$symb,$env{'form.previous'},$dispchgA,
 3968: 			     $dispchgB,$markchg,$toggchg,$feedurl);
 3969:       return OK;
 3970:   } elsif ($env{'form.markondisp'} || $env{'form.markonread'} ||
 3971: 	   $env{'form.allposts'}   || $env{'form.onlyunread'} ||
 3972: 	   $env{'form.onlyunmark'} || $env{'form.toggoff'}    ||
 3973: 	   $env{'form.toggon'}     || $env{'form.markread'}) {
 3974:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.symb'});
 3975:       my %discinfo;
 3976: # ------------------------ Modify setting for read/unread toggle for each post 
 3977:       if ($env{'form.toggoff'}) { $discinfo{$symb.'_readtoggle'}=0; }
 3978:       if ($env{'form.toggon'})  { $discinfo{$symb.'_readtoggle'}=1; }
 3979: # --------- Modify setting for identification of 'NEW' posts in this discussion
 3980:       if ($env{'form.markondisp'}) {
 3981: 	  $discinfo{$symb.'_lastread'} = time;
 3982: 	  $discinfo{$symb.'_markondisp'} = 1;
 3983:       }
 3984:       if ($env{'form.markonread'}) {
 3985: 	  if ( $env{'form.previous'} > 0 ) {
 3986: 	      $discinfo{$symb.'_lastread'} = $env{'form.previous'};
 3987: 	  }
 3988: 	  $discinfo{$symb.'_markondisp'} = 0;
 3989:       }
 3990: # --------------------------------- Modify display setting for this discussion 
 3991:       if ($env{'form.allposts'}) {
 3992: 	  $discinfo{$symb.'_showonlyunread'} = 0;
 3993: 	  $discinfo{$symb.'_showonlyunmark'} = 0;
 3994:       }
 3995:       if ($env{'form.onlyunread'}) { $discinfo{$symb.'_showonlyunread'} = 1;  }
 3996:       if ($env{'form.onlyunmark'}) { $discinfo{$symb.'_showonlyunmark'} = 1;  }
 3997: # ----------------------------------------------------- Mark new posts not NEW 
 3998:       if ($env{'form.markread'})   { $discinfo{$symb.'_lastread'} = time; }
 3999:       &Apache::lonnet::put('nohist_'.$env{'request.course.id'}.'_discuss',
 4000: 			   \%discinfo,$env{'user.domain'},$env{'user.name'});
 4001:       my $previous=$env{'form.previous'};
 4002:       if ($env{'form.markondisp'}) { $previous=undef; }
 4003:       &redirect_back($r,$feedurl,&mt('Changed display status').'<br />',
 4004: 		     '0','0','','',$previous,'','','','','','',$group);
 4005:       return OK;
 4006:   } elsif (($env{'form.hide'}) || ($env{'form.unhide'})) {
 4007: # ----------------------------------------------------------------- Hide/unhide
 4008:       my $entry=$env{'form.hide'}?$env{'form.hide'}:$env{'form.unhide'};
 4009:       my ($symb,$idx)=split(/\:\:\:/,$entry);
 4010:       ($symb,my $feedurl)=&get_feedurl_and_clean_symb($symb);
 4011: 
 4012:       my $crs='/'.$env{'request.course.id'};
 4013:       if ($env{'request.course.sec'}) {
 4014:           $crs.='_'.$env{'request.course.sec'};
 4015:       }
 4016:       $crs=~s/\_/\//g;
 4017:       my $seeid=&Apache::lonnet::allowed('rin',$crs);
 4018: 
 4019:       if ($env{'form.hide'} && !$seeid && !(&editing_allowed($env{'form.hide'},$env{'form.group'}))) {
 4020:           &redirect_back($r,$feedurl,&mt('Deletion not permitted').'<br />',                 '0','0','','',$env{'form.previous'},'','','','',
 4021:                  undef,undef,$group,);
 4022:           return OK;
 4023:       }
 4024: 
 4025:       my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 4026:                           $env{'course.'.$env{'request.course.id'}.'.domain'},
 4027: 		          $env{'course.'.$env{'request.course.id'}.'.num'});
 4028: 
 4029:       my $currenthidden=$contrib{'hidden'};
 4030:       my $currentstudenthidden=$contrib{'studenthidden'};
 4031: 
 4032:       if ($env{'form.hide'}) {
 4033: 	  $currenthidden.='.'.$idx.'.';
 4034: 	  unless ($seeid) {
 4035: 	      $currentstudenthidden.='.'.$idx.'.';
 4036: 	  }
 4037:       } else {
 4038: 	  $currenthidden=~s/\.$idx\.//g;
 4039:       }
 4040:       my %newhash=('hidden' => $currenthidden);
 4041:       if ( ($env{'form.hide'}) && (!$seeid) ) {
 4042: 	  $newhash{'studenthidden'} = $currentstudenthidden;
 4043:       }
 4044:       if ($env{'form.hide'}) {
 4045:           my $changelast = 0;
 4046:           my $newlast;
 4047:           ($changelast,$newlast) = &get_discussion_info($idx,%contrib);
 4048:           if ($changelast) {
 4049:               &Apache::lonnet::put('discussiontimes',{$symb => $newlast},
 4050:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 4051:                      $env{'course.'.$env{'request.course.id'}.'.num'});
 4052:           }
 4053:       }
 4054:       &Apache::lonnet::store(\%newhash,$symb,$env{'request.course.id'},
 4055:                            $env{'course.'.$env{'request.course.id'}.'.domain'},
 4056: 			   $env{'course.'.$env{'request.course.id'}.'.num'});
 4057: 
 4058:       &redirect_back($r,$feedurl,&mt('Changed discussion status').'<br />',
 4059: 		     '0','0','','',$env{'form.previous'},undef,undef,undef,
 4060:                      undef,undef,undef,$group);
 4061:       return OK;
 4062:   } elsif (($env{'form.like'}) || ($env{'form.unlike'})) {
 4063: # ----------------------------------------------------------------- Like/unlike
 4064:       my $entry=$env{'form.like'}?$env{'form.like'}:$env{'form.unlike'};
 4065:       my ($symb,$idx)=split(/\:\:\:/,$entry);
 4066:       ($symb,my $feedurl)=&get_feedurl_and_clean_symb($symb);
 4067:       my $status='OPEN';
 4068:       if ($Apache::lonhomework::parsing_a_problem ||
 4069:           $Apache::lonhomework::parsing_a_task) {
 4070:           $status=$Apache::inputtags::status[-1];
 4071:       }
 4072:       my $result;
 4073:       my $realsymb = &get_realsymb($symb);
 4074:       if (&discussion_vote_available($status,$realsymb)) {
 4075: #
 4076: # Likes and unlikes are in db-file "disclikes" of the course
 4077: # The prefix is the $symb to identify the resource discussion,
 4078: # and the $idx to identify the entry
 4079: #
 4080:           my $prefix=$symb.':'.$idx.':';
 4081:           my %contrib=&Apache::lonnet::dump('disclikes',
 4082:                                         $env{'course.'.$env{'request.course.id'}.'.domain'},
 4083:                                         $env{'course.'.$env{'request.course.id'}.'.num'},
 4084:                                         '^'.$prefix);
 4085: 
 4086: # Get current like or unlike status for the $idx for this user.
 4087:           my $thisuser=$env{'user.name'}.':'.$env{'user.domain'};
 4088:           my ($userlikes,$userunlikes);
 4089:           if (ref($contrib{$prefix.'likers'}) eq 'HASH') {
 4090:               if (exists($contrib{$prefix.'likers'}{$thisuser})) {
 4091:                   $userlikes = 1;
 4092:               }
 4093:           }
 4094:           if (ref($contrib{$prefix.'unlikers'}) eq 'HASH') {
 4095:               if (exists($contrib{$prefix.'unlikers'}{$thisuser})) {
 4096:                   $userunlikes = 1;
 4097:               }
 4098:           }
 4099: # Get the current "likes" count
 4100:           my $likes=$contrib{$prefix.'likes'};
 4101: # Find out if they already voted
 4102: # Users cannot like a post twice, or unlike it twice.
 4103: # They can change their mind, though.
 4104:           my $alreadyflag=0;
 4105:           my $thisuser=$env{'user.name'}.':'.$env{'user.domain'};
 4106:           if ($env{'form.like'}) {
 4107:               if ($userlikes) {
 4108:                   $alreadyflag=1;
 4109:               } elsif ($userunlikes) {
 4110:                   delete($contrib{$prefix.'unlikers'}{$thisuser});
 4111:                   $likes++;
 4112:               } else {
 4113:                   if (ref($contrib{$prefix.'likers'}) eq 'HASH') {
 4114:                       $contrib{$prefix.'likers'}{$thisuser} = 1;
 4115:                   } else {
 4116:                       $contrib{$prefix.'likers'} = {$thisuser => 1};
 4117:                   }
 4118:                   $likes++;
 4119:               }
 4120:           } else {
 4121:               if ($userunlikes) {
 4122:                   $alreadyflag=1;
 4123:               } elsif ($userlikes) {
 4124:                   delete($contrib{$prefix.'likers'}{$thisuser});
 4125:                   $likes--;
 4126:               } else {
 4127:                   if (ref($contrib{$prefix.'unlikers'}) eq 'HASH') {
 4128:                       $contrib{$prefix.'unlikers'}{$thisuser} = 1;
 4129:                   } else {
 4130:                       $contrib{$prefix.'unlikers'} = {$thisuser => 1};
 4131:                   }
 4132:                   $likes--;
 4133:               }
 4134:           }
 4135: # $alreadyflag would be 1 if they tried to double-like or double-unlike
 4136:           unless ($alreadyflag) {
 4137:               my %newhash=($prefix.'likes'    => $likes,
 4138:                            $prefix.'likers'   => $contrib{$prefix.'likers'},
 4139:                            $prefix.'unlikers' => $contrib{$prefix.'unlikers'});
 4140: # Store data in db-file "disclikes"
 4141:               if (&Apache::lonnet::put('disclikes',
 4142:                                        \%newhash,
 4143:                                        $env{'course.'.$env{'request.course.id'}.'.domain'},
 4144:                                        $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
 4145: # Also store with the person who posted the liked/unliked entry
 4146:                   if ($env{'form.like'}) {
 4147:                       &storediscussionlikes(1,$contrib{$idx.':sendername'},$contrib{$idx.':senderdomain'});
 4148:                       $result=&mt("Registered 'Like'");
 4149:                   } else {
 4150:                       &storediscussionlikes(-1,$contrib{$idx.':sendername'},$contrib{$idx.':senderdomain'});
 4151:                       $result=&mt("Registered 'Unlike'");
 4152:                   }
 4153:               } else {
 4154: # Oops, something went wrong
 4155:                   $result=&mt("Failed to register vote");
 4156:               }
 4157:           }
 4158:       } else {
 4159:           $result=&mt('Voting unavailable for this discussion');
 4160:       }
 4161:       &redirect_back($r,$feedurl,$result.'<br />',
 4162:                      '0','0','','',$env{'form.previous'},undef,undef,undef,
 4163:                      undef,undef,undef,$group);
 4164:       return OK;
 4165:   } elsif ($env{'form.cmd'}=~/^(threadedoff|threadedon)$/) {
 4166:       my ($symb,$feedurl)=&get_feedurl_and_clean_symb($env{'form.symb'});
 4167:       if ($env{'form.cmd'} eq 'threadedon') {
 4168: 	  &Apache::lonnet::put('environment',{'threadeddiscussion' => 'on'});
 4169: 	  &Apache::lonnet::appenv({'environment.threadeddiscussion' => 'on'});
 4170:       } else {
 4171:  	  &Apache::lonnet::del('environment',['threadeddiscussion']);
 4172: 	  &Apache::lonnet::delenv('environment.threadeddiscussion');
 4173:       }
 4174:       &redirect_back($r,$feedurl,&mt('Changed discussion view mode').'<br />',
 4175: 		     '0','0','','',$env{'form.previous'},undef,undef,undef,
 4176:                      undef,undef,undef,$group);
 4177:       return OK;
 4178:   } elsif ($env{'form.deldisc'}) {
 4179: # --------------------------------------------------------------- Hide for good
 4180:       my ($symb,$idx)=split(/\:\:\:/,$env{'form.deldisc'});
 4181:       ($symb,my $feedurl)=&get_feedurl_and_clean_symb($symb);
 4182:       my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 4183:                           $env{'course.'.$env{'request.course.id'}.'.domain'},
 4184: 		          $env{'course.'.$env{'request.course.id'}.'.num'});
 4185:       my ($changelast,$newlast) = &get_discussion_info($idx,%contrib);
 4186:       if ($changelast) {
 4187:           &Apache::lonnet::put('discussiontimes',{$symb => $newlast},
 4188:                    $env{'course.'.$env{'request.course.id'}.'.domain'},                   $env{'course.'.$env{'request.course.id'}.'.num'});
 4189:       }
 4190:       my %newhash=('deleted' => $contrib{'deleted'}.".$idx.");
 4191:       &Apache::lonnet::store(\%newhash,$symb,$env{'request.course.id'},
 4192: 			   $env{'course.'.$env{'request.course.id'}.'.domain'},
 4193: 			   $env{'course.'.$env{'request.course.id'}.'.num'});
 4194:       &redirect_back($r,$feedurl,&mt('Changed discussion status').'<br />',
 4195: 		     '0','0','','',$env{'form.previous'},undef,undef,undef,
 4196:                      undef,undef,undef,$group);
 4197:       return OK;
 4198:   } elsif ($env{'form.preview'}) {
 4199: # -------------------------------------------------------- User wants a preview
 4200:       &show_preview($r);
 4201:       return OK;
 4202:   } elsif ($env{'form.attach'}) {
 4203: # -------------------------------------------------------- Work on attachments
 4204:       &Apache::loncommon::content_type($r,'text/html');
 4205:       $r->send_http_header;
 4206:       &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['subject','comment','addnewattach','delnewattach','timestamp','numoldver','idx','discuss','blog']);
 4207:       my (@currnewattach,@currdelold,@keepold,$toolarge);
 4208:       &process_attachments(\@currnewattach,\@currdelold,\@keepold);
 4209:       if (exists($env{'form.addnewattach.filename'})) {
 4210:           if (length($env{'form.addnewattach'})<=$attachmax{'num'}) {
 4211:               my $subdir = 'feedback/'.$env{'form.timestamp'};
 4212:               my $newattachment=&Apache::lonnet::userfileupload('addnewattach',undef,$subdir);
 4213: 	      push(@currnewattach, $newattachment);
 4214:           } else {
 4215:               $toolarge = '<p><span class="LC_warning">'.&mt('Attachment not included - exceeded permitted length').'</span><br /></p>';
 4216:           }
 4217:       }
 4218:       my $attachmenturls;
 4219:       my ($symb) = &get_feedurl_and_clean_symb($env{'form.attach'});
 4220:       my $idx = $env{'form.idx'};
 4221:       if ($idx) {
 4222:           my %contrib=&Apache::lonnet::restore($symb,$env{'request.course.id'},
 4223:                          $env{'course.'.$env{'request.course.id'}.'.domain'},
 4224:                          $env{'course.'.$env{'request.course.id'}.'.num'});
 4225:           $attachmenturls = $contrib{$idx.':attachmenturl'};
 4226:       }
 4227:       &modify_attachments($r,\@currnewattach,\@currdelold,$symb,$idx,
 4228: 			  $attachmenturls,$attachmax{'text'},$toolarge);
 4229:       return OK;
 4230:   } elsif ($env{'form.export'}) {
 4231:       &Apache::loncommon::content_type($r,'text/html');
 4232:       $r->send_http_header;
 4233:       my ($symb,$feedurl) = &get_feedurl_and_clean_symb($env{'form.export'});
 4234:       my $mode='board';
 4235:       my $status='OPEN';
 4236:       my $previous=$env{'form.previous'};
 4237:       if ($feedurl =~ /$LONCAPA::assess_re/) {
 4238:           $mode='problem';
 4239:           $status=$Apache::inputtags::status[-1];
 4240:       }
 4241:       my $discussion = &list_discussion($mode,$status,$symb); 
 4242:       my $start_page = 
 4243: 	  &Apache::loncommon::start_page('Resource Feedback and Discussion');
 4244:       my $end_page = 
 4245: 	  &Apache::loncommon::end_page();
 4246:       $r->print($start_page.$discussion.$end_page);
 4247:       return OK;
 4248: 
 4249:   } elsif ($env{'form.undeleteall'}) {
 4250:       &Apache::loncommon::content_type($r,'text/html');
 4251:       $r->send_http_header;
 4252:       my ($symb,$feedurl) = &get_feedurl_and_clean_symb($env{'form.undeleteall'});
 4253:       $r->print(&Apache::loncommon::start_page('Undelete all deleted discussion entries'));
 4254:       if (&Apache::lonnet::allowed('rin',$env{'request.course.id'})) {
 4255:            if (&Apache::lonnet::store({'deleted' => ''},$symb,$env{'request.course.id'},
 4256:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 4257:                      $env{'course.'.$env{'request.course.id'}.'.num'}) eq 'ok') {
 4258:                $r->print(&Apache::lonhtmlcommon::confirm_success(&mt("Undeleted all entries")));
 4259:            } else {
 4260:                $r->print(&Apache::lonhtmlcommon::confirm_success(&mt("Failed to undelete entries"),1));
 4261:            }
 4262:            $r->print("<br /><a href='$feedurl'>".&mt("Return and reload")."</a>");
 4263:       }
 4264:       $r->print(&Apache::loncommon::end_page());
 4265:       return OK;
 4266:   } else {
 4267: # ------------------------------------------------------------- Normal feedback
 4268:       my $feedurl=$env{'form.postdata'};
 4269:       $feedurl=~s/^https?\:\/\///;
 4270:       $feedurl=~s/^$ENV{'SERVER_NAME'}//;
 4271:       $feedurl=~s/^$ENV{'HTTP_HOST'}//;
 4272:       $feedurl=~s/\?.+$//;
 4273: 
 4274:       my $symb;
 4275:       if ($env{'form.replydisc'}) {
 4276: 	  $symb=(split(/\:\:\:/,$env{'form.replydisc'}))[0];
 4277:       } elsif ($env{'form.editdisc'}) {
 4278: 	  $symb=(split(/\:\:\:/,$env{'form.editdisc'}))[0];
 4279:       } elsif ($env{'form.origpage'}) {
 4280: 	  $symb=""; 
 4281:       } elsif ($env{'form.sendmessageonly'}) {
 4282:           $symb=(split(/\:\:\:/,$env{'form.sendmessageonly'}))[0];
 4283:       } else {
 4284: 	  $symb=&Apache::lonnet::symbread($feedurl);
 4285:       }
 4286:       unless ($symb) {
 4287: 	  $symb=$env{'form.symb'};
 4288:       }
 4289:       if (defined($symb)) {
 4290:           ($symb,$feedurl)=&get_feedurl_and_clean_symb($symb);
 4291:       } else {
 4292:           # backward compatibility (bulletin boards used to be 'wrapped')
 4293:           &Apache::lonenc::check_decrypt(\$feedurl);
 4294:           &dewrapper(\$feedurl);
 4295:       }
 4296:       my $goahead=1;
 4297:       if ($feedurl=~/$LONCAPA::assess_re/) {
 4298: 	  unless ($symb) { $goahead=0; }
 4299:       }
 4300:       if (!$goahead) {
 4301:           # Ambiguous Problem Resource
 4302: 	  $r->internal_redirect('/adm/ambiguous');
 4303: 	  return OK;
 4304:       }
 4305: # Go ahead with feedback, no ambiguous reference
 4306:       unless (
 4307: 	  (
 4308: 	   ($feedurl=~m:^/res:) && ($feedurl!~m:^/res/adm:)
 4309: 	   ) 
 4310: 	  || 
 4311: 	  ($env{'request.course.id'} && ($feedurl!~m:^/adm:))
 4312: 	  ||
 4313: 	  ($env{'request.course.id'} && ($symb=~/^bulletin\_\_\_/))
 4314: 	  ) {
 4315: 	  &Apache::loncommon::content_type($r,'text/html');
 4316: 	  $r->send_http_header;
 4317: # Unable to give feedback
 4318:           &Apache::lonenc::check_encrypt(\$feedurl);
 4319: 	  &no_redirect_back($r,$feedurl);
 4320: 	  return OK;
 4321:       }
 4322: # --------------------------------------------------- Print login screen header
 4323:       unless ($env{'form.sendit'}) {
 4324:           &Apache::lonenc::check_encrypt(\$feedurl);
 4325: 	  &Apache::loncommon::content_type($r,'text/html');
 4326: 	  $r->send_http_header;
 4327:           if (($env{'form.replydisc'}) || ($env{'form.editdisc'})) {
 4328:               my ($blocked,$blocktext) = 
 4329:                      &Apache::loncommon::blocking_status('boards');
 4330:               if ($blocked) {
 4331:                   $r->print(&blocked_reply_or_edit($blocktext));
 4332:                   return OK;
 4333:               }
 4334:           }
 4335: 	  my $options=&screen_header($feedurl,$symb,$group);
 4336: 	  if ($options) {
 4337: 	      &mail_screen($r,$feedurl,$options,$symb,$attachmax{'text'});
 4338: 	  } else {
 4339: 	      &fail_redirect($r,$feedurl);
 4340: 	  }
 4341: 	  return OK;
 4342:       }
 4343:       
 4344: # Get previous user input
 4345:       my $prevattempts=&Apache::loncommon::get_previous_attempt(
 4346:                                    $symb,$env{'user.name'},$env{'user.domain'},
 4347: 				   $env{'request.course.id'});
 4348: 
 4349: # Get output from resource
 4350:       &Apache::lonenc::check_encrypt(\$feedurl);
 4351:       my $usersaw=&resource_output($feedurl);
 4352: 
 4353: # Get resource answer (need to allow student to view grades for this to work)
 4354:       &Apache::lonnet::appenv({'allowed.vgr'=>'F'});
 4355:       my $usersymb = &Apache::lonenc::check_encrypt($symb);
 4356:       my $useranswer=
 4357:           &Apache::loncommon::get_student_answers(
 4358:               $usersymb,$env{'user.name'},$env{'user.domain'},
 4359:               $env{'request.course.id'});
 4360:       &Apache::lonnet::delenv('allowed.vgr');
 4361: # Get attachments, if any, and not too large
 4362:       my $attachmenturl='';
 4363:       my $toolarge='';
 4364:       if (($env{'form.origpage'}) || ($env{'form.editdisc'}) ||
 4365: 	  ($env{'form.replydisc'})) {
 4366: 	  my ($symb,$idx);
 4367: 	  if ($env{'form.replydisc'}) {
 4368: 	      ($symb,$idx)=split(/\:\:\:/,$env{'form.replydisc'});
 4369: 	  } elsif ($env{'form.editdisc'}) {
 4370: 	      ($symb,$idx)=split(/\:\:\:/,$env{'form.editdisc'});
 4371: 	  } elsif ($env{'form.origpage'}) {
 4372: 	      $symb = $env{'form.symb'};
 4373: 	  }
 4374: 	  &Apache::lonenc::check_decrypt(\$symb);
 4375: 	  my @currnewattach = ();
 4376: 	  my @deloldattach = ();
 4377: 	  my @keepold = ();
 4378: 	  &process_attachments(\@currnewattach,\@deloldattach,\@keepold);
 4379: 	  $symb=~s|(bulletin___\d+___)adm/wrapper/|$1|;
 4380: 	  $attachmenturl=&construct_attachmenturl(\@currnewattach,\@keepold,$symb,$idx);
 4381:       } elsif ($env{'form.attachment.filename'}) {
 4382: 	  if (length($env{'form.attachment'})<=$attachmax{'num'}) {
 4383:               my $now = time;
 4384:               my $subdir = 'feedback/'.$now;
 4385: 	      $attachmenturl=&Apache::lonnet::userfileupload('attachment',undef,$subdir);
 4386: 	  } else {
 4387:               $toolarge = '<p><span class="LC_warning">'.&mt('Attachment not included - exceeded permitted length').'</span><br /></p>';
 4388:           }
 4389:       }
 4390: # Filter HTML out of message (could be nasty)
 4391:       my $override;
 4392:       if ($env{'form.discuss'} =~ /^(?:author|question|course|policy)$/) {
 4393:           $override = 1;
 4394:       }
 4395:       my $message=&clear_out_html($env{'form.comment'},$override);
 4396: 
 4397: # Assemble email
 4398:       my ($email,$citations)=&assemble_email($message,$prevattempts,
 4399: 					     $usersaw,$useranswer);
 4400:  
 4401: # Who gets this?
 4402:       my ($typestyle,%to) = &Apache::lonmsg::decide_receiver($feedurl);
 4403: 
 4404: # Actually send mail
 4405:       my ($status,$numsent)=&send_msg(&clear_out_html($env{'form.subject'}),
 4406: 				      $feedurl,$email,$citations,
 4407: 				      $attachmenturl,$usersymb,%to);
 4408: 
 4409: # Discussion? Store that.
 4410:       my $numpost=0;
 4411:       if (  ($env{'form.discuss'} ne ''
 4412: 	     && $env{'form.discuss'} !~ /^(?:author|question|course|policy)/)
 4413: 	   || $env{'form.anondiscuss'} ne '') {
 4414: 	  my $subject = &clear_out_html($env{'form.subject'});
 4415: 	  my $anonmode=($env{'form.discuss'} eq 'anon' || $env{'form.anondiscuss'} );
 4416: 	  $typestyle.=&adddiscuss($symb,$message,$anonmode,$attachmenturl,
 4417: 				  $subject,$group);
 4418: 	  $numpost++;
 4419:       }
 4420: 
 4421: # Add to blog?
 4422: 
 4423:       my $blog='';
 4424:       if ($env{'form.blog'}) {
 4425: 	  my $subject = &clear_out_html($env{'form.subject'});
 4426: 	  $status.=&Apache::lonrss::addentry($env{'user.name'},
 4427: 				    $env{'user.domain'},
 4428: 				    'CourseBlog_'.$env{'request.course.id'},
 4429: 				    $subject,$message,$feedurl,'public');
 4430:           if (&Apache::loncommon::course_type() eq 'Community') {
 4431:               $blog='<br />'.&mt('Added to my community blog').'<br />';
 4432:           } else {
 4433: 	      $blog='<br />'.&mt('Added to my course blog').'<br />';
 4434:           }
 4435:       }
 4436: 	  
 4437: # Receipt screen and redirect back to where came from
 4438:       &redirect_back($r,$feedurl,$typestyle,$numsent,$numpost,$blog,$status,$env{'form.previous'},undef,undef,undef,undef,undef,undef,$group,$toolarge);
 4439:   }
 4440:   return OK;
 4441: }
 4442: 
 4443: sub blocked_reply_or_edit {
 4444:     my ($blocktext) = @_;
 4445:     return 
 4446:       &Apache::loncommon::start_page('Resource Feedback and Discussion').
 4447:       $blocktext.'<br /><br /><a href="javascript:history.go(-1)">'.
 4448:       &mt('Back to previous page').
 4449:       &Apache::loncommon::end_page();
 4450: } 
 4451: 
 4452: sub wrap_symb {
 4453:     my ($ressymb)=@_;
 4454:     if ($ressymb =~ /bulletin___\d+___/) {
 4455:         unless ($ressymb =~ m|bulletin___\d+___adm/wrapper|) {
 4456:             $ressymb=~s|(bulletin___\d+___)|$1adm/wrapper|;
 4457:         }
 4458:     }
 4459:     return $ressymb;
 4460: }
 4461: sub dewrapper {
 4462:     my ($feedurl)=@_;
 4463:     if ($$feedurl=~m|^/adm/wrapper/adm/.*/bulletinboard$|) {
 4464:         $$feedurl=~s|^/adm/wrapper||;
 4465:     }
 4466: }
 4467: 
 4468: sub get_feedurl {
 4469:     my ($symb)=@_;
 4470:     my ($map,$ind,$url)=&Apache::lonnet::decode_symb($symb);
 4471:     my $feedurl = &Apache::lonnet::clutter($url);
 4472:     &dewrapper(\$feedurl);
 4473:     return $feedurl;
 4474: }
 4475: 
 4476: sub get_feedurl_and_clean_symb {
 4477:     my ($symb)=@_;
 4478:     &Apache::lonenc::check_decrypt(\$symb);
 4479: # backward compatibility (bulletin boards used to be 'wrapped')
 4480:     unless ($symb =~ m|bulletin___\d+___adm/wrapper|) {
 4481: 	$symb=~s|(bulletin___\d+___)|$1adm/wrapper|;
 4482:     }
 4483:     my $feedurl = &get_feedurl($symb);
 4484:     return ($symb,$feedurl);
 4485: }
 4486: 
 4487: sub editing_allowed {
 4488:     my ($postid,$group) = @_;
 4489:     $postid = &unescape($postid);
 4490:     my $can_edit = 0;
 4491:     if ($group ne '') {
 4492:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4493:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4494:         if ($postid =~ m|^bulletin___\d+___adm/wrapper(/adm/\Q$cdom\E/\Q$cnum\E/\d+/bulletinboard)|) {
 4495:             if (&check_group_priv($group,'egp') eq 'ok') {
 4496:                 $can_edit = 1;
 4497:             }
 4498:             return $can_edit;
 4499:         }     
 4500:     } 
 4501:     my $cid = $env{'request.course.id'};
 4502:     my $role = (split(/\./,$env{'request.role'}))[0];
 4503:     my $section = $env{'request.course.sec'};
 4504:     my $allow_editing_config = 
 4505: 	$env{'course.'.$cid.'.allow_discussion_post_editing'};
 4506:     if ($allow_editing_config =~ m/^\s*yes\s*$/i) {
 4507:         $can_edit = 1;
 4508:     } else {
 4509: 	foreach my $editor (split(/,/,$allow_editing_config)) {
 4510: 	    my ($editor_role,$editor_sec) = split(/:/,$editor);
 4511: 	    if ($editor_role eq $role
 4512: 		&& defined($editor_sec)
 4513: 		&& defined($section)
 4514: 		&& $editor_sec eq $section) {
 4515: 		$can_edit = 1;
 4516: 		last;
 4517: 	    }
 4518: 	    if ($editor_role eq $role
 4519: 		&& !defined($editor_sec)) {
 4520: 		$can_edit = 1;
 4521: 	    }
 4522: 	}
 4523:     }
 4524:     return $can_edit;
 4525: }
 4526: 
 4527: sub check_group_priv {
 4528:     my ($group,$grp_priv) = @_;
 4529:     foreach my $priv ('mdg','vcg') {
 4530:         my $checkcourse = $env{'request.course.id'}.
 4531:             ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'');
 4532:         if (&Apache::lonnet::allowed($priv,$checkcourse)) {
 4533:             return 'ok';
 4534:         }
 4535:     }
 4536:     if ($grp_priv && $group ne '') {
 4537:         if (&Apache::lonnet::allowed($grp_priv,$env{'request.course.id'}.'/'.$group)) {
 4538:             return 'ok';
 4539:         }
 4540:     }
 4541:     return '';
 4542: }
 4543: 
 4544: sub group_args { 
 4545:     my ($group) = @_;
 4546:     if ($group eq '') { return ''; }
 4547:     my $extra_args = '&amp;group='.$group;
 4548:     if (exists($env{'form.ref'})) {
 4549:         $extra_args .= '&amp;ref='.$env{'form.ref'};
 4550:     }
 4551:     return $extra_args;
 4552: }
 4553: 
 4554: sub get_resource_title {
 4555:     my ($symb,$feedurl) = @_;
 4556:     my ($restitle,$plainurl);
 4557:     if (defined($symb)) {
 4558:         my $plain_symb = &Apache::lonenc::check_decrypt($symb);
 4559:         $restitle = &Apache::lonnet::gettitle($plain_symb);
 4560:     }
 4561:     if (defined($feedurl)) {
 4562:         $plainurl = &Apache::lonenc::check_decrypt($feedurl);
 4563:     }
 4564:     if (!defined($restitle)) {
 4565:         if (defined($feedurl)) {
 4566:             $restitle = &Apache::lonnet::gettitle($plainurl);
 4567:         }
 4568:     }
 4569:     if ($plainurl ne $feedurl) {
 4570:         my ($plain_filename) = ($plainurl =~ m-/([^/]+)$-);
 4571:         if ($plain_filename eq $restitle) {
 4572:             $restitle = &mt('Untitled resource');
 4573:         }
 4574:     }
 4575:     if ($restitle eq '') {
 4576:         $restitle = &mt('Untitled resource');
 4577:     }
 4578:     return $restitle;
 4579: }
 4580: 
 4581: 1;
 4582: __END__
 4583: 
 4584: 
 4585: =pod
 4586: 
 4587: =head1 NAME
 4588: 
 4589: Apache::lonfeedback.pm
 4590: 
 4591: =head1 SYNOPSIS
 4592: 
 4593: Handles feedback from students to instructors and system administrators.
 4594: 
 4595: Provides a screenshot of the current resource, as well as previous attempts if the resource was a homework.
 4596: 
 4597: Used by lonmsg.pm.
 4598: 
 4599: This is part of the LearningOnline Network with CAPA project
 4600: described at http://www.lon-capa.org.
 4601: 
 4602: =head1 OVERVIEW
 4603: 
 4604: None
 4605: 
 4606: =head1 SUBROUTINES
 4607: 
 4608: =over
 4609: 
 4610: =item discussion_open()
 4611: 
 4612: =item discussion_visible()
 4613: 
 4614: =item discussion_vote_available()
 4615: 
 4616: =item get_realsymb()
 4617: 
 4618: =item list_discussion()
 4619: 
 4620: =item send_feedback_link()
 4621: 
 4622: =item send_message_link()
 4623: 
 4624: =item action_links_bar()
 4625: 
 4626: =item postingform_display()
 4627: 
 4628: =item build_posting_display
 4629: 
 4630: =item filter_regexp()
 4631: 
 4632: =item get_post_contents()
 4633: 
 4634: =item replicate_attachments()
 4635: 
 4636: =item mail_screen()
 4637: 
 4638: =item print_display_options()
 4639: 
 4640: =item print_sortfilter_options()
 4641: 
 4642: =item print_showposters()
 4643: 
 4644: =item get_post_versions()
 4645: 
 4646: =item get_post_attachments()
 4647: 
 4648: =item fail_redirect()
 4649: 
 4650: =item redirect_back()
 4651: 
 4652: =item no_redirect_back()
 4653: 
 4654: =item screen_header()
 4655: 
 4656: =item resource_output()
 4657: 
 4658: =item clear_out_html()
 4659: 
 4660: =item assemble_email()
 4661: 
 4662: =item feedback_available()
 4663: 
 4664: =item send_msg()
 4665: 
 4666: =item adddiscuss()
 4667: 
 4668: =item get_discussion_info()
 4669: 
 4670: =item show_preview()
 4671: 
 4672: =item newline_to_br()
 4673: 
 4674: =item tidy_html()
 4675: 
 4676: =item generate_preview_button()
 4677: 
 4678: =item modify_attachments()
 4679: 
 4680: =item process_attachments()
 4681: 
 4682: =item generate_attachments_button()
 4683: 
 4684: =item extract_attachments()
 4685: 
 4686: =item construct_attachmenturl()
 4687: 
 4688: =item add_blog_checkbox()
 4689: 
 4690: =item has_discussion()
 4691: 
 4692: =item sort_filter_names()
 4693: 
 4694: =item handler()
 4695: 
 4696: =item blocked_reply_or_edit()
 4697: 
 4698: =item wrap_symb()
 4699: 
 4700: =item dewrapper()
 4701: 
 4702: =item get_feedurl()
 4703: 
 4704: =item get_feedurl_and_clean_symb()
 4705: 
 4706: =item editing_allowed()
 4707: 
 4708: =item check_group_priv()
 4709: 
 4710: =item group_args()
 4711: 
 4712: =item get_resource_title()
 4713: 
 4714: =back
 4715: 
 4716: =cut

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