File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.290.2.7.2.1: download - view: text, annotated - select for diffs
Tue Mar 6 21:24:01 2012 UTC (12 years, 4 months ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.290.2.7: preferred, unified
- Customization for MITrelate.
  - Backport 1.336.

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

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