File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.340: download - view: text, annotated - select for diffs
Thu Mar 15 12:45:21 2012 UTC (12 years, 2 months ago) by goltermann
Branches: MAIN
CVS tags: HEAD
added pickboxes to unify the ui.
tidied up text and buttons to be more clear.
changed a headline to fit to context.

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

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