File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.353: download - view: text, annotated - select for diffs
Sun Apr 29 22:55:20 2012 UTC (12 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Update names of routines in POD.

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

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