File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.333: download - view: text, annotated - select for diffs
Tue Jan 10 14:52:57 2012 UTC (12 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #6545: discussion "karma"

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

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