File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.370.2.6: download - view: text, annotated - select for diffs
Wed Jan 19 01:35:58 2022 UTC (2 years, 3 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_4_uiuc, version_2_11_4
- For 2.11
  Backport 1.388, 1.389, 1.390

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

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