File:  [LON-CAPA] / loncom / interface / lonfeedback.pm
Revision 1.336: download - view: text, annotated - select for diffs
Tue Mar 6 18:10:23 2012 UTC (12 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 5991
  - Only append username:domain to poster's nickname if viewer has priv to
    see identity behnid anonymous postings.
  - Only wrap poster's name with &aboutmewrapper() if aboutme page service
    is available for the poster.

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

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