File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.290.2.7.2.3: download - view: text, annotated - select for diffs
Fri Mar 9 15:09:39 2012 UTC (12 years, 3 months ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.290.2.7: preferred, unified
- Customization for MITrelate
  - Backport 1.338.

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

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