File:  [LON-CAPA] / loncom / interface / lonmsgdisplay.pm
Revision 1.157.4.1: download - view: text, annotated - select for diffs
Tue Feb 14 17:28:25 2012 UTC (12 years, 2 months ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.157: preferred, unified
- Customization for MITrelate.
  - Backport 1.158.
  - No domain selector for users from relate domain who do not have .adv priv.

    1: # The LearningOnline Network with CAPA
    2: # Routines for messaging display
    3: #
    4: # $Id: lonmsgdisplay.pm,v 1.157.4.1 2012/02/14 17:28:25 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::lonmsgdisplay;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::lonmsgdisplay: supports internal messaging
   37: 
   38: =head1 SYNOPSIS
   39: 
   40: lonmsgdisplay provides a handler to allow users to read, send, 
   41: and delete messages, and to create and delete message folders,
   42: and to move messages between folders.
   43: 
   44: =head1 OVERVIEW
   45: 
   46: =head2 Messaging Overview
   47: 
   48: X<messages>LON-CAPA provides an internal messaging system similar to
   49: email, but customized for LON-CAPA's usage. LON-CAPA implements its
   50: own messaging system, rather then building on top of email, because of
   51: the features LON-CAPA messages can offer that conventional e-mail can
   52: not:
   53: 
   54: =over 4
   55: 
   56: =item * B<Critical messages>: A message the recipient B<must>
   57: acknowlegde receipt of before they are allowed to continue using the
   58: system, preventing a user from claiming they never got a message
   59: 
   60: =item * B<Receipts>: LON-CAPA can reliably send reciepts informing the
   61: sender that it has been read; again, useful for preventing students
   62: from claiming they did not see a message. (While conventional e-mail
   63: has some reciept support, it's sporadic, e-mail client-specific, and
   64: generally the receiver can opt to not send one, making it useless in
   65: this case.)
   66: 
   67: =item * B<Context>: LON-CAPA knows about the sender, such as where
   68: they are in a course. When a student mails an instructor asking for
   69: help on the problem, the instructor receives not just the student's
   70: question, but all submissions the student has made up to that point,
   71: the user's rendering of the problem, and the complete view the student
   72: saw of the resource, including discussion up to that point. Finally,
   73: the instructor is reading all of this inside of LON-CAPA, not their
   74: email program, so they have full access to LON-CAPA's grading
   75: interface, or other features they may wish to use in response to the
   76: student's query.
   77: 
   78: =item * B<Blocking>: LON-CAPA can block selected communication 
   79: features for students during an online exam. A course coordinator or
   80: instructor can set an open and close date/time for scheduled online
   81: exams in a course. If a user uses the LON-CAPA internal messaging 
   82: system to display e-mails during the scheduled blocking event,  
   83: display of all e-mail sent during the blocking period will be 
   84: suppressed, and a message of explanation, including details of the 
   85: currently active blocking periods will be displayed instead. A user 
   86: who has a course coordinator or instructor role in a course will be
   87: unaffected by any blocking periods for the course, unless the user
   88: also has a student role in the course, AND has selected the student role.
   89: 
   90: =back
   91: 
   92: Users can ask LON-CAPA to forward messages to conventional e-mail
   93: addresses on their B<PREF> screen, but generally, LON-CAPA messages
   94: are much more useful than traditional email can be made to be, even
   95: with HTML support.
   96: 
   97: =cut
   98: 
   99: use strict;
  100: use Apache::lonnet;
  101: use HTML::TokeParser();
  102: use Apache::Constants qw(:common);
  103: use Apache::loncommon();
  104: use Apache::lonhtmlcommon();
  105: use Apache::lontexconvert();
  106: use HTML::Entities();
  107: use Apache::lonlocal;
  108: use Apache::loncommunicate;
  109: use Apache::lonfeedback;
  110: use Apache::lonrss();
  111: use Apache::lonselstudent();
  112: use lib '/home/httpd/lib/perl/';
  113: use LONCAPA qw(:DEFAULT :match);
  114: 
  115: # Querystring component with sorting type
  116: my $sqs='';
  117: my $startdis='';
  118: 
  119: # ============================================================ List all folders
  120: 
  121: sub folderlist {
  122:     my ($folder,$msgstatus) = @_;
  123:     my %lt = &Apache::lonlocal::texthash(
  124:                 actn => 'Action',
  125:                 fold => 'Folder',
  126:                 show => 'Show',
  127:                 status => 'Message Status',
  128:                 go   => 'Go',
  129:                 nnff => 'New Name for Folder',
  130:                 newn => 'New Name',
  131:                 thfm => 'The folder may not be renamed',
  132:                 fmnb => 'folder may not be renamed as it is a folder provided by the system.',
  133:                 asth => 'as this name is already in use for a system-provided or user-defined folder.',
  134:                 the => 'The',
  135:                 tnfm => 'The new folder may not be named',
  136: 
  137:     );
  138: 
  139: 	# set se lastvisit for the new mail check in the toplevel menu
  140: 	&Apache::lonnet::appenv({'user.mailcheck.lastvisit'=>time});
  141: 
  142:     my %actions = &Apache::lonlocal::texthash(
  143:                                 view => 'View Folder',
  144:                                 rename => 'Rename Folder',
  145:                                 delete => 'Delete Folder',
  146:     );
  147:     $actions{'select_form_order'} = ['view','rename','delete'];
  148: 
  149:     my %statushash = &Apache::lonlocal::texthash(&get_msgstatus_types());
  150: 
  151:     $statushash{'select_form_order'} = ['','new','read','replied','forwarded'];
  152: 
  153:     my %permfolders = &get_permanent_folders();
  154:     my $permlist = join("','",sort(keys(%permfolders)));
  155:     my ($permlistkeys,$permlistvals);
  156:     foreach my $key (sort(keys(%permfolders))) {
  157:         $permlistvals .= $permfolders{$key}."','";
  158:         $permlistkeys .= $key."','";
  159:     }
  160:     $permlistvals =~ s/','$//;
  161:     $permlistkeys =~ s/','$//;
  162:     my %gotfolders = &Apache::lonmsg::get_user_folders();
  163:     my %userfolders;
  164: 
  165:     foreach my $key (keys(%gotfolders)) {
  166:         $key =~ s/(['"])/\$1/g; #' stupid emacs
  167:         $userfolders{$key} = $key;
  168:     }
  169:     my @userorder = sort(keys(%userfolders));
  170:     my %formhash = (%permfolders,%userfolders);
  171:     my $folderlist = join("','",@userorder);
  172:     $folderlist .= "','".$permlistvals;
  173: 
  174:     $formhash{'select_form_order'} = ['','critical',@userorder,'sent','trash'];
  175:     my $output = qq|<script type="text/javascript">
  176: // <![CDATA[
  177: function folder_choice(targetform,caller) {
  178:     var permfolders_keys = new Array('$permlistkeys');
  179:     var permfolders_vals = new Array('$permlistvals');
  180:     var allfolders = new Array('$folderlist');
  181:     if (caller == 'change') {
  182:         if (targetform.folderaction.options[targetform.folderaction.selectedIndex].value == 'rename') {
  183:             for (var i=0; i<permfolders_keys.length; i++) {
  184:                 if (permfolders_keys[i] == targetform.folder.value) {
  185:                     alert("$lt{'the'} '"+permfolders_vals[i]+"' $lt{'fmnb'}");
  186:                     return;
  187:                 }
  188:             }
  189:             var foldername=prompt('$lt{'nnff'}','$lt{'newn'}');
  190:             if (foldername) {
  191:                 targetform.renamed.value=foldername;
  192:                 for (var i=0; i<allfolders.length; i++) {
  193:                     if (allfolders[i] == foldername) {
  194:                         alert("$lt{'thfm'} '"+foldername+"' $lt{'asth'}");
  195:                         return;
  196:                     }
  197:                 }
  198:                 targetform.submit();
  199:             }
  200:         }
  201:         else {
  202:             targetform.submit();
  203:         }
  204:     }
  205:     if (caller == 'new') {
  206:         var newname=targetform.newfolder.value;
  207:         if (newname) {
  208:             for (var i=0; i<allfolders.length; i++) {
  209:                 if (allfolders[i] == newname) {
  210:                     alert("$lt{'tnfm'} '"+newname+"' $lt{'asth'}");
  211:                     return;
  212:                 }
  213:             }
  214:             targetform.submit();
  215:         }
  216:     }
  217: }
  218: // ]]>
  219: </script>|;
  220:     my %show = ('select_form_order' => [10,20,50,100,200],
  221: 		map {$_=>$_} (10,20,50,100,200));
  222: 
  223:     $output .= '
  224: <form method="post" action="/adm/email" name="folderlist">
  225:    <table border="0" cellspacing="2" cellpadding="8">
  226:     <tr>
  227:      <td><b>'.$lt{'fold'}.'</b><br />'."\n".
  228:          &Apache::loncommon::select_form($folder,'folder',\%formhash).'
  229:      </td>
  230:      <td><b>'.$lt{'show'}.'</b><br />'."\n".
  231:          &Apache::loncommon::select_form($env{'form.interdis'},'interdis',
  232: 					 \%show).'
  233:      </td>
  234:      <td><b>'.$lt{'status'}.'</b><br />'."\n".
  235:        &Apache::loncommon::select_form($msgstatus,'msgstatus',\%statushash).'
  236:      </td>
  237:      <td><b>'.$lt{'actn'}.'</b><br />'."\n".'
  238:          <span class="LC_nobreak">'.
  239:          &Apache::loncommon::select_form('view','folderaction',\%actions).
  240:          ' <input type="button" value="'.$lt{'go'}.
  241:          '" onclick="javascript:folder_choice(this.form,'."'change'".');" />
  242:          </span>
  243:      </td>
  244:      <td><b>'.&mt('New Folder').'</b><br />'."\n".'
  245:          <span class="LC_nobreak">
  246:          <input type="text" size="15" name="newfolder" value="" />
  247:          <input type="button" value="'.$lt{'go'}.
  248:          '" onclick="javascript:folder_choice(this.form,'."'new'".');" />
  249:          </span>
  250:      </td>
  251:     </tr>
  252:    </table>
  253: '."\n".
  254:     '<input type="hidden" name="sortedby" value="'.$env{'form.sortedby'}.'" />'.
  255:     '<input type="hidden" name="renamed" value="" />'.
  256:         ($folder=~/^critical/?'</form>':'');
  257:     return $output;
  258: }
  259: 
  260: sub get_permanent_folders {
  261:     my %permfolders = 
  262: 	&Apache::lonlocal::texthash(''         => 'INBOX',
  263: 				    'trash'    => 'TRASH',
  264: 				    'critical' => 'Critical',
  265: 				    'sent'     => 'Sent Messages',
  266: 				    );
  267:     return %permfolders;
  268: }
  269: 
  270: sub get_msgstatus_types {
  271:     # Don't translate here!
  272:     my %statushash = (
  273:         ''          => 'Any',
  274:         'new'       => 'Unread',
  275:         'read'      => 'Read',
  276:         'replied'   => 'Replied to',
  277:         'forwarded' => 'Forwarded',
  278:     );
  279:     return %statushash;
  280: }
  281: 
  282: sub scrollbuttons {
  283:     my ($start,$maxdis,$first,$finish,$total,$msgstatus)=@_;
  284:     unless ($total>0) { return ''; }
  285:     $start++; $maxdis++;$first++;$finish++;
  286: 
  287:     my %statushash = &get_msgstatus_types();
  288:     my $status;
  289:     if ($msgstatus eq '') {
  290:         $status = 'All'; # Don't translate here!
  291:     } else {
  292:         $status = $statushash{$msgstatus};
  293:     }
  294:     my $output = '<b>'.&mt('Page:').'</b> ';
  295:     if ($maxdis == 1) {
  296:         # No buttons if only one page is displayed
  297:         $output .= '1/1';
  298:     } else {
  299:         $output .=
  300:            '<input type="submit" name="firstview" value="|&lt;" />'.
  301:            '<input type="submit" name="prevview" value="&lt;" />'.
  302:            ' <input type="text" size="5" name="startdis" value="'.$start.'" onchange="this.form.submit()" /> / '.$maxdis.' '.
  303:            '<input type="submit" name="nextview" value="&gt;" />'.
  304:            '<input type="submit" name="lastview" value="&gt;|" />';
  305:     }
  306:     $output .=
  307:         '<p>'
  308:        .'<b>'.&mt($status.' messages:').'</b> '
  309:        .&mt('showing messages [_1] through [_2] of [_3].',
  310:             $first,$finish,$total)
  311:        .'</p>'
  312:        .'</form>';
  313: 
  314:     return $output;
  315: }
  316: # =============================================================== Status Change
  317: 
  318: sub statuschange {
  319:     my ($msgid,$newstatus,$folder)=@_;
  320:     my $suffix=&Apache::lonmsg::foldersuffix($folder);
  321:     my %status=&Apache::lonnet::get('email_status'.$suffix,[$msgid]);
  322:     if ($status{$msgid}=~/^error\:/) { $status{$msgid}=''; }
  323:     unless ($status{$msgid}) { $status{$msgid}='new'; }
  324:     unless (($status{$msgid} eq 'replied') || 
  325:             ($status{$msgid} eq 'forwarded')) {
  326: 	&Apache::lonnet::put('email_status'.$suffix,{$msgid => $newstatus});
  327:     }
  328:     if (($newstatus eq 'deleted') || ($newstatus eq 'new')) {
  329: 	&Apache::lonnet::put('email_status'.$suffix,{$msgid => $newstatus});
  330:     }
  331:     if ($newstatus eq 'deleted') {
  332: 	return &movemsg($msgid,$folder,'trash');
  333:     }
  334:     return ;
  335: }
  336: 
  337: # ============================================================= Make new folder
  338: 
  339: sub makefolder {
  340:     my ($newfolder) = @_;
  341:     my %permfolders = &get_permanent_folders();
  342:     my %userfolders = &Apache::lonmsg::get_user_folders();
  343:     my ($outcome,$warning);
  344:     if (defined($userfolders{$newfolder})) {
  345:         return &mt('The folder name: "[_1]" is already in use for an existing folder.',$newfolder);
  346:     }
  347:     foreach my $perm (keys(%permfolders)) {
  348:         if ($permfolders{$perm} eq $newfolder) {
  349:             return &mt('The folder name: "[_1]" is already used for one of the folders automatically generated by the system.',$newfolder);
  350:         }
  351:     } 
  352:     if (&get_msgfolder_lock() eq 'ok') {
  353:         my %counter_hash = &Apache::lonnet::get('email_folders',["\0".'idcount']);
  354:         my $lastcount = $counter_hash{"\0".'idcount'};
  355:         my $folder_id = $lastcount + 1;
  356:         while (defined($userfolders{$folder_id})) {
  357:             $folder_id ++;
  358:         }
  359:         my %folderinfo = ( id      => $folder_id,
  360:                            created => time, );
  361:         $outcome =  
  362: 	    &Apache::lonnet::put('email_folders',{$newfolder => \%folderinfo,
  363: 						  "\0".'idcount' => $folder_id});
  364:         my $releaseresult = &release_msgfolder_lock();
  365:         if ($releaseresult ne 'ok') {
  366:             $warning = $releaseresult;
  367:         }
  368:     } else {
  369:         $outcome = 
  370: 	    &mt('Error - could not obtain lock on message folders record.');
  371:     }
  372:     return ($outcome,$warning);
  373: }
  374: 
  375: # ============================================================= Delete folder
  376: 
  377: sub deletefolder {
  378:     my ($folder)=@_;
  379:     my %permfolders = &get_permanent_folders();
  380:     if (defined($permfolders{$folder})) {
  381:         return &mt('The folder "[_1]" may not be deleted.',$folder); 
  382:     }
  383:     my %userfolders = &Apache::lonmsg::get_user_folders();
  384:     if (!defined($userfolders{$folder})) {
  385:         return &mt('The folder "[_1]" does not exist so deletion is not required.',
  386:                    $folder);
  387:     }
  388:     # check folder is empty;
  389:     my $suffix=&Apache::lonmsg::foldersuffix($folder);
  390:     my @messages = &Apache::lonnet::getkeys('nohist_email'.$suffix);
  391:     if (@messages > 0) {
  392:         return &mt('The folder "[_1]" contains messages so it may not be deleted.',$folder).
  393:                '<br />'.
  394:                &mt('Delete or move the messages to a different folder first.');
  395:     }
  396:     my $delresult = &Apache::lonnet::del('email_folders',[$folder]);
  397:     return $delresult;
  398: }
  399: 
  400: sub renamefolder {
  401:     my ($folder) = @_;
  402:     my $newname = $env{'form.renamed'};
  403:     my %permfolders = &get_permanent_folders();
  404:     if ($env{'form.renamed'} eq '') {
  405:         return &mt('The folder "[_1]" may not be renamed to "[_2]" as the new name you requested is an invalid name.',$folder,$newname);
  406:     }
  407:     if (defined($permfolders{$folder})) {
  408:         return &mt('The folder "[_1]" may not be renamed as it is a folder provided by the system.',$folder);
  409:     }
  410:     if (defined($permfolders{$newname})) {
  411:         return &mt('The folder "[_1]" may not be renamed to "[_2]" as the new name you requested is reserved for folders provided automatically by the system.',$folder,$newname);
  412:     }
  413:     my %userfolders = &Apache::lonmsg::get_user_folders();
  414:     if (defined($userfolders{$newname})) {
  415:         return &mt('The folder "[_1]" may not be renamed to "[_2]" because the new name you requested is already being used for an existing folder.',$folder,$newname);
  416:     }
  417:     if (!defined($userfolders{$folder})) {
  418:         return &mt('The folder "[_1]" could not be renamed to "[_2]" because the folder does not exist.',$folder,$newname);
  419:     }
  420:     my %folderinfo;
  421:     if (ref($userfolders{$folder}) eq 'HASH') {
  422:         %folderinfo = %{$userfolders{$folder}};
  423:     } else {
  424:         %folderinfo = ( id      => $folder,
  425:                         created => $userfolders{$folder},);
  426:     }
  427:     my $outcome =
  428:      &Apache::lonnet::put('email_folders',{$newname => \%folderinfo});
  429:     if ($outcome eq 'ok') {
  430:         $outcome = &Apache::lonnet::del('email_folders',[$folder]);
  431:     }
  432:     return $outcome;
  433: }
  434: 
  435: sub get_msgfolder_lock {
  436:     # get lock for mail folder counter.
  437:     my $lockhash = { "\0".'lock_counter' => time, };
  438:     my $tries = 0;
  439:     my $gotlock = &Apache::lonnet::newput('email_folders',$lockhash);
  440:     while (($gotlock ne 'ok') && $tries <3) {
  441:         $tries ++;
  442:         sleep(1);
  443:         $gotlock = &Apache::lonnet::newput('email_folders',$lockhash);
  444:     }
  445:     return $gotlock;
  446: }
  447: 
  448: sub release_msgfolder_lock {
  449:     #  remove lock
  450:     my @del_lock = ("\0".'lock_counter');
  451:     my $dellockoutcome=&Apache::lonnet::del('email_folders',\@del_lock);
  452:     if ($dellockoutcome ne 'ok') {
  453:         return ('<br />'.&mt('Warning: failed to release lock for counter').'<br />');
  454:     } else {
  455:         return 'ok';
  456:     }
  457: }
  458: 
  459: 
  460: # ======================================================== Move between folders
  461: 
  462: sub movemsg {
  463:     my ($msgid,$srcfolder,$trgfolder)=@_;
  464:     if ($srcfolder eq 'new') { $srcfolder=''; }
  465:     my $srcsuffix=&Apache::lonmsg::foldersuffix($srcfolder);
  466:     my $trgsuffix=&Apache::lonmsg::foldersuffix($trgfolder);
  467:     if ($srcsuffix eq $trgsuffix) {
  468: 	return (0,&mt('Message not moved, Attempted to move message to the same folder as it already is in.'));
  469:     }
  470: 
  471: # Copy message
  472:     my %message=&Apache::lonnet::get('nohist_email'.$srcsuffix,[$msgid]);
  473:     if (!exists($message{$msgid}) || $message{$msgid} eq '') {
  474: 	if (&Apache::lonnet::error(%message)) {
  475: 	    return (0,&mt('Message not moved, A network error occurred.'));
  476: 	} else {
  477: 	    return (0,&mt('Message not moved as the message is no longer in the source folder.'));
  478: 	}
  479:     }
  480: 
  481:     my $result =&Apache::lonnet::put('nohist_email'.$trgsuffix,
  482: 				     {$msgid => $message{$msgid}});
  483:     if (&Apache::lonnet::error($result)) {
  484: 	return (0,&mt('Message not moved, A network error occurred.'));
  485:     }
  486: 
  487: # Copy status
  488:     unless ($trgfolder eq 'trash') {
  489:        	my %status=&Apache::lonnet::get('email_status'.$srcsuffix,[$msgid]);
  490: 	# a non-existant status is the mark of an unread msg
  491: 	if (&Apache::lonnet::error(%status)) {
  492: 	    return (0,&mt('Message copied to new folder but status was not, A network error occurred.'));
  493: 	}
  494: 	my $result=&Apache::lonnet::put('email_status'.$trgsuffix,
  495: 					{$msgid => $status{$msgid}});
  496: 	if (&Apache::lonnet::error($result)) {
  497: 	    return (0,&mt('Message copied to new folder but status was not, A network error occurred.'));
  498: 	}
  499:     }
  500: 
  501: # Delete orginals
  502:     my $result_del_msg = 
  503: 	&Apache::lonnet::del('nohist_email'.$srcsuffix,[$msgid]);
  504:     my $result_del_stat =
  505: 	&Apache::lonnet::del('email_status'.$srcsuffix,[$msgid]);
  506:     if (&Apache::lonnet::error($result_del_msg)) {
  507: 	return (0,&mt('Message copied, but unable to delete the original from the source folder.'));
  508:     }
  509:     if (&Apache::lonnet::error($result_del_stat)) {
  510: 	return (0,&mt('Message copied, but unable to delete the original status from the source folder.'));
  511:     }
  512: 
  513:     return (1);
  514: }
  515: 
  516: # ======================================================= Display a course list
  517: 
  518: sub discourse {
  519:     my ($statushash) = @_;
  520:     my ($result,$active,$previous,$future);
  521:     my $crstype = &Apache::loncommon::course_type();
  522:     my ($course_personnel,
  523: 	$current_members,
  524: 	$expired_members,
  525: 	$future_members) = 
  526: 	    &Apache::lonselstudent::get_people_in_class($env{'request.course.sec'});
  527:     unshift @$current_members, (@$course_personnel);
  528:     my %defaultUsers;
  529:     
  530:     my $tmptext;
  531:     if ($tmptext = &Apache::lonselstudent::render_student_list($current_members,
  532:                                                                "activeusers",
  533:                                                                "current",
  534:                                                                \%defaultUsers,
  535:                                                                1,"selectedusers",1,'email')
  536:        ) {
  537:        my $bcc_curr_hdr;
  538:        if ($crstype eq 'Community') {
  539:            $bcc_curr_hdr = &mt('Bcc: community participants with current access');
  540:        } else {
  541:            $bcc_curr_hdr = &mt('Bcc: course members with current access');
  542:        }
  543:        $result .= '<fieldset id="LC_activeusers"><legend>'
  544:                  .$bcc_curr_hdr
  545:                  .'</legend>'
  546:                  .'<form name="activeusers">';
  547:        $result .= $tmptext.'</form></fieldset><br />';
  548:        if (ref($statushash) eq 'HASH') {
  549:            $statushash->{'active'} = 1;
  550:        }
  551:     }
  552:     if ($tmptext = &Apache::lonselstudent::render_student_list($expired_members,
  553:                                                                "previoususers",
  554:                                                                "expired",
  555:                                                                \%defaultUsers,
  556:                                                                1, "selectedusers",0,'email')
  557:        ) {
  558:        my $bcc_prev_hdr;
  559:        if ($crstype eq 'Community') {
  560:            $bcc_prev_hdr = &mt('Bcc: community participants with expired access');
  561:        } else {
  562:            $bcc_prev_hdr = &mt('Bcc: course members with expired access');
  563:        }
  564:        $result .= '<fieldset id="LC_previoususers"><legend>'
  565:                  .$bcc_prev_hdr
  566:                  .'</legend>'
  567:                  .'<form name="previoususers">';
  568:        $result .= $tmptext.'</form></fieldset><br />';
  569:        if (ref($statushash) eq 'HASH') {
  570:            $statushash->{'previous'} = 1;
  571:        }
  572: 
  573:     }
  574:     if ($tmptext = &Apache::lonselstudent::render_student_list($future_members,
  575:                                                                "futureusers",
  576:                                                                "future",
  577:                                                                \%defaultUsers,
  578:                                                                1, "selectedusers",0,'email')
  579:        ) {
  580:        my $bcc_future_hdr;
  581:        if ($crstype eq 'Community') {
  582:            $bcc_future_hdr = &mt('Bcc: community participants with future access');
  583:        } else {
  584:            $bcc_future_hdr = &mt('Bcc: course members with future access');
  585:        }
  586: 
  587:        $result .= '<fieldset id="LC_futureusers"><legend>'
  588:                  .$bcc_future_hdr
  589:                  .'</legend>'
  590:                  .'<form name="futureusers">';
  591:        $result .= $tmptext.'</form></fieldset>';
  592:        if (ref($statushash) eq 'HASH') {
  593:            $statushash->{'future'} = 1;
  594:        }
  595: 
  596:     }
  597:     return $result;
  598: }
  599: 
  600: sub disgroup {
  601:     my ($r,$cdom,$cnum,$group,$access_status) = @_;
  602:     my $hasfloat;
  603:     #  Needs to be in a course
  604:     if (!($env{'request.course.fn'})) {
  605:         $r->print('<span class="LC_error">'.&mt('Error: you must have a course role selected to be able to send a broadcast message to a group in the course.').'</span>');
  606:         return;
  607:     }
  608:     if ($cdom eq '' || $cnum eq '') {
  609:         $r->print('<span class="LC_error">'.&mt('Error: could not determine domain or number of course').'</span>');
  610:         return;
  611:     }
  612:     my ($memberinfo,$numitems) =
  613:                  &Apache::longroup::group_memberlist($cdom,$cnum,$group,{},[]);
  614:     my @statustypes = ('active');
  615:     my $viewgrps = &Apache::lonnet::allowed('vcg',$env{'request.course.id'}.
  616:                    ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''));
  617:     my $editgrps = &Apache::lonnet::allowed('mdg',$env{'request.course.id'}.
  618:                    ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''));
  619:     if ($viewgrps || $editgrps) {
  620:         push(@statustypes,('future','previous'));
  621:     }
  622:     if (keys(%{$memberinfo}) == 0) {
  623:         $r->print('<span class="LC_warning">'.
  624:                   &mt('As this group has no members, there are no recipients to select').
  625:                   '</span>');
  626:         return;
  627:     } else {
  628:         $hasfloat = 1;
  629:         $r->print('<div class="LC_left_float">');
  630:         my %Sortby = (
  631:                          active   => {},
  632:                          previous => {},
  633:                          future   => {},
  634:                      );
  635:         my %lt = &Apache::lonlocal::texthash(
  636:                                      'name'     => 'Name',
  637:                                      'usnm'     => 'Username',
  638:                                      'doma'     => 'Domain',
  639:                                      'active'   => 'Broadcast to Active Members',
  640:                                      'previous' => 'Broadcast (Bcc) to Former Members',
  641:                                      'future'   => 'Broadcast (Bcc) to Future Members',
  642:                                     );
  643:         foreach my $user (sort(keys(%{$memberinfo}))) {
  644:             my $status = $$memberinfo{$user}{status};
  645:             if ($env{'form.'.$status.'.sortby'} eq 'fullname') {
  646:                 push(@{$Sortby{$status}{$$memberinfo{$user}{fullname}}},$user);
  647:             } elsif ($env{'form.'.$status.'.sortby'} eq 'username') {
  648:                 push(@{$Sortby{$status}{$$memberinfo{$user}{uname}}},$user);
  649:             } elsif ($env{'form.'.$status.'.sortby'} eq 'domain') {
  650:                 push(@{$Sortby{$status}{$$memberinfo{$user}{udom}}},$user);
  651:             } else {
  652:                 push(@{$Sortby{$status}{$$memberinfo{$user}{fullname}}},$user);
  653:             }
  654:         }
  655:         $r->print(&group_check_uncheck());
  656:         foreach my $status (@statustypes)  {
  657:             if (ref($numitems) eq 'HASH') {
  658:                 if ((defined($$numitems{$status})) && ($$numitems{$status})) {
  659:                     my $formname = $status.'users';
  660:                     if (ref($access_status) eq 'HASH') {
  661:                         $access_status->{$status} = $$numitems{$status};
  662:                     }
  663:                     $r->print('<fieldset>'.
  664:                               '<legend>'.$lt{$status}.'</legend>'.
  665:                               '<form name="'.$formname.'">'.
  666:                               '<span class="LC_nobreak">'.
  667:                               '<input type="button" value="'.&mt('Check All').'" '.
  668:                               'onclick="javascript:toggleAll('."this.form,'check'".')" />'.
  669:                               '&nbsp;&nbsp;'.
  670:                               '<input type="button" value="'.&mt('Uncheck All').'" '.
  671:                               'onclick="javascript:toggleAll('."this.form,'uncheck'".')" />'.
  672:                               '</span>');
  673:                     if ($status eq 'active') {
  674:                         $r->print(('&nbsp;'x3).'<select name="groupmail">'.
  675:                                  '<option value="bcc" selected="selected">'.&mt('Bcc').'</option>'.
  676:                                  '<option value="cc">'.&mt('Cc').'</option>'.
  677:                                '</select>');
  678:                     }
  679:                     $r->print('<br />'.&Apache::loncommon::start_data_table().
  680:                                &Apache::loncommon::start_data_table_header_row().
  681:                                "<th>$lt{'name'}</th>".
  682:                                "<th>$lt{'usnm'}</th>".
  683:                                "<th>$lt{'doma'}</th>".
  684:                                &Apache::loncommon::end_data_table_header_row());
  685:                     foreach my $key (sort(keys(%{$Sortby{$status}}))) {
  686:                         foreach my $user (@{$Sortby{$status}{$key}}) {
  687:                             $r->print(&Apache::loncommon::start_data_table_row().
  688:                                 '<td><span class="LC_nobreak"><input type="checkbox" '.
  689:                                 'name="selectedusers_forminput" value="'.
  690:                                 $user.':'.$status.'" />'.
  691:                                 $$memberinfo{$user}{'fullname'}.'</span></td>'.
  692:                                 '<td>'.$$memberinfo{$user}{'uname'}.'</td>'.
  693:                                 '<td>'.$$memberinfo{$user}{'udom'}.'</td>'.
  694:                                 &Apache::loncommon::end_data_table_row());
  695:                         }
  696:                     }
  697:                     $r->print(&Apache::loncommon::end_data_table().'</form>'.
  698:                               '</fieldset><br />');
  699:                 }
  700:             }
  701:         }
  702:         $r->print('</div>');
  703:     }
  704:     return $hasfloat;
  705: }
  706: 
  707: sub group_check_uncheck {
  708:     my $output = qq|
  709: <script type="text/javascript">
  710: // <![CDATA[
  711: function toggleAll(form,action) {
  712:     if (typeof(form.selectedusers_forminput.length)=="undefined") {
  713:          if (action == 'check') {
  714:             form.selectedusers_forminput.checked = true;
  715:          } else {
  716:             form.selectedusers_forminput.checked = false;
  717:         }
  718:     } else {
  719:         for (var i=0; i<form.selectedusers_forminput.length; i++) {
  720:             if (action == 'check') {
  721:                 form.selectedusers_forminput[i].checked = true;
  722:             } else {
  723:                 form.selectedusers_forminput[i].checked = false;
  724:             }
  725:         }
  726:     }
  727: }
  728: // ]]>
  729: </script>
  730:     |;
  731: }
  732: 
  733: sub groupmail_header {
  734:     my ($action,$group,$cdom,$cnum) = @_;
  735:     my ($description,$refarg);
  736:     if (!$cdom || !$cnum) {
  737:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  738:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  739:     }
  740:     if (exists($env{'form.ref'})) {
  741:         $refarg = 'ref='.$env{'form.ref'};
  742:     }
  743:     if (!$group) {
  744:         $group = $env{'form.group'};
  745:     }
  746:     if ($group eq '') {
  747:         return  '';
  748:     } else {
  749:         my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum,$group);
  750:         if (defined($curr_groups{$group})) {
  751:             my %groupinfo =
  752:                     &Apache::longroup::get_group_settings($curr_groups{$group});
  753:             $description = &unescape($groupinfo{'description'});
  754:         }
  755:     }
  756:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  757:     if ($refarg) {
  758:         my $brtitle;
  759:         if (&Apache::loncommon::course_type() eq 'Community') {
  760:             $brtitle = 'View community groups';  
  761:         } else {
  762:             $brtitle = 'View course groups';
  763:         }  
  764:         &Apache::lonhtmlcommon::add_breadcrumb
  765:             ({href=>"/adm/coursegroups",
  766:               text=>"Groups",
  767:               title=>$brtitle});
  768:     }
  769:     &Apache::lonhtmlcommon::add_breadcrumb
  770:         ({href=>"/adm/$cdom/$cnum/$group/smppg?$refarg",
  771:           text=>"Group: $description",
  772:           title=>"Go to group's home page"},
  773:          {href=>"/adm/email?compose=group&amp;group=".
  774:                 "$env{'form.group'}&amp;$refarg",
  775:           text=>"Send a Message in a Group",
  776:           title=>"Compose Group Message"},);
  777:     if ($action eq 'sending') {
  778:             &Apache::lonhtmlcommon::add_breadcrumb
  779:                          ({text=>"Messages being sent.",
  780:                            title=>"E-mails sent"},);
  781:     }
  782:     my $groupheader = &Apache::loncommon::start_page('Group Message');
  783:     $groupheader .= &Apache::lonhtmlcommon::breadcrumbs
  784:                 ('Group - '.$env{'form.group'}.' Email');
  785:     return $groupheader;
  786: }
  787: 
  788: sub groupmail_sent {
  789:     my ($group,$cdom,$cnum) = @_;
  790:     my $refarg;
  791:     if (exists($env{'form.ref'})) {
  792:         $refarg = 'ref='.$env{'form.ref'};
  793:     }
  794:     my $output .= '<br /><br /><a href="/adm/email?compose=group&amp;group='.
  795:                   $group.'&amp;'.$refarg.'">'.
  796:                   &mt('Send another group message').'</a>'.'&nbsp;&nbsp;&nbsp;'.
  797:                   '<a href="/adm/'.$cdom.'/'.$cnum.'/'.$group.'/smppg?'.
  798:                   $refarg.'">'. &mt('Return to group page').'</a>';
  799:     return $output;
  800: }
  801: 
  802: # ==================================================== Display Critical Message
  803: 
  804: sub discrit {
  805:     my $r=shift;
  806:     my $header = '<h1>'.&mt('Critical Messages').'</h1>'
  807:                 .'<div class="LC_warning">'
  808:                 .&mt('Access to other pages will be prevented until you have moved all critical messages to your inbox.')
  809:                 .'</div><br />'
  810:                 .'<form action="/adm/email" method="post">'
  811:                 .'<input type="hidden" name="confirm" value="true" />';
  812:     my %what=&Apache::lonnet::dump('critical');
  813:     my $result = '';
  814:     foreach my $key (sort(keys(%what))) {
  815:         my %content=&Apache::lonmsg::unpackagemsg($what{$key});
  816:         next if ($content{'senderdomain'} eq '');
  817:         my $description;
  818:         if ($content{'courseid'} ne '') {
  819:             if ($content{'courseid'} =~ m{/^$match_domain\_$match_courseid$}) {
  820:                 my %courseinfo=&Apache::lonnet::coursedescription($content{'courseid'},{'one_time' => 1});
  821:                 if ($courseinfo{'description'} ne '') {
  822:                     $description = $courseinfo{'description'};
  823:                 }
  824:             }
  825:         }
  826:         $result .= &Apache::lonhtmlcommon::start_pick_box()
  827:                   .&Apache::lonhtmlcommon::row_title(&mt('From'),undef,'LC_oddrow_value')
  828:                   .'<b>'.&Apache::loncommon::aboutmewrapper(
  829:                    &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).'</b>'
  830:                   .' ('.$content{'sendername'}.':'.$content{'senderdomain'}.')'
  831:                   .&Apache::lonhtmlcommon::row_closure(1)
  832:                   .&Apache::lonhtmlcommon::row_title(&mt('Date'),undef,'LC_evenrow_value')
  833:                   .$content{'time'}
  834:                   .&Apache::lonhtmlcommon::row_closure(1)
  835:                   .&Apache::lonhtmlcommon::row_title(&mt('Subject'),undef,'LC_oddrow_value')
  836:                   .$content{'subject'}
  837:                   .&Apache::lonhtmlcommon::row_closure(1);
  838:         if ($description ne '') {
  839:             $result .= &Apache::lonhtmlcommon::row_title(&mt('Course'),undef,'LC_oddrow_value')
  840:                       .$description
  841:                       .&Apache::lonhtmlcommon::row_closure(1);
  842:         }
  843:         $result .= &Apache::lonhtmlcommon::row_title(&mt('Message'),undef,'LC_evenrow_value')
  844:                   .'<pre>'.&Apache::lontexconvert::msgtexconverted($content{'message'}).'</pre>'
  845:                   .&Apache::lonhtmlcommon::row_closure()
  846:                   .&Apache::lonhtmlcommon::row_title('',undef,'LC_oddrow_value')
  847:                   .'<div class="LC_warning">';
  848:         my ($rec_button,$reprec_button);
  849:         $rec_button = &mt('Move to Inbox');
  850:         if (!$content{'noreplies'}) {
  851:             $reprec_button = &mt('Move to Inbox/Compose reply');
  852:         }
  853:         if ($content{'sendback'}) {
  854:             $rec_button = &mt('Confirm Receipt');
  855:             if (!$content{'noreplies'}) {
  856:                 $reprec_button = &mt('Confirm Receipt and Reply');
  857:             }
  858:             $result .= &mt('You have to confirm that you have received this message before you can view other pages. After confirmation, this message will be moved to your regular inbox');
  859:         } else {
  860:             $result .= &mt('Access to other pages will be prevented until you have moved the message to your inbox.'); 
  861:         }
  862:         $result .= '</div>'
  863:                   .&Apache::lonhtmlcommon::row_closure(1)
  864:                   .&Apache::lonhtmlcommon::row_title('',undef,'LC_evenrow_value')
  865:                   .'<input type="submit" name="rec_'.$key.'" value="'.$rec_button.'" />';
  866:         if (!$content{'noreplies'}) {
  867:             $result .= '<input type="submit" name="reprec_'.$key.'" '
  868:                       .'value="'.$reprec_button.'" />'
  869:         }
  870:         $result .= &Apache::lonhtmlcommon::row_closure(1)
  871:                   .&Apache::lonhtmlcommon::end_pick_box()
  872:                   .'<br />';
  873:     }
  874:     # Check to see if there were any messages.
  875:     if ($result eq '') {
  876:         $result =
  877:             '<p class="LC_info">'.
  878:             &mt('You have no critical messages.').
  879:             '</p>'.
  880:             '<a href="/adm/roles">'.&mt('Select a course').'</a><br />'.
  881:             '<a href="/adm/email">'.&mt('Communicate').'</a>';
  882:     } else {
  883:         $r->print($header);
  884:     }
  885:     $r->print($result);
  886:     $r->print('<input type="hidden" name="displayedcrit" value="true" /></form>');
  887: }
  888: 
  889: sub sortedmessages {
  890:     my ($blocked,$startblock,$endblock,$numblocked,$folder,$msgstatus) = @_;
  891:     my $suffix=&Apache::lonmsg::foldersuffix($folder);
  892:     my @messages = &Apache::lonnet::getkeys('nohist_email'.$suffix);
  893:     #unpack the varibles and repack into temp for sorting
  894:     my @temp;
  895:     my %descriptions;
  896:     my %status_cache = 
  897: 	&Apache::lonnet::get('email_status'.&Apache::lonmsg::foldersuffix($folder),\@messages);
  898: 
  899:     my $get_received;
  900:     if ($folder eq 'sent' 
  901: 	&& ($env{'form.sortedby'} =~ m/^(rev)?(user|domain)$/)) {
  902: 	$get_received = 1;
  903:     }
  904: 
  905:     foreach my $msgid (@messages) {
  906:         next if ($msgid eq '');
  907: 	my $esc_msgid=&escape($msgid);
  908: 	my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$fromcid,$processid,$symb,$error) =
  909: 	    &Apache::lonmsg::unpackmsgid($esc_msgid,$folder,undef,
  910: 					 \%status_cache);
  911:         next if ($msgstatus ne '' && $msgstatus ne $status);
  912:         my $description = &get_course_desc($fromcid,\%descriptions);
  913: 	my @temp1 = ($sendtime,$shortsubj,$fromname,$fromdomain,$status,
  914: 		     $esc_msgid,$description);
  915: 	if ($get_received) {
  916: 	    my %message = &Apache::lonnet::get('nohist_email'.$suffix,
  917: 					       [$msgid]);
  918: 	    my %content = &Apache::lonmsg::unpackagemsg($message{$msgid});
  919: 	    push(@temp1,$content{'recuser'},$content{'recdomain'});
  920: 	}
  921:         # Check whether message was sent during blocking period.
  922:         if ($sendtime >= $startblock && ($sendtime <= $endblock && $endblock > 0) ) {
  923:             $$blocked{$msgid} = 'ON';
  924:             $$numblocked ++;
  925:         } else { 
  926:             push @temp ,\@temp1;
  927:         }
  928:     }
  929:     #default sort
  930:     @temp = sort  {$a->[0] <=> $b->[0]} @temp;    
  931:     if ($env{'form.sortedby'} eq "date"){
  932:         @temp = sort  {$a->[0] <=> $b->[0]} @temp;    
  933:     }
  934:     if ($env{'form.sortedby'} eq "revdate"){
  935:     	@temp = sort  {$b->[0] <=> $a->[0]} @temp; 
  936:     }
  937:     if ($env{'form.sortedby'} eq "user"){
  938: 	if ($get_received) {
  939: 	    @temp = sort  {lc($a->[7][0]) cmp lc($b->[7][0])} @temp;
  940: 	} else {
  941: 	    @temp = sort  {lc($a->[2])    cmp lc($b->[2])}    @temp;
  942: 	}
  943:     }
  944:     if ($env{'form.sortedby'} eq "revuser"){
  945: 	if ($get_received) {
  946: 	    @temp = sort  {lc($b->[7][0]) cmp lc($a->[7][0])} @temp;
  947: 	} else {
  948: 	    @temp = sort  {lc($b->[2])    cmp lc($a->[2])}    @temp;
  949: 	}
  950:     }
  951:     if ($env{'form.sortedby'} eq "domain"){
  952: 	if ($get_received) {
  953: 	    @temp = sort  {$a->[8][0] cmp $b->[8][0]} @temp;
  954: 	} else {
  955: 	    @temp = sort  {$a->[3]    cmp $b->[3]}    @temp;
  956: 	}
  957:     }
  958:     if ($env{'form.sortedby'} eq "revdomain"){
  959: 	if ($get_received) {
  960: 	    @temp = sort  {$b->[8][0] cmp $a->[8][0]} @temp;
  961: 	} else {
  962: 	    @temp = sort  {$b->[3]    cmp $a->[3]}    @temp;
  963: 	}
  964:     }
  965:     if ($env{'form.sortedby'} eq "subject"){
  966:         @temp = sort  {lc($a->[1]) cmp lc($b->[1])} @temp;
  967:     }
  968:     if ($env{'form.sortedby'} eq "revsubject"){
  969:         @temp = sort  {lc($b->[1]) cmp lc($a->[1])} @temp;
  970:     }
  971:     if ($env{'form.sortedby'} eq "course"){
  972:         @temp = sort  {lc($a->[6]) cmp lc($b->[6])} @temp;
  973:     }
  974:     if ($env{'form.sortedby'} eq "revcourse"){
  975:         @temp = sort  {lc($b->[6]) cmp lc($a->[6])} @temp;
  976:     }
  977:     if ($env{'form.sortedby'} eq "status"){
  978:         @temp = sort  {$a->[4] cmp $b->[4]} @temp;
  979:     }
  980:     if ($env{'form.sortedby'} eq "revstatus"){
  981:         @temp = sort  {$b->[4] cmp $a->[4]} @temp;
  982:     }
  983:     return @temp;
  984: }
  985: 
  986: sub get_course_desc {
  987:     my ($fromcid,$descriptions) = @_;
  988:     my $description;
  989:     if (!$fromcid) {
  990:         return $description;
  991:     } else {
  992:         if (defined($$descriptions{$fromcid})) {
  993:             $description = $$descriptions{$fromcid};
  994:         } else {
  995:             if (defined($env{'course.'.$fromcid.'.description'})) {
  996:                 $description = $env{'course.'.$fromcid.'.description'};
  997:             } else {
  998:                 if ($fromcid =~ m{/^$match_domain\_$match_courseid$}) {
  999:                     my %courseinfo=&Apache::lonnet::coursedescription($fromcid,
 1000:                                                                       {'one_time' => 1});
 1001:                     $description = $courseinfo{'description'};
 1002:                 }
 1003:             }
 1004:             if ($description ne '') {
 1005:                 $$descriptions{$fromcid} = $description;
 1006:             }
 1007:         }
 1008:         return $description;
 1009:     }
 1010: }
 1011: 
 1012: # ======================================================== Display all messages
 1013: 
 1014: sub disall {
 1015:     my ($r,$folder,$msgstatus)=@_;
 1016:     my %saveable = ('msgstatus' => 'scalar',
 1017: 		    'sortedby'  => 'scalar',
 1018: 		    'interdis'  => 'scalar',
 1019: 		    );
 1020:     &Apache::loncommon::store_settings('user','mail',\%saveable);
 1021:     &Apache::loncommon::restore_settings('user','mail',\%saveable);
 1022:     $folder    ||= $env{'form.folder'};
 1023:     $msgstatus ||= $env{'form.msgstatus'};
 1024:     $env{'form.interdis'} ||= 20;
 1025: 
 1026:     $r->print(&folderlist($folder,$msgstatus));
 1027:     if ($folder eq 'critical') {
 1028: 	&discrit($r);
 1029:     } else {
 1030: 	&disfolder($r,$folder,$msgstatus);
 1031:     }
 1032: }
 1033: 
 1034: # ============================================================ Display a folder
 1035: 
 1036: sub disfolder {
 1037:     my ($r,$folder,$msgstatus)=@_;
 1038:     my %statushash = &get_msgstatus_types();
 1039:     my %blocked = ();
 1040:     my %setters = ();
 1041:     my $numblocked = 0;
 1042:     my ($startblock,$endblock) = &Apache::loncommon::blockcheck(\%setters,'com');
 1043:     my %lt = &Apache::lonlocal::texthash(
 1044:                       sede => 'Select a destination folder to which the messages will be moved.',
 1045:                       nome => 'No messages have been selected to apply this action to.',
 1046:                       chec => 'Check the checkbox for at least one message.',  
 1047:     );
 1048:     my $jscript = &Apache::loncommon::check_uncheck_jscript();
 1049:     $r->print(<<ENDDISHEADER);
 1050: <script type="text/javascript">
 1051: // <![CDATA[
 1052:     $jscript
 1053: 
 1054:     function validate_checkedaction() {
 1055:         document.disall.markedaction.value = document.disall.checkedaction.options[document.disall.checkedaction.selectedIndex].value;
 1056:         if (document.disall.checkedaction.options[document.disall.checkedaction.selectedIndex].value == 'markedmove') {
 1057:             if (document.disall.movetofolder.options[document.disall.movetofolder.selectedIndex].value == "") {
 1058:                 alert("$lt{'sede'}");
 1059:                 return;
 1060:             } 
 1061:         }
 1062:         var checktotal = 0;
 1063:         if (document.forms.disall.delmark.length > 0) {
 1064:             for (var i=0; i<document.forms.disall.delmark.length; i++) {
 1065:                 if (document.forms.disall.delmark[i].checked) {
 1066:                     checktotal ++;
 1067:                 }
 1068:             }
 1069:         } else {
 1070:             if (document.forms.disall.delmark.checked) {
 1071:                 checktotal ++;
 1072:             }
 1073:         }   
 1074:         if (checktotal == 0) {
 1075:             alert("$lt{'nome'}\\n$lt{'chec'}");
 1076:             return;
 1077:         }
 1078:         document.disall.submit();
 1079:     }
 1080: // ]]>
 1081: </script>
 1082: ENDDISHEADER
 1083: 
 1084:     my $fsqs='&amp;folder='.$folder;
 1085:     my @temp=&sortedmessages(\%blocked,$startblock,$endblock,\$numblocked,$folder,$msgstatus);
 1086:     my $totalnumber=$#temp+1;
 1087:     if ($totalnumber < 1) {
 1088:         $r->print('<p class="LC_info">');
 1089:         if ($msgstatus eq '') {
 1090:             $r->print(&mt('There are no messages in this folder.'));
 1091:         } elsif ($msgstatus eq 'replied') {
 1092:             $r->print(&mt('You have not replied to any messages in this folder.'));
 1093:         } else {
 1094:             $r->print(&mt('There are no '.lc($statushash{$msgstatus}).' messages in this folder.'));
 1095:         }
 1096:         $r->print('</p>');
 1097:         if ($numblocked > 0) {
 1098:             $r->print(&blocked_in_folder($numblocked,$startblock,$endblock,
 1099:                                          \%setters));
 1100:         }
 1101:         return;
 1102:     }
 1103:     my $interdis = $env{'form.interdis'};
 1104:     my $number=int($totalnumber/$interdis);
 1105:     if ($totalnumber%$interdis == 0) {
 1106: 	$number--; 
 1107:     }
 1108: 
 1109:     if (($startdis<0) || ($startdis>$number)) { $startdis=$number; }
 1110:     my $firstdis=$interdis*$startdis;
 1111:     if ($firstdis>$#temp) { $firstdis=$#temp-$interdis+1; }
 1112:     my $lastdis=$firstdis+$interdis-1;
 1113:     if ($lastdis>$#temp) { $lastdis=$#temp; }
 1114:     $r->print(&scrollbuttons($startdis,$number,$firstdis,$lastdis,$totalnumber,$msgstatus));
 1115:     $r->print('<form method="post" name="disall" action="/adm/email">'.
 1116: 	      &Apache::loncommon::start_data_table().
 1117:           &Apache::loncommon::start_data_table_row().
 1118:           '<th colspan="1">&nbsp;</th><th>');
 1119:     if ($env{'form.sortedby'} eq "revdate") {
 1120: 	$r->print('<a href = "/adm/email?sortedby=date'.$fsqs.'">'.&mt('Date').'</a></th>');
 1121:     } else {
 1122: 	$r->print('<a href = "/adm/email?sortedby=revdate'.$fsqs.'">'.&mt('Date').'</a></th>');
 1123:     }
 1124:     $r->print('<th>');
 1125:     if ($env{'form.sortedby'} eq "revuser") {
 1126: 	$r->print('<a href = "/adm/email?sortedby=user'.$fsqs.'">'.&mt('Username').'</a>');
 1127:     } else {
 1128: 	$r->print('<a href = "/adm/email?sortedby=revuser'.$fsqs.'">'.&mt('Username').'</a>');
 1129:     }
 1130:     $r->print('</th><th>');
 1131:     if ($env{'form.sortedby'} eq "revdomain") {
 1132: 	$r->print('<a href = "/adm/email?sortedby=domain'.$fsqs.'">'.&mt('Domain').'</a>');
 1133:     } else {
 1134: 	$r->print('<a href = "/adm/email?sortedby=revdomain'.$fsqs.'">'.&mt('Domain').'</a>');
 1135:     }
 1136:     $r->print('</th><th>');
 1137:     if ($env{'form.sortedby'} eq "revsubject") {
 1138: 	$r->print('<a href = "/adm/email?sortedby=subject'.$fsqs.'">'.&mt('Subject').'</a>');
 1139:     } else {
 1140:     	$r->print('<a href = "/adm/email?sortedby=revsubject'.$fsqs.'">'.&mt('Subject').'</a>');
 1141:     }
 1142:     $r->print('</th><th>');
 1143:     if ($env{'form.sortedby'} eq "revcourse") {
 1144:         $r->print('<a href = "/adm/email?sortedby=course'.$fsqs.'">'.&mt('Course').'</a>');
 1145:     } else {
 1146:         $r->print('<a href = "/adm/email?sortedby=revcourse'.$fsqs.'">'.&mt('Course').'</a>');
 1147:     }
 1148:     $r->print('</th><th colspan="2">');
 1149:     if ($env{'form.sortedby'} eq "revstatus") {
 1150: 	$r->print('<a href = "/adm/email?sortedby=status'.$fsqs.'">'.&mt('Status').'</a></th>');
 1151:     } else {
 1152:      	$r->print('<a href = "/adm/email?sortedby=revstatus'.$fsqs.'">'.&mt('Status').'</a></th>');
 1153:     }
 1154:     $r->print("</tr>\n");
 1155: 
 1156:     my $suffix = &Apache::lonmsg::foldersuffix($folder);
 1157:     my $count = $firstdis;
 1158:     for (my $n=$firstdis;$n<=$lastdis;$n++) {
 1159: 	my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$origID,
 1160: 	    $description,$recv_name,$recv_domain)= 
 1161: 		@{$temp[$n]};
 1162:         if (($status ne 'deleted') && defined($sendtime) && $sendtime!~/error/) {
 1163:             my $class_msgstatus = '';
 1164:             $count ++;
 1165:             if ($status eq 'new') {
 1166:                 $class_msgstatus = 'LC_mail_new';
 1167:             } elsif ($status eq 'read') {
 1168:                 $class_msgstatus = 'LC_mail_read';
 1169:             } elsif ($status eq 'replied') {
 1170:                 $class_msgstatus = 'LC_mail_replied'; 
 1171:             } else {
 1172:                 $class_msgstatus = 'LC_mail_other';
 1173:             }
 1174:             $r->print(&Apache::loncommon::start_data_table_row($class_msgstatus));
 1175: 	    my ($dis_name,$dis_domain) = ($fromname,$fromdomain);
 1176: 	    if ($folder eq 'sent') {
 1177:                 if (defined($recv_name) && defined($recv_domain)) {
 1178: 		    if (ref($recv_name) eq 'ARRAY' && 
 1179:                         ref($recv_domain) eq 'ARRAY') {
 1180: 		        $dis_name   = join('<br />',@{$recv_name});
 1181: 		        $dis_domain = join('<br />',@{$recv_domain});
 1182:                     }
 1183: 		} else {
 1184: 		    my $msg_id  = &unescape($origID);
 1185: 		    my %message = &Apache::lonnet::get('nohist_email'.$suffix,
 1186: 						       [$msg_id]);
 1187: 		    my %content = &Apache::lonmsg::unpackagemsg($message{$msg_id});
 1188:                     if (ref($content{'recuser'}) eq 'ARRAY') {
 1189: 		        $dis_name   = join('<br />',@{$content{'recuser'}});
 1190:                     }
 1191:                     if (ref($content{'recdomain'}) eq 'ARRAY') {
 1192: 		        $dis_domain = join('<br />',@{$content{'recdomain'}});
 1193:                     }
 1194: 		}
 1195: 	    }
 1196:             my $localsenttime = &Apache::lonlocal::locallocaltime($sendtime);
 1197: 	    $r->print('<td align="right"><span class="LC_nobreak">'.(($status eq 'new')?'<b>':'').
 1198:                       $count.'.'.(($status eq 'new')?'</b>':'').'&nbsp;'.
 1199:                       '<input type="checkbox" name="delmark"'. 
 1200:                       ' value="'.$origID.'" /></span></td>');
 1201:             foreach my $item ($localsenttime,$dis_name,$dis_domain,$shortsubj) {
 1202:                 $r->print('<td>'.(($status eq 'new')?'<b>':'').
 1203:                           '<a href="/adm/email?display='.$origID.$sqs.'">'.
 1204:                           $item.(($status eq 'new')?'</b>':'').'</a></td>');
 1205:             }
 1206:             # Description and Status
 1207:             my $showstatus;
 1208:             my %statushash = &get_msgstatus_types();
 1209:             if ($status eq '') {
 1210:                 $showstatus = '';
 1211:             } else {
 1212:                 $showstatus = $statushash{$status};
 1213:             }
 1214:             $r->print('<td>'.(($status eq 'new')?'<b>':'').$description.
 1215:                       (($status eq 'new')?'</b>':'').
 1216:                       '</td>');
 1217:             $r->print('<td class="'.$class_msgstatus.'">&nbsp;&nbsp;</td>'.
 1218:                       '<td>'.
 1219:                       (($status eq 'new')?'<b>':'').&mt($showstatus).
 1220:                       (($status eq 'new')?'</b>':'').
 1221:                       '</td>');
 1222: 
 1223:             $r->print(&Apache::loncommon::end_data_table_row());
 1224: 
 1225:         } elsif ($status eq 'deleted') {
 1226: # purge
 1227:             my ($result,$msg) = 
 1228:         	&movemsg(&unescape($origID),$folder,'trash');
 1229:         }
 1230:     }   
 1231:     $r->print(&Apache::loncommon::end_data_table());
 1232: 
 1233: 
 1234:     # Bottom Functions
 1235:     $r->print('<table border="0" cellspacing="2" cellpadding="8">
 1236:  <tr>
 1237:   <td>
 1238:    <fieldset>
 1239:    <legend>'.&mt('Select').'</legend>
 1240:    <span class="LC_nobreak">
 1241:    <input type="button" onclick="javascript:checkAll(document.disall.delmark)" value="'.&mt('Check All').'" />'."\n".
 1242:   ' <input type="button" onclick="javascript:uncheckAll(document.disall.delmark)" value="'.&mt('Uncheck All').'" />'."\n".
 1243:   '<input type="hidden" name="sortedby" value="'.$env{'form.sortedby'}.'" />
 1244:   </span>
 1245:   </fieldset>
 1246:   </td>'."\n".
 1247:   '<td><b>'.&mt('Action').'</b><br />'."\n".
 1248:   '  <select name="checkedaction">'."\n");
 1249: 
 1250:     if ($folder ne 'trash') {
 1251:         $r->print('    <option value="markeddel">'.&mt('Delete').'</option>'."\n");
 1252:     }
 1253:     if ($msgstatus ne 'read') {
 1254:         $r->print('    <option value="markedread">'.&mt('Mark Read').'</option>."\n"');
 1255:     }
 1256:     if ($msgstatus ne 'unread') {
 1257:         $r->print('    <option value="markedunread">'.&mt('Mark Unread').'</option>'."\n");
 1258:     }
 1259:     $r->print('   <option value="markedforward">'.&mt('Forward').'</option>'."\n");
 1260: 
 1261:     my %gotfolders = &Apache::lonmsg::get_user_folders();
 1262:     if (keys(%gotfolders) > 0) {
 1263:         $r->print('   <option value="markedmove">'.&mt('Move to Folder ->').
 1264:                   '</option>');
 1265:     }
 1266:     $r->print("\n".'</select></td>'."\n");
 1267: 
 1268:     if (keys(%gotfolders) > 0) {
 1269:         $r->print('<td><b>'.&mt('Destination folder').'<b><br />');
 1270: 	my %userfolders;
 1271:         foreach my $key (keys(%gotfolders)) {
 1272:             $userfolders{$key} = $key;
 1273:         }
 1274:         $userfolders{''} = "";
 1275:         $r->print(&Apache::loncommon::select_form('','movetofolder',\%userfolders).
 1276:                   '</td>');
 1277:     }
 1278:     $r->print('<td>'.
 1279:               '<input type="button" name="go" value="'.&mt('Go').
 1280:               '" onclick="javascript:validate_checkedaction()"/></td>'."\n".
 1281:               '</tr></table>');
 1282:     my $postedstartdis=$startdis+1;
 1283:     $r->print('<input type="hidden" name="folder" value="'.$folder.'" /><input type="hidden" name="startdis" value="'.$postedstartdis.'" /><input type="hidden" name="interdis" value="'.$env{'form.interdis'}.'" /><input type="hidden" name="msgstatus" value="'.$msgstatus.'" /><input type="hidden" name="markedaction" value="" /></form>');
 1284:     if ($numblocked > 0) {
 1285:         $r->print(&blocked_in_folder($numblocked,$startblock,$endblock,
 1286:                                      \%setters));
 1287:     }
 1288: }
 1289: 
 1290: sub blocked_in_folder {
 1291:     my ($numblocked,$startblock,$endblock,$setters) = @_;
 1292:     my $beginblock = &Apache::lonlocal::locallocaltime($startblock);
 1293:     my $finishblock = &Apache::lonlocal::locallocaltime($endblock);
 1294:     my $output = '<br /><br />'.
 1295:                   &mt('[quant,_1,message is, messages are] not viewable because display of LON-CAPA messages sent to you by other students between [_2] and [_3] is currently being blocked because of online exams.',$numblocked,$beginblock,$finishblock);
 1296:     #$output .= &Apache::loncommon::build_block_table($startblock,$endblock,
 1297:     #                                                 $setters);
 1298:     
 1299:     my ($blocked, $blocktext) = &Apache::loncommon::blocking_status("com");
 1300:     $output .="<br /><br />".$blocktext;
 1301: 
 1302:     return $output;
 1303: }
 1304: 
 1305: # ============================================================== Compose output
 1306: 
 1307: sub compout {
 1308:     my ($r,$forwarding,$replying,$broadcast,$replycrit,$folder,$dismode,
 1309:         $multiforward)=@_;
 1310:     my $suffix=&Apache::lonmsg::foldersuffix($folder);
 1311:     my ($cdom,$cnum,$group,$refarg);
 1312:     if (exists($env{'form.group'})) {
 1313:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1314:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1315:         $group = $env{'form.group'};
 1316:         my $action = 'composing';
 1317:         $r->print(&groupmail_header($action,$group,$cdom,$cnum));
 1318:     } elsif ($broadcast eq 'individual') {
 1319: 	&printheader($r,'/adm/email?compose=individual',
 1320: 	     'Send a Message');
 1321:     } elsif ($broadcast) {
 1322: 	&printheader($r,'/adm/email?compose=group',
 1323: 	     'Broadcast Message');
 1324:     } elsif ($forwarding) {
 1325: 	&Apache::lonhtmlcommon::add_breadcrumb
 1326:         ({href=>"/adm/email?display=".&escape($forwarding),
 1327:           text=>"Display Message"});
 1328: 	&printheader($r,'/adm/email?forward='.&escape($forwarding),
 1329: 	     'Forwarding a Message');
 1330:     } elsif ($replying) {
 1331: 	&Apache::lonhtmlcommon::add_breadcrumb
 1332:         ({href=>"/adm/email?display=".&escape($replying),
 1333:           text=>"Display Message"});
 1334: 	&printheader($r,'/adm/email?replyto='.&escape($replying),
 1335: 	     'Replying to a Message');
 1336:     } elsif ($replycrit) {
 1337: 	$r->print('<h3>'.&mt('Replying to a Critical Message').'</h3>');
 1338: 	$replying=$replycrit;
 1339:     } elsif ($multiforward) {
 1340:         &Apache::lonhtmlcommon::add_breadcrumb
 1341:         ({href=>"/adm/email?folder=".&escape($folder),
 1342:           text=>"Display All Messages"});
 1343:         &printheader($r,'/adm/email?compose=multiforward',
 1344:              'Forwarding Multiple Messages');
 1345:         if ($multiforward > 1) {
 1346:             $r->print(&mt('Each of the[_1] [quant,_2,message] [_3]you checked'
 1347:                          .' will be forwarded to the recipient(s) you select below.'
 1348:                          ,'<b>',$multiforward,'</b>')
 1349:                     .'<br />');
 1350:         } else {
 1351:             $r->print(&mt('The message you checked will be forwarded to the recipient(s) you select below.').'<br />');
 1352:         }
 1353: 
 1354:     } else {
 1355: 	&printheader($r,'/adm/email?compose=upload',
 1356: 	     'Distribute from Uploaded File');
 1357:     }
 1358: 
 1359:     my $dispcrit='';
 1360:     my $dissub='';
 1361:     my $dismsg='';
 1362:     my $disbase='';
 1363:     my $attachrow;
 1364:     my $func1='Send'; # do not translate here!
 1365:     my %func2=( # do not translate here!
 1366:                'ma'  => 'Message',
 1367:                'msg' => 'Messages',
 1368:               );
 1369:     my %lt=&Apache::lonlocal::texthash('us'  => 'Username',
 1370: 				       'do'  => 'Domain',
 1371: 				       'ad'  => 'Additional Recipients',
 1372:                                        'rt'  => 'Reply to',
 1373:                                        'ar'  => 'Allow replies',
 1374: 				       'sb'  => 'Subject',
 1375: 				       'ca'  => 'Cancel',
 1376:                                        'gen' => 'Generate messages from a file',
 1377:                                        'gmt' => 'General message text',
 1378:                                        'tff' => 'The file format for the uploaded portion of the message is',
 1379:                                        'uas' => 'Upload and Send',
 1380:                                        'atta' => 'Attachment',
 1381:                                        'to'   => 'To:',
 1382:                                       );
 1383:     my %attachmax = (
 1384:                      text => &mt('(128 KB max size)'),
 1385:                      num  => 131072,
 1386:                     );
 1387:     if (!$forwarding && !$multiforward) {
 1388:         $attachrow = '<tr><td colspan="3"><b>'.$lt{'atta'}.'</b> '.$attachmax{'text'}.': <input type="file" name="attachment" /></td></tr>';
 1389:     }
 1390:     if (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
 1391: 	|| &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
 1392: 				    '/'.$env{'request.course.sec'})) {
 1393:          my $crstype = &Apache::loncommon::course_type();
 1394: 	 my $crithelp = Apache::loncommon::help_open_topic("Course_Critical_Message");
 1395:          my $rsstxt;
 1396:          if (&Apache::loncommon::course_type() eq 'Community') {
 1397:              $rsstxt = &mt('Include in community RSS newsfeed');
 1398:          } else {
 1399:              $rsstxt = &mt('Include in course RSS newsfeed');
 1400:          }
 1401:          $dispcrit=
 1402:  '<span class="LC_nobreak"><label><input type="checkbox" name="critmsg" /> '.&mt('Send as critical message').'.</label>'.$crithelp.'&nbsp;&nbsp;'.&mt('Require return receipt?').'<label><input type="radio" name="sendbck" value="1" />'.&mt('Yes').'</label>&nbsp;&nbsp;<label><input type="radio" name="sendbck" value="" checked="checked" />'.&mt('No').'</label></span><br />'.
 1403:  '<label><input type="checkbox" name="permanent" /> '.
 1404: &mt('Send copy to permanent e-mail address (if known)').'</label><br />'.
 1405: '<label><input type="checkbox" name="rsspost" /> '.
 1406: 		  $rsstxt.'</label><br />';
 1407:     }
 1408:     if ($broadcast ne 'group') {
 1409:         if (&Apache::lonnet::allowed('dff',$env{'request.course.id'}) ||
 1410:             &Apache::lonnet::allowed('dff',$env{'request.course.id'}.
 1411:                                      '/'.$env{'request.course.sec'})) {
 1412: 
 1413:             my $rectxt;
 1414:             if (&Apache::loncommon::course_type() eq 'Community') {
 1415:                 $rectxt = &mt("Include in community's 'User records' for recipient(s)");
 1416:             } else {
 1417:                 $rectxt = &mt("Include in course's 'User records' for recipient(s)");
 1418:             }
 1419: 
 1420:             $dispcrit.='<label>'.
 1421:                        '<input type="checkbox" name="courserecord" value="1" /> '.
 1422:                        $rectxt.
 1423:                        '</label><br />';
 1424:         }
 1425:     }
 1426: 
 1427:     my %message;
 1428:     my %content;
 1429:     my ($hasfloat,$broadcast_js,$sendmode,$can_grp_broadcast);
 1430:     my $defdom=$env{'user.domain'};
 1431:     if ($broadcast eq 'group') {
 1432:         my %access_status = (
 1433:                            active => 0,
 1434:                            previous => 0,
 1435:                            future => 0,
 1436:                       );
 1437:  
 1438:         if ($group eq '') {
 1439:             my $studentsel = &discourse(\%access_status);
 1440:             if ($studentsel) {
 1441:                 $r->print('<div class="LC_left_float">'.$studentsel.'</div>');
 1442:                 $hasfloat = 1;
 1443:             }
 1444:         } else {
 1445:             $can_grp_broadcast = &check_group_priv($group);
 1446:             if ($can_grp_broadcast) {
 1447:                 $hasfloat = &disgroup($r,$cdom,$cnum,$group,\%access_status);
 1448:             }
 1449:         }
 1450:         if ($hasfloat) {
 1451:             $sendmode = '<input type="hidden" name="sendmode" value="group" />'."\n";
 1452:             $broadcast_js = qq|
 1453: <script type="text/javascript">
 1454: // <![CDATA[
 1455: function courseRecipients() {
 1456: |;
 1457:         foreach my $type (keys(%access_status)) {
 1458:             if ($access_status{$type}) {
 1459:                 my $formname = $type.'users';
 1460:                 if ($type eq 'active' && $group ne '') {
 1461:                     $broadcast_js .= qq|
 1462:                     document.compemail.groupmail.value = document.$formname.groupmail[document.$formname.groupmail.selectedIndex].value;
 1463: |;
 1464:                 }
 1465:                 $broadcast_js .= qq|
 1466:     if (typeof(document.$formname.selectedusers_forminput.length)=="undefined") {
 1467:         document.compemail.courserecips.value += '_&&&_'+document.$formname.selectedusers_forminput.value;
 1468:     } else {
 1469:         for (var i=0; i<document.$formname.selectedusers_forminput.length; i++) {
 1470:             if (document.$formname.selectedusers_forminput[i].checked) {
 1471:                 document.compemail.courserecips.value += '_&&&_'+document.$formname.selectedusers_forminput[i].value;  
 1472:             }
 1473:         }
 1474:     }
 1475:                 |;
 1476:             }
 1477:         }
 1478:         $broadcast_js .= qq|
 1479:     return;
 1480: }
 1481: // ]]>
 1482: </script>
 1483: 
 1484: |;
 1485:         }
 1486:     }
 1487:     if ($forwarding) {
 1488: 	%message=&Apache::lonnet::get('nohist_email'.$suffix,[$forwarding]);
 1489: 	%content=&Apache::lonmsg::unpackagemsg($message{$forwarding},$folder);
 1490: 	$dispcrit.='<input type="hidden" name="forwid" value="'.
 1491: 	    $forwarding.'" />';
 1492: 	$func1='Forward'; # do not translate here!
 1493: 	
 1494: 	$dissub=&mt('Forwarding').': '.$content{'subject'};
 1495: 	$dismsg=&mt('Forwarded message from').' '.
 1496: 	    $content{'sendername'}.' '.&mt('at').' '.$content{'senderdomain'};
 1497: 	if ($content{'baseurl'}) {
 1498: 	    $disbase='<input type="hidden" name="baseurl" value="'.&escape($content{'baseurl'}).'" />';
 1499: 	}
 1500:     }
 1501:     if ($replying) {
 1502: 	%message=&Apache::lonnet::get('nohist_email'.$suffix,[$replying]);
 1503: 	%content=&Apache::lonmsg::unpackagemsg($message{$replying},$folder);
 1504: 	$dispcrit.='<input type="hidden" name="replyid" value="'.
 1505: 	    $replying.'" />';
 1506: 	$func1='Send Reply to'; # do not translate here!
 1507: 	
 1508: 	$dissub=&mt('Reply').': '.$content{'subject'};       
 1509: 	$dismsg='> '.$content{'message'};
 1510: 	$dismsg=~s/\r/\n/g;
 1511: 	$dismsg=~s/\f/\n/g;
 1512: 	$dismsg=~s/\n+/\n\> /g;
 1513: 	if ($content{'baseurl'}) {
 1514: 	    $disbase='<input type="hidden" name="baseurl" value="'.&escape($content{'baseurl'}).'" />';
 1515: 	    if ($env{'user.adv'}) {
 1516: 		$disbase.='<label><input type="checkbox" name="storebasecomment" />'.&mt('Save message for re-use').
 1517: 		    '</label> <a href="/adm/email?showcommentbaseurl='.
 1518: 		    &escape($content{'baseurl'}).'" target="comments">'.
 1519: 		    &mt('Show re-usable messages').'</a><br />';
 1520: 	    }
 1521: 	}
 1522:         my $jscript = &Apache::loncommon::check_uncheck_jscript();
 1523:         $r->print(<<"ENDREPSCRIPT");
 1524: <script type="text/javascript">
 1525: // <![CDATA[
 1526: $jscript
 1527: // ]]>
 1528: </script>
 1529: ENDREPSCRIPT
 1530:     }
 1531:     my $citation=&displayresource(%content);
 1532:     my $onsubmit;
 1533:     if ($env{'form.recdom'}) { $defdom=$env{'form.recdom'}; }
 1534:     if ($env{'form.text'}) { $dismsg=$env{'form.text'}; }
 1535:     if ($env{'form.subject'}) { $dissub=$env{'form.subject'}; }
 1536:     if ($hasfloat) {
 1537:         $r->print($broadcast_js.'<div class="LC_left_float">');
 1538:         $onsubmit = ' onsubmit="javascript:courseRecipients();" ';
 1539:     }
 1540:     $r->print(
 1541:                 '<form action="/adm/email"  name="compemail" method="post"'.
 1542:                 ' enctype="multipart/form-data"'.$onsubmit.'>'."\n".
 1543:                 '<input type="hidden" name="sendmail" value="on" />'."\n".
 1544:                 '<table>');
 1545:     if (($broadcast eq 'group') && ($group ne '') && (!$can_grp_broadcast)) {
 1546:         $r->print(&recipient_input_row($cdom,%lt));
 1547:     }
 1548:     if (($broadcast ne 'group') && ($broadcast ne 'upload')) {
 1549: 	if ($replying) {
 1550:             if ($content{'noreplies'}) {
 1551:                 $r->print('<tr><td>'.&mt('This message was designated by the sender not to allow replies.').'</td></tr></table></form>');
 1552:                 return;
 1553:             }
 1554:             $r->print('<tr><td colspan="3"><b>'.&mt('Replying to').'</b> ');
 1555:             if ($content{'replytoaddr'}) {
 1556:                 my ($replytoname,$replytodom) = split(/:/,$content{'replytoaddr'});
 1557:                 if ($replytoname ne '' && $replytodom ne '') {
 1558:                     $r->print(&Apache::loncommon::plainname($replytoname,
 1559:                                  $replytodom).' ('.$replytoname.':'.
 1560:                                  $replytodom.')');
 1561:                     $r->print('<input type="hidden" name="recuname" value="'.
 1562:                           $replytoname.'" />'.
 1563:                           '<input type="hidden" name="recdomain" value="'.
 1564:                           $replytodom.'" /></td></tr>');
 1565: 
 1566:                 } else {
 1567:                     $r->print(&mt('The sender did not designate a reply to address for this message.').'</td></tr></table>');
 1568:                     return;
 1569:                 }
 1570:             } else {
 1571: 	        $r->print(&Apache::loncommon::aboutmewrapper(
 1572: 							 &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).' ('.
 1573: 		      $content{'sendername'}.':'.
 1574: 		      $content{'senderdomain'}.')');
 1575:                 $r->print('<input type="hidden" name="recuname" value="'.
 1576: 		          $content{'sendername'}.'" />'.
 1577: 		          '<input type="hidden" name="recdomain" value="'.
 1578:                           $content{'senderdomain'}.'" /></td></tr>');
 1579:             }
 1580:             if ($content{'recipid'}) {
 1581:                 my %recips;
 1582:                 &retrieve_recips('replying',\%content,\%recips);
 1583:                 if (ref($recips{'to'}) eq 'ARRAY') {
 1584:                     if (@{$recips{'to'}} > 0) {
 1585:                         my $replyall;
 1586:                         if (@{$recips{'to'}} > 1) {
 1587:                             $replyall = qq|
 1588:  <span class="LC_nobreak">
 1589:       <input type="button" value="check all"
 1590:         onclick="javascript:checkAll(document.compemail.replying_to)" />
 1591:         &nbsp;&nbsp;
 1592:       <input type="button" value="uncheck all"
 1593:         onclick="javascript:uncheckAll(document.compemail.replying_to)" />
 1594:  </span>
 1595: |;
 1596:                         }
 1597:                         my $tolist = join(' ',@{$recips{'to'}});
 1598:                         $r->print('<tr><td colspan="3"><table><tr><td>'.&mt('[_1]Send reply[_2] to other recipients','<b>','</b>').':<br />'.$replyall.'</td><td>'.$tolist.'</td></tr></table></td></tr>');
 1599:                     }
 1600:                 }
 1601:                 if (ref($recips{'cc'}) eq 'ARRAY') {
 1602:                     if (@{$recips{'cc'}} > 0) {
 1603:                         my $replyall;
 1604:                         if (@{$recips{'cc'}} > 1) {
 1605:                             $replyall = qq|
 1606:  <span class="LC_nobreak">
 1607:       <input type="button" value="check all"
 1608:         onclick="javascript:checkAll(document.compemail.replying_cc)" />
 1609:         &nbsp;&nbsp;
 1610:       <input type="button" value="uncheck all"
 1611:         onclick="javascript:uncheckAll(document.compemail.replying_cc)" />
 1612:  </span>
 1613: |;
 1614:                         }
 1615:                         my $cclist = join(' ',@{$recips{'cc'}});
 1616:                         $r->print('<tr><td colspan="3"><table><tr><td>'.&mt('[_1]Cc[_2] to other copied recipients','<b>','</b>').':<br />'.$replyall.'</td><td>'.$cclist.'</td></tr></table></td></tr>');
 1617:                     }
 1618:                 }
 1619:                 if ($content{'group'} ne '') {
 1620:                     if (&check_group_priv($content{'group'})) {
 1621:                         if (ref($recips{'group_cc_broadcast'}) eq 'ARRAY') {
 1622:                             if (@{$recips{'group_cc_broadcast'}} > 0) {
 1623:                                 my $replyall;
 1624:                                 if (@{$recips{'group_cc_broadcast'}} > 1) {
 1625:                                     $replyall = qq|
 1626:  <span class="LC_nobreak">
 1627:       <input type="button" value="check all"
 1628:         onclick="javascript:checkAll(document.compemail.replying_groupcc)" />
 1629:         &nbsp;&nbsp;
 1630:       <input type="button" value="uncheck all"
 1631:         onclick="javascript:uncheckAll(document.compemail.replying_groupcc)" />
 1632:  </span>
 1633: |;
 1634:                                 }
 1635:                                 my $groupcclist = join(' ',@{$recips{'group_cc_broadcast'}});
 1636:                                 $r->print('<tr><td colspan="3"><table><tr><td>'.&mt('[_1]Cc[_2] to other copied group members','<b>','</b>').':<br />'.$replyall.'</td><td>'.$groupcclist.'<input type="hidden" name="group" value="'.$content{'group'}.'" /><input type="hidden" name="sendmode" value="group" /><input type="hidden" name="groupmail" value="cc" /></td></tr></table></td></tr>');
 1637:                             }
 1638:                         }
 1639:                     }
 1640:                 }
 1641:             }
 1642: 	} else {
 1643:             $r->print(&recipient_input_row($defdom,%lt));
 1644:         }
 1645:     }
 1646:     my $latexHelp = &Apache::loncommon::helpLatexCheatsheet(undef,undef,1);
 1647:     my $textareaclass;
 1648:     if (&Apache::lonhtmlcommon::htmlareabrowser()) {
 1649:         $r->print(&Apache::lonhtmlcommon::htmlareaselectactive());
 1650:         $textareaclass = 'class="LC_richDefaultOff"';
 1651:     }
 1652:     my $subj_size;
 1653:     if ($multiforward) {
 1654:         $r->print(&additional_rec_row(\%lt));
 1655:         $r->print('<tr><td colspan="2">'.
 1656:                   &mt('Unless you choose otherwise:').'<ul><li>'.
 1657:         &mt("The subject in each forwarded message will be <i>'Forwarding:'</i> followed by the original subject.").'</li><li>'.
 1658:         &mt("The message itself will begin with a first line: <i>'Forwarded message from'</i> followed by the original sender's name.").'</li></ul></td></tr>');
 1659:         $func1='Forward'; # do not translate here!
 1660:         $dissub = &mt('Forwarding').': ';
 1661:         $subj_size = '10';
 1662:         my $extra = '&lt;'.&mt('original subject').'&gt;&nbsp;&nbsp;&nbsp;'.
 1663:                     '<input type="radio" name="showorigsubj" value="1" checked="checked" />'.&mt('Yes').'&nbsp;<input type="radio" name="showorigsubj" value="0" />'.&mt('No');
 1664:         $dismsg = &mt('Forwarded message from ').' ';
 1665:         my $sender = &mt("sender's name");
 1666:         $r->print(&msg_subject_row($dissub,\%lt,$subj_size,$extra));
 1667:         $r->print('<tr><td>'.&mt('Message begins with:').'</td><td><input type="text" name="msgheader" value="'.$dismsg.'" />&nbsp;'.$sender.'&nbsp;&nbsp;&nbsp;<input type="radio" name="showorigsender" value="1" checked="checked" />'.&mt('Yes').'&nbsp;<input type="radio" name="showorigsender" value="0" />'.&mt('No').'<input type="hidden" name="multiforward" value="'.$multiforward.'" /></td></tr>
 1668: </table>
 1669: <br /><table>
 1670: <tr><td align="left">'."\n".
 1671: $latexHelp."<br />\n".
 1672: &mt("Any new text to display before the text of the original messages:").'<br />'."\n".
 1673: '<textarea name="message" id="message" cols="80" rows="5" wrap="hard" $textareaclass></textarea>');
 1674:         my @to_forward = &Apache::loncommon::get_env_multiple('form.delmark');
 1675:         foreach my $msg (@to_forward) {
 1676:             $r->print('<input type="hidden" name="delmark" value="'.$msg.'" />');
 1677:         }
 1678:         $r->print(&submit_button_row($folder,$dismode,&mt($func1.' '.$func2{'msg'}),
 1679:                                      \%lt));
 1680:     } elsif ($broadcast ne 'upload') {
 1681:         $subj_size = '50';
 1682:         $r->print(&additional_rec_row(\%lt));
 1683:         if (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
 1684:             || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
 1685:                                         '/'.$env{'request.course.sec'})) {
 1686:             $r->print(&reply_to_row(\%lt));
 1687:         }
 1688:         $r->print(&msg_subject_row($dissub,\%lt,$subj_size));
 1689:         $r->print(<<"ENDCOMP");
 1690: $attachrow
 1691: </table><br />
 1692: $latexHelp<br />
 1693: <textarea name="message" id="message" cols="80" rows="15" wrap="hard" $textareaclass>$dismsg
 1694: </textarea>
 1695: <br />
 1696: $sendmode
 1697: $dispcrit
 1698: $disbase
 1699: ENDCOMP
 1700:         $r->print(&submit_button_row($folder,$dismode,&mt($func1.' '.$func2{'ma'}),
 1701:                                      \%lt,$hasfloat,$group));
 1702:         $r->print($citation);
 1703:         if (exists($env{'form.ref'})) {
 1704:             $r->print('<input type="hidden" name="ref" value="'.
 1705:                       $env{'form.ref'}.'" />');
 1706:         }
 1707:         if (exists($env{'form.group'})) {
 1708:             $r->print('<input type="hidden" name="group" value="'.
 1709:                       $env{'form.group'}.'" />');
 1710:         }
 1711:     } else { # $broadcast is 'upload'
 1712: 	$r->print(<<ENDBLOCK);
 1713: <input type="hidden" name="sendmode" value="upload" />
 1714: <input type="hidden" name="send" value="on" />
 1715: <h3>$lt{'gen'}</h3>
 1716: <p>
 1717: Subject: <input type="text" size="50" name="subject" />
 1718: </p>
 1719: <p>$lt{'gmt'}:<br />
 1720: <textarea name="message" id="message" cols="60" rows="10" wrap="hard" $textareaclass>$dismsg
 1721: </textarea></p>
 1722: <p>
 1723: $lt{'tff'}:
 1724: ENDBLOCK
 1725:        $r->print('
 1726: <pre>'."\n".
 1727: &mt('username1:domain1: text')."\n".
 1728: &mt('username2:domain2: text')."\n".
 1729: &mt('username3:domain1: text')."\n".
 1730: '</pre>
 1731: </p>
 1732: <p>
 1733: '.&mt('The messages will be assembled from all lines with the respective'."\n".'<tt>username:domain</tt>, and appended to the general message text.'));
 1734:         $r->print(<<ENDUPLOAD);
 1735: </p>
 1736: <p>
 1737: <input type="file" name="upfile" size="40" /></p><p>
 1738: $dispcrit
 1739: <input type="submit" value="$lt{'uas'}" /></p>
 1740: ENDUPLOAD
 1741:     }
 1742:     if ($env{'form.displayedcrit'}) {
 1743: 	$r->print('<input type="hidden" name="displayedcrit" value="true" />');
 1744:     }
 1745:     $r->print('</form>');
 1746:     if ($hasfloat) {
 1747:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1748:     }
 1749:     $r->print(&generate_preview_form);
 1750: }
 1751: 
 1752: sub check_group_priv {
 1753:     my ($group) = @_;
 1754:     my $cid = $env{'request.course.id'};
 1755:     my $sec = $env{'request.course.sec'};
 1756:     return if !$cid;
 1757:     my $can_broadcast = &Apache::lonnet::allowed('sgb',$cid.'/'.$group);
 1758:     my $viewgrps = &Apache::lonnet::allowed('vcg',$cid.($sec?'/'.$sec:''));
 1759:     my $editgrps = &Apache::lonnet::allowed('mdg',$cid.($sec?'/'.$sec:''));
 1760:     if ($viewgrps || $editgrps || $can_broadcast) {
 1761:         return 1;
 1762:     }
 1763:     return;
 1764: }
 1765: 
 1766: sub recipient_input_row {
 1767:     my ($dom,%lt) = @_;
 1768:     my $domform;
 1769:     if (($dom eq 'relate') && (!$env{'user.adv'})) {
 1770:         $domform = '<span class="LC_cusr_emph">'.$dom.'</span>'.
 1771:                    '<input type="hidden" name="recdomain" value="'.$dom.'" />';  
 1772:     } else {
 1773:         $domform = &Apache::loncommon::select_dom_form($dom,'recdomain');
 1774:     }
 1775:     my $selectlink=
 1776:       &Apache::loncommon::selectstudent_link('compemail','recuname',
 1777:                                              'recdomain');
 1778:     my $output = <<"ENDREC";
 1779: <tr><td colspan="3"><span class="LC_nobreak"><b>$lt{'to'}</b> $lt{'us'}:&nbsp;<input type="text" size="15" name="recuname" value="$env{'form.recname'}" />&nbsp;$lt{'do'}:&nbsp;$domform&nbsp;&nbsp;$selectlink</span></td></tr>
 1780: ENDREC
 1781:     return $output;
 1782: }
 1783: 
 1784: sub reply_to_row {
 1785:     my ($lt) = @_;
 1786:     my $radioyes = &mt('Yes');
 1787:     my $radiono = &mt('No');
 1788:     my $output = <<"ENDREP";
 1789: <tr><td colspan="3"><span class="LC_nobreak"><b>$lt->{'ar'}</b>:<label><input type="radio" name="can_reply" value="Y" checked="checked" />$radioyes</label>&nbsp;&nbsp;<label><input type="radio" name="can_reply" value="N" />$radiono</label></span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="LC_nobreak">$lt->{'rt'}:&nbsp;<input type="text" size="25" name="reply_to_addr" value="$env{'user.name'}:$env{'user.domain'}" /></span></td></tr>
 1790: ENDREP
 1791:     return $output;
 1792: }
 1793: 
 1794: sub additional_rec_row {
 1795:     my ($lt) = @_;
 1796:     my $cc = &mt('Cc:');
 1797:     my $bcc = &mt('Bcc:');
 1798:     my $exmpl = &mt('username:domain,username:domain,...'); 
 1799:     my $output = <<"ENDADD";
 1800: <tr><td colspan="3"><fieldset id="LC_additionalrecips"><legend>$lt->{'ad'} <tt>($exmpl)</tt></legend><table>
 1801: <tr><td>&nbsp;</td><td>$lt->{'to'}</td><td><input type="text" size="50" name="additionalrec_to" /></td></tr>
 1802: <tr><td>&nbsp;</td><td>$cc</td><td><input type="text" size="50" name="additionalrec_cc" /></td></tr> 
 1803: <tr><td>&nbsp;</td><td>$bcc</td><td><input type="text" size="50" name="additionalrec_bcc" /></td></tr></table></fieldset></td></tr>
 1804: ENDADD
 1805:     return $output;
 1806: }
 1807: 
 1808: sub submit_button_row {
 1809:     my ($folder,$dismode,$sendtext,$lt,$is_crsform,$group) = @_;
 1810:     my $pre=&mt("Show Preview and Check Spelling");
 1811:     my $value=&mt('Send');
 1812:     my $prevbutton = '<input type="button" name="preview" value="'.$pre.'" onclick="if (typeof(document.compemail.onsubmit)=='."'function'".') {document.compemail.onsubmit();};document.preview.comment.value=document.compemail.message.value;document.preview.subject.value=document.compemail.subject.value;document.preview.submit();" />';
 1813:     my $output = qq|
 1814: <input type="hidden" name="folder" value="$folder" />
 1815: <input type="hidden" name="dismode" value="$dismode" />|;
 1816:     if ($is_crsform) {
 1817:         $output .= '<input type="hidden" name="courserecips" value="" />'."\n";
 1818:         if ($group ne '') {
 1819:             $output .= '<input type="hidden" name="groupmail" value="" />'."\n";
 1820:         }
 1821:     }
 1822:     $output .= qq|
 1823: <table><tr><td align="left">
 1824: <input type="submit" name="send" value="$value" title="$sendtext" />
 1825: <input type="submit" name="cancel" value="$lt->{'ca'}" />
 1826: </td><td width="60">&nbsp;</td><td align="right">$prevbutton</td></tr></table>
 1827: |;
 1828:     return $output;
 1829: }
 1830: 
 1831: sub msg_subject_row {
 1832:     my ($dissub,$lt,$subj_size,$extra) = @_;
 1833:     my $output = '<tr><td colspan="3"><b>'.$lt->{'sb'}.'</b>:&nbsp;<input type="text" size="'.
 1834:                  $subj_size.'" name="subject" value="'.$dissub.'" />'.$extra.
 1835:                  '</td></tr>';
 1836:     return $output;
 1837: }
 1838: 
 1839: sub generate_preview_form {
 1840:     my $prevbutton = (<<ENDPREVIEW);
 1841: <form name="preview" action="/adm/feedback?preview=1" method="post" target="preview">
 1842: <input type="hidden" name="subject" />
 1843: <input type="hidden" name="comment" />
 1844: </form>
 1845: ENDPREVIEW
 1846: }
 1847: 
 1848: # ---------------------------------------------------- Display all face to face
 1849: 
 1850: sub retrieve_instructor_comments {
 1851:     my ($user,$domain)=@_;
 1852:     my $target=$env{'form.grade_target'};
 1853:     if (! $env{'request.course.id'}) { return; }
 1854:     if (! &Apache::lonnet::allowed('dff',$env{'request.course.id'})
 1855: 	&& ! &Apache::lonnet::allowed('dff',$env{'request.course.id'}.
 1856: 				      '/'.$env{'request.course.sec'})) {
 1857: 	return;
 1858:     }
 1859:     my %records=&Apache::lonnet::dump('nohist_email',
 1860: 			 $env{'course.'.$env{'request.course.id'}.'.domain'},
 1861: 			 $env{'course.'.$env{'request.course.id'}.'.num'},
 1862:                          '%255b'.$user.'%253a'.$domain.'%255d');
 1863:     my $result='';
 1864:     foreach my $key (sort(keys(%records))) {
 1865:         my %content=&Apache::lonmsg::unpackagemsg($records{$key});
 1866:         next if ($content{'senderdomain'} eq '');
 1867:         next if ($content{'subject'} !~ /^Record/);
 1868: 	# &Apache::lonfeedback::newline_to_br(\$content{'message'});
 1869: 	$result.='Recorded by '.
 1870:             $content{'sendername'}.':'.$content{'senderdomain'}."\n";
 1871:         $result.=
 1872:             &Apache::lontexconvert::msgtexconverted($content{'message'})."\n";
 1873:      }
 1874:     return $result;
 1875: }
 1876: 
 1877: sub disfacetoface {
 1878:     my ($r,$user,$domain,$target)=@_;
 1879:     if ($target eq '') {
 1880:         $target=$env{'form.grade_target'};
 1881:     }
 1882:     unless ($env{'request.course.id'}) { return; }
 1883:     if  (!&Apache::lonnet::allowed('dff',$env{'request.course.id'})
 1884: 	 && ! &Apache::lonnet::allowed('dff',$env{'request.course.id'}.
 1885: 				       '/'.$env{'request.course.sec'})) {
 1886: 	$r->print(&mt('Not allowed'));
 1887: 	return;
 1888:     }
 1889:     my %records=&Apache::lonnet::dump('nohist_email',
 1890: 			 $env{'course.'.$env{'request.course.id'}.'.domain'},
 1891: 			 $env{'course.'.$env{'request.course.id'}.'.num'},
 1892:                          '%255b'.$user.'%253a'.$domain.'%255d');
 1893:     my $result='<div>';
 1894:     foreach my $key (sort(keys(%records))) {
 1895:         my %content=&Apache::lonmsg::unpackagemsg($records{$key});
 1896:         next if ($content{'senderdomain'} eq '');
 1897:     if (!&Apache::lonfeedback::contains_block_html($content{'message'})) {
 1898: 		&Apache::lonfeedback::newline_to_br(\$content{'message'});
 1899: 	}
 1900:         if ($content{'subject'}=~/^Record/) {
 1901: 	    $result.='<h3>'.&mt('Record').'</h3>';
 1902:         } elsif ($content{'subject'}=~/^Broadcast/) {
 1903:             $result .='<h3>'.&mt('Broadcast Message').'</h3>';
 1904:             if ($content{'subject'}=~/^Broadcast\./) {
 1905:                 if (defined($content{'coursemsgid'})) {
 1906:                     my $crsmsgid = &escape($content{'coursemsgid'});
 1907:                     my $broadcast_message = &general_message($crsmsgid);
 1908:                     $content{'message'} = '<b>'.&mt('Subject').': '.$content{'message'}.'</b><br />'.$broadcast_message;
 1909:                 } else {
 1910:                     %content=&Apache::lonmsg::unpackagemsg($content{'message'});
 1911:                     $content{'message'} =
 1912:                     '<b>'.&mt('Subject').': '.$content{'subject'}.'</b><br />'.
 1913:                     $content{'message'};
 1914:                 }
 1915:             }
 1916:         } elsif ($content{'subject'}=~/^Archive/) {
 1917:             $result.='<h3>'.&mt('Archived Message').'</h3>';
 1918:             if (defined($content{'coursemsgid'})) {
 1919:                 my $crsmsgid = &escape($content{'coursemsgid'});
 1920:                 my $archive_message = &general_message($crsmsgid);
 1921:                 $content{'message'} = '<b>'.&mt('Subject').': '.$content{'message'}.'</b><br />'.$archive_message;
 1922:             } else {
 1923:                 %content=&Apache::lonmsg::unpackagemsg($content{'message'});
 1924:                 $content{'message'} =
 1925:                 '<b>'.&mt('Subject').': '.$content{'subject'}.'</b><br
 1926: '.
 1927:                 $content{'message'};
 1928:             }
 1929:         } else {
 1930:             $result.='<h3>'.&mt('Critical Message').'</h3>';
 1931:             if (defined($content{'coursemsgid'})) {
 1932:                 my $crsmsgid=&escape($content{'coursemsgid'});
 1933:                 my $critical_message = &general_message($crsmsgid);
 1934:                 $content{'message'} = '<b>'.&mt('Subject').': '.$content{'message'}.'</b><br />'.$critical_message;
 1935:             } else {
 1936:                 %content=&Apache::lonmsg::unpackagemsg($content{'message'});
 1937:                 $content{'message'}=
 1938:                 '<b>'.&mt('Subject').': '.$content{'subject'}.'</b><br />'.
 1939: 		$content{'message'};
 1940:             }
 1941:         }
 1942:         $result.=&mt('By').': <b>'.
 1943: &Apache::loncommon::aboutmewrapper(
 1944:  &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).'</b> ('.
 1945: $content{'sendername'}.':'.
 1946:             $content{'senderdomain'}.') '.$content{'time'}.
 1947:             '<br /><pre>'.
 1948:               &Apache::lontexconvert::msgtexconverted($content{'message'}).
 1949: 	      '</pre>';
 1950:      }
 1951:     # Check to see if there were any messages.
 1952:     if ($result eq '') {
 1953:         my $lctype = &mt(lc(&Apache::loncommon::course_type()));
 1954: 	if ($target ne 'tex') { 
 1955: 	    $r->print("<p><b>".&mt('No notes, face-to-face discussion records, critical messages, or broadcast messages in this [_1].',$lctype)."</b></p>");
 1956: 	} else {
 1957: 	    $r->print('\textbf{'.&mt('No notes, face-to-face discussion records, critical messages or broadcast messages in this [_1].',$lctype).'}\\\\');
 1958: 	}
 1959:     } elsif ($target ne 'tex') {
 1960:        $r->print($result.'</div>');
 1961:     } else {
 1962: 		$r->print(&Apache::lonxml::xmlparse($r, 'tex', $result));
 1963: 	}
 1964: }
 1965: 
 1966: sub general_message {
 1967:     my ($crsmsgid) = @_;
 1968:     my %general_content;
 1969:     if ($crsmsgid) { 
 1970:         my %course_content = &Apache::lonnet::get('nohist_email',[$crsmsgid],
 1971:                            $env{'course.'.$env{'request.course.id'}.'.domain'},
 1972:                            $env{'course.'.$env{'request.course.id'}.'.num'});
 1973:         %general_content = &Apache::lonmsg::unpackagemsg($course_content{$crsmsgid});
 1974:     }
 1975:     return $general_content{'message'};
 1976: }
 1977: 
 1978: # ---------------------------------------------------------------- Face to face
 1979: 
 1980: sub facetoface {
 1981:     my ($r,$stage)=@_;
 1982:     if (!&Apache::lonnet::allowed('dff',$env{'request.course.id'})
 1983: 	&& ! &Apache::lonnet::allowed('dff',$env{'request.course.id'}.
 1984: 				      '/'.$env{'request.course.sec'})) {
 1985: 	$r->print(&mt('Not allowed'));
 1986: 	return;
 1987:     }
 1988:     my $crstype = &Apache::loncommon::course_type();
 1989:     my $leaders = ($crstype eq 'Community') ? 'coordinators and leaders'
 1990:                                             : 'faculty and staff';
 1991:     &printheader($r,
 1992: 		 '/adm/email?recordftf=query',
 1993: 		 "User Notes, Face-to-Face, Critical Messages, Broadcast Messages, Archived Messages");
 1994: # from query string
 1995: 
 1996:     if ($env{'form.recname'}) { $env{'form.recuname'}=$env{'form.recname'}; }
 1997:     if ($env{'form.recdom'}) { $env{'form.recdomain'}=$env{'form.recdom'}; }
 1998: 
 1999:     my $defdom=$env{'user.domain'};
 2000: # already filled in
 2001:     if ($env{'form.recdomain'}) { $defdom=$env{'form.recdomain'}; }
 2002: # generate output
 2003:     my $domform = &Apache::loncommon::select_dom_form($defdom,'recdomain');
 2004:     my $stdbrws = &Apache::loncommon::selectstudent_link
 2005: 	('stdselect','recuname','recdomain');
 2006:     my %lt=&Apache::lonlocal::texthash('user' => 'Username',
 2007: 				       'dom' => 'Domain',
 2008: 				       'head' => "User Notes, Records of Face-To-Face Discussions, Critical Messages, Broadcast Messages and Archived Messages in $crstype",
 2009: 				       'subm' => 'Retrieve discussion and message records',
 2010: 				       'newr' => 'New Record (record is visible to '.lc($crstype).' '.$leaders.')',
 2011: 				       'post' => 'Post this Record');
 2012: 
 2013:     $r->print('<h2>'.$lt{'head'}.'</h2>'
 2014:              .'<form method="post" action="/adm/email" name="stdselect">'
 2015:              .'<input type="hidden" name="recordftf" value="retrieve" />'
 2016:              .&Apache::lonhtmlcommon::start_pick_box()
 2017:              .&Apache::lonhtmlcommon::row_title($lt{'user'})
 2018:              .'<input type="text" size="12" name="recuname" value="'.$env{'form.recuname'}.'" />'
 2019:              .' '.$stdbrws
 2020:              .&Apache::lonhtmlcommon::row_closure()
 2021:              .&Apache::lonhtmlcommon::row_title($lt{'dom'})
 2022:              .$domform
 2023:              .&Apache::lonhtmlcommon::row_closure(1)
 2024:              .&Apache::lonhtmlcommon::end_pick_box()
 2025:              .'<br />'
 2026:              .'<input type="submit" value="'.$lt{'subm'}.'" />'
 2027:              .'</form>'
 2028:     );
 2029: 
 2030:     if (($stage ne 'query') &&
 2031:         ($env{'form.recdomain'}) && ($env{'form.recuname'})) {
 2032:         chomp($env{'form.newrecord'});
 2033:         if ($env{'form.newrecord'}) {
 2034: 	    &Apache::lonmsg::store_instructor_comment($env{'form.newrecord'},
 2035: 						      $env{'form.recuname'},
 2036: 						      $env{'form.recdomain'});
 2037:         }
 2038:         my $aboutmelink=&Apache::loncommon::aboutmewrapper(
 2039:                             &Apache::loncommon::plainname($env{'form.recuname'}
 2040:                                                          ,$env{'form.recdomain'})
 2041:                            ,$env{'form.recuname'},$env{'form.recdomain'});
 2042:         $r->print('<hr />'
 2043:                  .'<h2>'
 2044:                  .&mt('Discussion and message records for [_1] ([_2])'
 2045:                      ,$aboutmelink
 2046:                      ,$env{'form.recuname'}.':'.$env{'form.recdomain'})
 2047:                  .'<h2>'
 2048:        );
 2049:         &disfacetoface($r,$env{'form.recuname'},$env{'form.recdomain'});
 2050: 	$r->print(<<ENDRHEAD);
 2051: <form method="post" action="/adm/email">
 2052: <input name="recdomain" value="$env{'form.recdomain'}" type="hidden" />
 2053: <input name="recuname" value="$env{'form.recuname'}" type="hidden" />
 2054: ENDRHEAD
 2055:         $r->print(<<ENDBFORM);
 2056: <hr />$lt{'newr'}<br />
 2057: <textarea name="newrecord" cols="80" rows="10" wrap="hard"></textarea>
 2058: <br />
 2059: <input type="hidden" name="recordftf" value="post" />
 2060: <input type="submit" value="$lt{'post'}" />
 2061: </form>
 2062: ENDBFORM
 2063:     }
 2064: }
 2065: 
 2066: # ----------------------------------------------------------- Blocking during exams
 2067: 
 2068: sub examblock {
 2069:     my ($r,$action) = @_;
 2070:     unless ($env{'request.course.id'}) { return;}
 2071:     if (!&Apache::lonnet::allowed('dcm',$env{'request.course.id'})
 2072: 	&& ! &Apache::lonnet::allowed('dcm',$env{'request.course.id'}.
 2073: 				      '/'.$env{'request.course.sec'})) {
 2074: 	$r->print('Not allowed');
 2075: 	return;
 2076:     }
 2077:     my $usertype;
 2078:     my $crstype = &Apache::loncommon::course_type();
 2079:     if ($crstype eq 'Community') {
 2080:         $usertype = 'members';
 2081:     } else {
 2082: 	$usertype = 'students';
 2083:     }
 2084:     my $lctype = lc($crstype);
 2085:     my %lt=&Apache::lonlocal::texthash(
 2086:             'comb' => 'Communication Blocking',
 2087:             'cbds' => 'Communication blocking during scheduled exams',
 2088:             'desc' => "You can use communication blocking to prevent $usertype enrolled in this $lctype from displaying LON-CAPA messages sent by other $usertype during an online exam. As blocking of communication could potentially interrupt legitimate communication between $usertype who are also both enrolled in a different LON-CAPA course or community, please be careful that you select the correct start and end times for your scheduled exam when setting or modifying these parameters.",
 2089:              'mecb' => 'Modify existing communication blocking periods',
 2090:              'ncbc' => 'No communication blocks currently saved',
 2091:              'stor' => 'Save',
 2092:     );
 2093: 
 2094:     my %ltext = &Apache::lonlocal::texthash(
 2095:             'dura' => 'Duration',
 2096:             'setb' => 'Set by',
 2097:             'even' => 'Event',
 2098:             'blck' => 'Blocked?',
 2099:             'actn' => 'Action',
 2100:             'star' => 'Start',
 2101:             'endd' => 'End'
 2102:     );
 2103: 
 2104:     &printheader($r,'/adm/email?block=display',$lt{'comb'});
 2105:     $r->print('<h3>'.$lt{'cbds'}.'</h3>');
 2106: 
 2107:     if ($action eq 'store') {
 2108:         &blockstore($r);
 2109:     }
 2110: 
 2111:     $r->print($lt{'desc'}.'<br /><br />
 2112:                <form name="blockform" method="post" action="/adm/email?block=store">
 2113:              ');
 2114: 
 2115:     $r->print('<h4>'.$lt{'mecb'}.'</h4>');
 2116:     my %records = ();
 2117:     my $blockcount = 0;
 2118:     my $parmcount = 0;
 2119:     &get_blockdates(\%records,\$blockcount);
 2120:     if ($blockcount > 0) {
 2121:         $parmcount = &display_blocker_status($r,\%records,\%ltext);
 2122:     } else {
 2123:         $r->print($lt{'ncbc'}.'<br /><br />');
 2124:     }
 2125:     &display_addblocker_table($r,$parmcount,\%ltext);
 2126:     my $end_page=&Apache::loncommon::end_page();
 2127:     $r->print(<<"END");
 2128: <br />
 2129: <input type="hidden" name="blocktotal" value="$blockcount" />
 2130: <input type ="submit" value="$lt{'stor'}" />
 2131: </form>
 2132: $end_page
 2133: END
 2134:     return;
 2135: }
 2136: 
 2137: sub blockstore {
 2138:     my $r = shift;
 2139:     my %lt=&Apache::lonlocal::texthash(
 2140:             'tfcm' => 'The following changes were made',
 2141:             'ncwm' => 'No changes were made.' 
 2142:     );
 2143:     my %adds = ();
 2144:     my %removals = ();
 2145:     my %cancels = ();
 2146:     my $modtotal = 0;
 2147:     my $canceltotal = 0;
 2148:     my $addtotal = 0;
 2149:     my %blocking = ();
 2150:     $r->print('<h3>'.$lt{'head'}.'</h3>');
 2151:     foreach my $envkey (keys(%env)) {
 2152:         if ($envkey =~ m/^form\.modify_(\d+)$/) {
 2153:             $adds{$1} = $1;
 2154:             $removals{$1} = $1;
 2155:             $modtotal ++;
 2156:         } elsif ($envkey =~ m/^form\.cancel_(\d+)$/) {
 2157:             $cancels{$1} = $1;
 2158:             unless ( defined($removals{$1}) ) {
 2159:                 $removals{$1} = $1;
 2160:                 $canceltotal ++;
 2161:             }
 2162:         } elsif ($envkey =~ m/^form\.add_(\d+)$/) {
 2163:             $adds{$1} = $1;
 2164:             $addtotal ++;
 2165:         } 
 2166:     }
 2167: 
 2168:     foreach my $key (keys(%removals)) {
 2169:         my $hashkey = $env{'form.key_'.$key};
 2170:         &Apache::lonnet::del('comm_block',["$hashkey"],
 2171:                          $env{'course.'.$env{'request.course.id'}.'.domain'},
 2172:                          $env{'course.'.$env{'request.course.id'}.'.num'}
 2173:                          );
 2174:     }
 2175:     foreach my $key (keys(%adds)) {
 2176:         unless ( defined($cancels{$key}) ) {
 2177:             my ($newstart,$newend) = &get_dates_from_form($key);
 2178:             my $newkey = $newstart.'____'.$newend;
 2179:             my $blocktypes = &get_block_choices($key);
 2180:             $blocking{$newkey} = {
 2181:                           setter => $env{'user.name'}.':'.$env{'user.domain'},
 2182:                           event  => &escape($env{'form.title_'.$key}),
 2183:                           blocks => $blocktypes,
 2184:                         };
 2185:         }
 2186:     }
 2187:     if ($addtotal + $modtotal > 0) {
 2188:         &Apache::lonnet::put('comm_block',\%blocking,
 2189:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 2190:                      $env{'course.'.$env{'request.course.id'}.'.num'}
 2191:                      );
 2192:     }
 2193:     my $chgestotal = $canceltotal + $modtotal + $addtotal;
 2194:     if ($chgestotal > 0) {
 2195:         $r->print($lt{'tfcm'}.'<ul>');
 2196:         if ($canceltotal > 0) {
 2197:             $r->print('<li>'.&mt('[quant,_1,communication blocking period was,communication blocking periods were] removed.',$canceltotal).'</li>');
 2198:         }
 2199:         if ($modtotal > 0) {
 2200:             $r->print('<li>'.&mt('[quant,_1,communication blocking period was,communication blocking periods were] modified.',$modtotal).'</li>');
 2201:         }
 2202:         if ($addtotal > 0) {
 2203:             $r->print('<li>'.&mt('[quant,_1,communication blocking period was,communication blocking periods were] added.',$addtotal).'</li>');
 2204:         }
 2205:         $r->print('</ul>');
 2206:     } else {
 2207:         $r->print($lt{'ncwm'});
 2208:     }
 2209:     $r->print('<br />');
 2210:     return;
 2211: }
 2212: 
 2213: sub get_dates_from_form {
 2214:     my $item = shift;
 2215:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate_'.$item);
 2216:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate_'.$item);
 2217:     return ($startdate,$enddate);
 2218: }
 2219: 
 2220: sub get_blockdates {
 2221:     my ($records,$blockcount) = @_;
 2222:     $$blockcount = 0;
 2223:     %{$records} = &Apache::lonnet::dump('comm_block',
 2224:                          $env{'course.'.$env{'request.course.id'}.'.domain'},
 2225:                          $env{'course.'.$env{'request.course.id'}.'.num'}
 2226:                          );
 2227:     $$blockcount = keys(%{$records});
 2228: 
 2229:     if ((keys(%{$records}))[0] =~ /^error: 2 /) {
 2230: 	$records = {};
 2231: 	$$blockcount = 0;
 2232:     }
 2233: }
 2234: 
 2235: sub get_block_choices {
 2236:     my $item = shift;
 2237:     my $blocklist;
 2238:     my ($typeorder,$types) = &blocktype_text();
 2239:     foreach my $type (@{$typeorder}) {
 2240:         if ($env{'form.'.$type.'_'.$item}) {
 2241:             $blocklist->{$type} = 'on'; 
 2242:         } else {
 2243:             $blocklist->{$type} = 'off';
 2244:         }
 2245:     }
 2246:     return $blocklist;
 2247: }
 2248: 
 2249: sub display_blocker_status {
 2250:     my ($r,$records,$ltext) = @_;
 2251:     my $parmcount = 0;
 2252:   
 2253:     my %lt = &Apache::lonlocal::texthash(
 2254:         'modi' => 'Modify',
 2255:         'canc' => 'Cancel',
 2256:     );
 2257:     my ($typeorder,$types) = &blocktype_text();
 2258:     $r->print(&Apache::loncommon::start_data_table());
 2259:     $r->print(<<"END");
 2260:   <tr>
 2261:     <th>$ltext->{'dura'}</th>
 2262:     <th>$ltext->{'setb'}</th>
 2263:     <th>$ltext->{'even'}</th>
 2264:     <th>$ltext->{'blck'}</th>
 2265:     <th>$ltext->{'actn'}</th>
 2266:   </tr>
 2267: END
 2268:     foreach my $record (sort(keys(%{$records}))) {
 2269:         my $onchange = 'onFocus="javascript:window.document.forms['.
 2270:                        "'blockform'].elements['modify_".$parmcount."'].".
 2271:                        'checked=true;"';
 2272:         my ($start,$end) = split(/____/,$record);
 2273:         my $startform = &Apache::lonhtmlcommon::date_setter('blockform','startdate_'.$parmcount,$start,$onchange);
 2274:         my $endform = &Apache::lonhtmlcommon::date_setter('blockform','enddate_'.$parmcount,$end,$onchange);
 2275: 	
 2276: 	my ($setuname,$setudom,$title,$blocks) = 
 2277: 	    &Apache::loncommon::parse_block_record($$records{$record});
 2278: 	$title = &HTML::Entities::encode($title,'"<>&');
 2279:         my $settername = 
 2280:            &Apache::loncommon::aboutmewrapper(
 2281:                            &Apache::loncommon::plainname($setuname,$setudom),
 2282:                            $setuname,$setudom);
 2283:         $r->print(&Apache::loncommon::start_data_table_row());
 2284:         $r->print(<<"END");
 2285:         <td>$ltext->{'star'}:&nbsp;$startform<br />$ltext->{'endd'}:&nbsp;&nbsp;$endform</td>
 2286:         <td>$settername</td>
 2287:         <td><input type="text" name="title_$parmcount" size="15" value="$title" /><input type="hidden" name="key_$parmcount" value="$record" /></td>
 2288:         <td>
 2289: END
 2290:         foreach my $block (@{$typeorder}) {
 2291:             my $blockstatus = '';
 2292:             if ($blocks->{$block} eq 'on') {
 2293:                 $blockstatus = 'checked="checked"';
 2294:             }
 2295:             $r->print('<span class="LC_nobreak"><label><input type="checkbox" name="'.$block.'_'.$parmcount.'" '.$blockstatus.' value="1" />'.$types->{$block}.'</label></span><br />');
 2296:         }
 2297:         $r->print(<<"END");
 2298:         </td>      
 2299:         <td><span class="LC_nobreak"><label>
 2300:         <input type="checkbox" name="modify_$parmcount" />$lt{'modi'}
 2301:         </label></span><br /><span class="LC_nobreak">
 2302:         <label>
 2303:         <input type="checkbox" name="cancel_$parmcount" />$lt{'canc'}
 2304:         </label></span>
 2305: END
 2306:         $r->print(&Apache::loncommon::end_data_table_row());
 2307:         $parmcount++;
 2308:     }
 2309:     $r->print(<<"END");
 2310: </table>
 2311: <br />
 2312: <br />
 2313: END
 2314:     return $parmcount;
 2315: }
 2316: 
 2317: sub display_addblocker_table {
 2318:     my ($r,$parmcount,$ltext) = @_;
 2319:     my $start = time;
 2320:     my $end = $start + (60 * 60 * 2); #Default is an exam of 2 hours duration.
 2321:     my $onchange = 'onFocus="javascript:window.document.forms['.
 2322:                    "'blockform'].elements['add_".$parmcount."'].".
 2323:                    'checked=true;"';
 2324:     my $startform = &Apache::lonhtmlcommon::date_setter('blockform','startdate_'.$parmcount,$start,$onchange);
 2325:     my $endform = &Apache::lonhtmlcommon::date_setter('blockform','enddate_'.$parmcount,$end,$onchange);
 2326:     my %lt = &Apache::lonlocal::texthash(
 2327:         'addb' => 'Add block',
 2328:         'exam' => 'e.g., Exam 1',
 2329:         'addn' => 'Add new communication blocking periods'
 2330:     );
 2331:     my ($typeorder,$types) = &blocktype_text();
 2332:     $r->print(<<"END");
 2333: <h4>$lt{'addn'}</h4> 
 2334: END
 2335:     $r->print(&Apache::loncommon::start_data_table());
 2336:     $r->print(<<"END");
 2337:    <tr>
 2338:      <th>$ltext->{'dura'}</th>
 2339:      <th>$ltext->{'even'} $lt{'exam'}</th>
 2340:      <th>$ltext->{'blck'}</th>
 2341:      <th>$ltext->{'actn'}</th>
 2342:    </tr>
 2343: END
 2344:     $r->print(&Apache::loncommon::start_data_table_row());
 2345:     $r->print(<<"END");
 2346:      <td>$ltext->{'star'}:&nbsp;$startform<br />$ltext->{'endd'}:&nbsp;&nbsp;$endform</td>
 2347:      <td><input type="text" name="title_$parmcount" size="15" value="" /></td>
 2348:      <td>
 2349: END
 2350:     foreach my $block (@{$typeorder}) {
 2351:         $r->print('<span class="LC_nobreak"><label><input type="checkbox" name="'.$block.'_'.$parmcount.'" value="1" />'.$types->{$block}.'</label></span><br />');
 2352:      }
 2353:      $r->print(<<"END");
 2354:      </td>
 2355:      <td><span class="LC_nobreak"><label>
 2356:      <input type="checkbox" name="add_$parmcount" value="1" />$lt{'addb'}
 2357:      </label></span></td>
 2358: END
 2359:     $r->print(&Apache::loncommon::end_data_table_row());
 2360:     $r->print(&Apache::loncommon::end_data_table());
 2361:     return;
 2362: }
 2363: 
 2364: sub blocktype_text {
 2365:     my %types = &Apache::lonlocal::texthash(
 2366:         'com' => 'Messaging',
 2367:         'chat' => 'Chat Room',
 2368:         'boards' => 'Discussion',
 2369:         'port' => 'Portfolio',
 2370:         'groups' => 'Groups',
 2371:         'blogs' => 'Blogs',
 2372:     );
 2373:     my $typeorder = ['com','chat','boards','port','groups','blogs'];
 2374:     return ($typeorder,\%types);
 2375: }
 2376: 
 2377: # ----------------------------------------------------------- Display a message
 2378: 
 2379: sub displaymessage {
 2380:     my ($r,$msgid,$folder,$msgstatus)=@_;
 2381:     my $suffix=&Apache::lonmsg::foldersuffix($folder);
 2382:     my %blocked = ();
 2383:     my %setters = ();
 2384:     my $numblocked = 0;
 2385:     my $crstype = &Apache::loncommon::course_type();
 2386: 
 2387: # info to generate "next" and "previous" buttons and check if message is blocked
 2388:     my ($startblock,$endblock) = &Apache::loncommon::blockcheck(\%setters,'com');
 2389:     my @messages=&sortedmessages(\%blocked,$startblock,$endblock,\$numblocked,$folder,$msgstatus);
 2390:     if ( $blocked{$msgid} eq 'ON' ) {
 2391:         &printheader($r,'/adm/email',&mt('Display a Message'));
 2392:         #$r->print(&mt('You attempted to display a message that is currently blocked because you are enrolled in one or more courses for which there is an ongoing online exam.'));
 2393:         #&build_block_table($r,$startblock,$endblock,\%setters);
 2394:         my($blocked, $blocktext) = &Apache::loncommon::blocking_status("com");
 2395:         $r->print("<br />".$blocktext);
 2396:         return;
 2397:     }
 2398:     if ($msgstatus eq '') {
 2399:         &statuschange($msgid,'read',$folder);
 2400:     }
 2401:     my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
 2402:     my %content=&Apache::lonmsg::unpackagemsg($message{$msgid});
 2403:     my $counter=0;
 2404:     my $escmsgid=&escape($msgid);
 2405:     foreach (@messages) {
 2406: 	if ($_->[5] eq $escmsgid){
 2407: 	    last;
 2408: 	}
 2409: 	$counter++;
 2410:     }
 2411: 
 2412:     my $see_anonymous;
 2413:     my $from_student = 0;
 2414:     if ($env{'request.course.id'} eq $content{'courseid'}) {
 2415: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2416: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2417: 	my $username = $content{'sendername'}.':'.$content{'senderdomain'};
 2418: 	my %classlist_entry =
 2419: 	    &Apache::lonnet::get('classlist',[$username],$cdom,$cnum);
 2420: 	if (exists($classlist_entry{$username})) {
 2421: 	    $from_student = 1;
 2422: 	    $see_anonymous = &Apache::lonnet::allowed('rin',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''));
 2423: 	}
 2424:     }
 2425: 
 2426: 
 2427:     my $number_of_messages = scalar(@messages); #subtract 1 for last index
 2428: # start output
 2429:     &printheader($r,'/adm/email?display='.&escape($msgid),'Display a Message','',$content{'baseurl'});
 2430: 
 2431: # Prepare available functions
 2432:     my @functionlist;
 2433:     if (!$content{'noreplies'}) {
 2434:         push(@functionlist,'<a href="/adm/email?replyto='.&escape($msgid).$sqs.'">'
 2435:                      .&mt('Reply')
 2436:                      .'</a>');
 2437:     }
 2438:     push(@functionlist,'<a href="/adm/email?forward='.&escape($msgid).$sqs.'">'
 2439:                   .&mt('Forward')
 2440:                   .'</a>');
 2441:     push(@functionlist,'<a href="/adm/email?markunread='.&escape($msgid).$sqs.'">'
 2442:                   .&mt('Mark Unread')
 2443:                   .'</a>');
 2444:     push(@functionlist,'<a href="/adm/email?markdel='.&escape($msgid).$sqs.'">'
 2445:                   .&mt('Delete')
 2446:                   .'</a>');
 2447:     push(@functionlist,'<a href="/adm/email?'.$sqs.'">'
 2448:                   .&mt('Back to Folder Display')
 2449:                   .'</a>');
 2450:     if ($counter > 0){
 2451:         push(@functionlist,'<a href="/adm/email?display='.$messages[$counter-1]->[5].$sqs.'">'
 2452:                           .&mt('Previous')
 2453:                           .'</a>');
 2454:     }
 2455:     if ($counter < $number_of_messages - 1){
 2456:         push(@functionlist,'<a href="/adm/email?display='.$messages[$counter+1]->[5].$sqs.'">'
 2457:                           .&mt('Next')
 2458:                           .'</a>');
 2459:     }
 2460: 
 2461: # Prepare available actions
 2462:     my $symb;
 2463:     if (defined($content{'symb'})) {
 2464:         $symb = $content{'symb'};
 2465:     } elsif (defined($content{'baseurl'})) {
 2466:         $symb=&Apache::lonnet::symbread($content{'baseurl'});
 2467:     }
 2468:         my @actionlist;
 2469:     if ($env{'user.adv'}) {
 2470: 
 2471: 	if (&Apache::lonnet::allowed('vgr',$env{'request.course.id'})) {
 2472: 		push(@actionlist,&Apache::loncommon::track_student_link(
 2473:                                       &mt('View recent activity')
 2474:                                      ,$content{'sendername'}
 2475:                                      ,$content{'senderdomain'}
 2476:                                      ,'check'));
 2477: 	}
 2478: 	if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) && $symb) {
 2479: 	    push(@actionlist,&Apache::loncommon::pprmlink(
 2480:                                   &mt('Set/Change parameters')
 2481:                                      ,$content{'sendername'}
 2482:                                      ,$content{'senderdomain'}
 2483:                                      ,$symb
 2484:                                      ,'check'));
 2485: 	}
 2486: 	if (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}) && $symb) {
 2487: 	    push(@actionlist,&Apache::loncommon::pgrdlink(
 2488:                                  &mt('Set/Change grades')
 2489:                                      ,$content{'sendername'}
 2490:                                      ,$content{'senderdomain'}
 2491:                                      ,$symb
 2492:                                      ,'check'));
 2493: 	}
 2494:     }
 2495: 
 2496: # Print functionlist and actionlist in page header
 2497:         my $functions='<div class="LC_columnSection">';
 2498: 
 2499:         # Functionlist
 2500:         $functions.=&Apache::lonhtmlcommon::start_funclist();
 2501:         foreach my $item (@functionlist) {
 2502:             $functions.=&Apache::lonhtmlcommon::add_item_funclist($item);
 2503:         }
 2504:         $functions .= &Apache::lonhtmlcommon::end_funclist();
 2505: 
 2506:         # Actionlist
 2507:         if (@actionlist) {
 2508:             my $legendtext=&mt('Currently available actions (will open extra window)');
 2509:             $functions.=&Apache::lonhtmlcommon::start_funclist($legendtext);
 2510:             foreach my $item (@actionlist) {
 2511:                 $functions.=&Apache::lonhtmlcommon::add_item_funclist($item);
 2512:             }
 2513:             $functions.=&Apache::lonhtmlcommon::end_funclist();
 2514:         }
 2515: 
 2516:         $functions.='</div>';
 2517:         $r->print(&Apache::loncommon::head_subbox($functions));
 2518: 
 2519: 
 2520:     my ($tonum,$tolist,$cclist,$bcclist,$groupcclist,%recipients);
 2521:     if ($content{'recipid'}) {
 2522:         $tonum = &retrieve_recips('display',\%content,\%recipients);
 2523:         if (ref($recipients{'cc'}) eq 'ARRAY') {
 2524:             $cclist = join(', ',@{$recipients{'cc'}});
 2525:         }
 2526:         if (ref($recipients{'to'}) eq 'ARRAY') {
 2527:             $tolist = join(', ',@{$recipients{'to'}});
 2528:         }
 2529:         if (ref($recipients{'bcc'}) eq 'ARRAY') {
 2530:             $bcclist = join(', ',@{$recipients{'bcc'}});
 2531:         }
 2532:     }
 2533: 
 2534:     my $broadcast_link;
 2535:     if (($content{'courseid'}) && ($content{'recipid'} &&
 2536:         (ref($recipients{'course_broadcast'}) eq 'ARRAY') ||
 2537:         (ref($recipients{'group_cc_broadcast'}) eq 'ARRAY') ||
 2538:         (ref($recipients{'group_bcc_broadcast'}) eq 'ARRAY'))) {
 2539:         $broadcast_link = &recipients_link($r,\%content,\%recipients);
 2540:     }
 2541: 
 2542:     if (((!$tolist) && (!$broadcast_link)) && ref($content{'recuser'}) eq 'ARRAY') {
 2543:         my @recipients;
 2544:         for (my $i=0; $i<@{$content{'recuser'}}; $i++) {
 2545:             $recipients[$i] =  &Apache::loncommon::aboutmewrapper(
 2546:                &Apache::loncommon::plainname($content{'recuser'}[$i],
 2547:                                       $content{'recdomain'}[$i]),
 2548:                   $content{'recuser'}[$i],$content{'recdomain'}[$i]).
 2549:            ' ('.$content{'recuser'}[$i].':'.$content{'recdomain'}[$i].') ';
 2550:         }
 2551:         $tolist = join(', ',@recipients);
 2552:     }
 2553:     my ($restitle,$baseurl,$refers_to);
 2554:     if (defined($content{'resource_title'})) {
 2555:         $restitle = $content{'resource_title'};
 2556:     } else {
 2557:         if (defined($content{'baseurl'})) {
 2558:             $restitle = &Apache::lonnet::gettitle($content{'baseurl'});
 2559:         }
 2560:     }
 2561:     if (defined($content{'baseurl'})) {
 2562:         $baseurl = &Apache::lonenc::check_encrypt($content{'baseurl'});
 2563:     }
 2564:     $r->print('<div class="LC_clear_float_footer">');
 2565:     if ($from_student && $see_anonymous ) {
 2566: 	$r->print(&Apache::loncommon::student_image_tag($content{'senderdomain'},$content{'sendername'}).'</br>');
 2567:     }
 2568: 
 2569:     # Display LON-CAPA Message (Start)
 2570:     # Subject
 2571:     $r->print('</div>'
 2572:              .&Apache::lonhtmlcommon::start_pick_box()
 2573:              .&Apache::lonhtmlcommon::row_title(&mt('Subject'))
 2574:              .$content{'subject'}
 2575:              .&Apache::lonhtmlcommon::row_closure()
 2576:     );
 2577:     if ($folder eq 'sent') {
 2578:         # To
 2579:         if ($tolist) {
 2580:             $r->print(&Apache::lonhtmlcommon::row_title(&mt('To'))
 2581:                      .$tolist
 2582:                      .&Apache::lonhtmlcommon::row_closure()
 2583:             );
 2584:         }
 2585:         if ($cclist) {
 2586:             $r->print(&Apache::lonhtmlcommon::row_title(&mt('Cc'))
 2587:                      .$cclist
 2588:                      .&Apache::lonhtmlcommon::row_closure()
 2589:             );
 2590:         }
 2591:         if ($bcclist) {
 2592:             $r->print(&Apache::lonhtmlcommon::row_title(&mt('Bcc'))
 2593:                      .$bcclist
 2594:                      .&Apache::lonhtmlcommon::row_closure()
 2595:             );
 2596:         }
 2597:         if (($content{'courseid'}) && ($content{'recipid'})) {
 2598:             my %broadcast_types = 
 2599:                 &Apache::lonlocal::texthash (
 2600:                     course_broadcast    => 'Broadcast to', 
 2601:                     group_cc_broadcast  => 'Cc to group',
 2602:                     group_bcc_broadcast => 'Bcc to group',
 2603:                 );                   
 2604:             foreach my $type (sort(keys(%broadcast_types))) {
 2605:                 if (ref($recipients{$type}) eq 'ARRAY') {
 2606:                     my $num = @{$recipients{$type}};
 2607:                     my $broadcastlist = join(', ',@{$recipients{$type}});
 2608:                     if ($broadcastlist && $broadcast_link) {
 2609:                         if ($type eq 'group_cc_broadcast') {
 2610:                             $groupcclist = $broadcastlist;
 2611:                         }
 2612:                         $r->print(&Apache::lonhtmlcommon::row_title(
 2613:                                             $broadcast_types{$type})
 2614:                                   .&mt('[quant,_1,recipient]',$num)
 2615:                                   .' <a href="javascript:showBroadcastList();">['
 2616:                                   .&mt('Show').']</a>' 
 2617:                                   .&Apache::lonhtmlcommon::row_closure());
 2618:                     }
 2619:                 }
 2620:             }
 2621:         }
 2622:         if ($content{'replytoaddr'}) {
 2623:             my ($replytoname,$replytodom) = split(/:/,$content{'replytoaddr'});
 2624:             if ($replytoname ne '' && $replytodom ne '') {
 2625:                 $r->print(&Apache::lonhtmlcommon::row_title(&mt('Reply To'))
 2626:                          .$replytoname.':'.$replytodom
 2627:                          .&Apache::lonhtmlcommon::row_closure()
 2628:                 );
 2629:             }
 2630:         }
 2631:     } else {
 2632:         # From, Reply
 2633:         $r->print(&Apache::lonhtmlcommon::row_title(&mt('From'))
 2634:                  .&Apache::loncommon::aboutmewrapper(
 2635:                      &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),
 2636:                                                  $content{'sendername'},$content{'senderdomain'})
 2637:         );
 2638:         if ($content{'noreplies'}) {
 2639:             $r->print(' ('.&mt('No replies to sender').')'
 2640:                      .&Apache::lonhtmlcommon::row_closure()
 2641:             );
 2642:         } else {
 2643:             if ($content{'replytoaddr'}) {
 2644:                 my ($replytoname,$replytodom) = split(/:/,$content{'replytoaddr'});
 2645:                 if ($replytoname ne '' && $replytodom ne '') {
 2646:                     $r->print(&Apache::lonhtmlcommon::row_closure()
 2647:                              .&Apache::lonhtmlcommon::row_title(&mt('Reply To'))
 2648:                              .$replytoname.':'.$replytodom
 2649:                              .&Apache::lonhtmlcommon::row_closure()
 2650:                     );
 2651:                 } else {
 2652:                     $r->print(&Apache::lonhtmlcommon::row_closure());
 2653:                 }
 2654:             } else {
 2655:                 $r->print(' ('.$content{'sendername'}.':'.$content{'senderdomain'}.') '
 2656:                          .&Apache::lonhtmlcommon::row_closure()
 2657:                 );
 2658:             }
 2659:             if ($tonum && $tolist) {
 2660:                 $r->print(&Apache::lonhtmlcommon::row_title(&mt('To'))
 2661:                          .$tolist
 2662:                          .&Apache::lonhtmlcommon::row_closure()
 2663:                     );
 2664:             }
 2665:             if ($cclist) { 
 2666:                 $r->print(&Apache::lonhtmlcommon::row_title(&mt('Cc'))
 2667:                          .$cclist
 2668:                          .&Apache::lonhtmlcommon::row_closure()
 2669:                     );
 2670:             }
 2671:             if ($content{'group'} ne '') {
 2672:                 if (&check_group_priv($content{'group'})) {
 2673:                     if (ref($recipients{'group_cc_broadcast'}) eq 'ARRAY') { 
 2674:                         $groupcclist = join(', ',@{$recipients{'group_cc_broadcast'}});
 2675:                         if ($groupcclist) {
 2676:                             $r->print(&Apache::lonhtmlcommon::row_title(&mt('Group Cc'))
 2677:                                      .$groupcclist
 2678:                                      .&Apache::lonhtmlcommon::row_closure()
 2679:                             );
 2680:                         }
 2681:                     }
 2682:                 }
 2683:             }
 2684:         }
 2685:     }
 2686: 
 2687:     # Course
 2688:     if ($content{'courseid'} ne '') {
 2689:         if ($content{'courseid'} =~ m{^$match_domain\_$match_courseid$}) {
 2690:             my %courseinfo;
 2691:             %courseinfo=&Apache::lonnet::coursedescription($content{'courseid'},
 2692:                                                            {'one_time' => 1});
 2693:             my $description = $courseinfo{'description'};
 2694:             if ($description ne '') {
 2695:                 $r->print(&Apache::lonhtmlcommon::row_title(&mt($crstype))
 2696:                          .$description
 2697:                 );
 2698:                 if ($content{'coursesec'}) {
 2699:                     $r->print(' ('.&mt('Section').': '.$content{'coursesec'}.')');
 2700:                 }
 2701:                 $r->print(&Apache::lonhtmlcommon::row_closure());
 2702:             }
 2703:         }
 2704:     }
 2705:     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Time'))
 2706:              .$content{'time'}
 2707:              .&Apache::lonhtmlcommon::row_closure()
 2708:     );
 2709: 
 2710:     # Refers to
 2711:     if ($baseurl) {
 2712:         if (defined($content{'courseid'}) && defined($env{'request.course.id'})) {
 2713:             if ($content{'courseid'} eq $env{'request.course.id'}) {
 2714:                 my $symblink;
 2715:                 my $showsymb = &Apache::lonenc::check_decrypt($symb);
 2716:                 my $showurl = &Apache::lonenc::check_decrypt($baseurl);
 2717:                 my $encrypturl = &Apache::lonnet::EXT('resource.0.encrypturl',
 2718:                               $showsymb,$env{'user.domain'},$env{'user.name'});
 2719:                 if ($symb) {
 2720:                     if ($encrypturl =~ /^yes$/i && !$env{'request.role.adv'}) {
 2721:                         $showsymb = &Apache::lonenc::check_encrypt($symb);
 2722:                     }
 2723:                     $symblink = '?symb='.$showsymb;
 2724:                 }
 2725:                 if ($encrypturl =~ /^yes$/i && !$env{'request.role.adv'}) {
 2726:                     $showurl = $baseurl;
 2727:                 }
 2728:                 $r->print(&Apache::lonhtmlcommon::row_title(&mt('Refers to'))
 2729:                          .'<a href="'.$showurl.$symblink.'">'.$restitle.'</a>'
 2730:                          .&Apache::lonhtmlcommon::row_closure()
 2731:                 );
 2732:                 $refers_to = 1;
 2733:             }
 2734:         }
 2735:         if (!$refers_to) {
 2736:             if ($baseurl =~ m-^/enc/-) {
 2737:                 if (defined($content{'courseid'})) {
 2738:                     if (!$env{'request.course.id'}) {
 2739:                         my $unencurl =
 2740:                            &Apache::lonenc::unencrypted($baseurl,
 2741:                                                         $content{'courseid'});
 2742:                         if ($unencurl ne '') {
 2743:                             if (&Apache::lonnet::allowed('bre',$unencurl)) {
 2744:                                 $r->print(&Apache::lonhtmlcommon::row_title(&mt('Refers to'))
 2745:                                          .'<a href="'.$unencurl.'">'.$restitle.'</a>'
 2746:                                          .&Apache::lonhtmlcommon::row_closure()
 2747:                                 );
 2748:                             }
 2749:                         }
 2750:                     }
 2751:                 }
 2752:             } else {
 2753:                 if (&Apache::lonnet::allowed('bre',$baseurl)) {
 2754:                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Refers to'))
 2755:                              .'<a href="'.$baseurl.'">'.$restitle.'</a>'
 2756:                              .&Apache::lonhtmlcommon::row_closure()
 2757:                     );
 2758: 
 2759:                 }
 2760:             }
 2761:         }
 2762:     }
 2763: 
 2764:     # Message
 2765:     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Message'))
 2766:              .'<pre>'
 2767: 	     .&Apache::lontexconvert::msgtexconverted($content{'message'},1)
 2768: 	     .'</pre>'
 2769:     );
 2770:     if (&displayresource(%content)) {
 2771:         $r->print(&Apache::lonhtmlcommon::row_closure()
 2772:                  .&Apache::lonhtmlcommon::row_title(&mt('Resource Details'))
 2773:                  .&displayresource(%content)
 2774:         );
 2775:     } 
 2776:     $r->print(&Apache::lonhtmlcommon::row_closure(1).
 2777:               &Apache::lonhtmlcommon::end_pick_box());
 2778:     # Display LON-CAPA Message (End)
 2779:     return;
 2780: }
 2781: 
 2782: sub retrieve_recips {
 2783:     my ($context,$content,$recips)= @_;
 2784:     my $tonum = 0;
 2785:     if (ref($content) eq 'HASH') {
 2786:         my %reciphash =
 2787:             &Apache::lonnet::get('nohist_emailrecip',[$content->{'recipid'}],
 2788:                                  $content->{'senderdomain'},$content->{'sendername'});
 2789:         my $recipinfo = $reciphash{$content->{'recipid'}};
 2790:         if (ref($recipinfo) eq 'HASH') {
 2791:             foreach my $type ('to','cc','course_broadcast','group_cc_broadcast','group_bcc_broadcast') {
 2792:                 if (ref($recipinfo->{$type}) eq 'HASH') {
 2793:                     if ($type eq 'to') {
 2794:                         $tonum = keys(%{$recipinfo->{$type}});
 2795:                     }
 2796:                     foreach my $user (sort(keys(%{$recipinfo->{$type}}))) {
 2797:                         my ($uname,$udom) = split(/:/,$user);
 2798:                         next if (($context eq 'replying') && ($uname eq $env{'user.name'})
 2799:                                  && ($udom eq $env{'user.domain'}));
 2800:                         my $showuser ='<span class="LC_nobreak">';
 2801:                         if ($context eq 'replying') {
 2802:                             if (($type eq 'to') || ($type eq 'cc')) { 
 2803:                                 $showuser = '<label><input type="checkbox" name="replying_'.$type.'" value="'.$user.'" />';
 2804:                             } elsif ($type eq 'group_cc_broadcast') {
 2805:                                 $showuser = '<label><input type="checkbox" name="replying_groupcc" value="'.$user.'" />';
 2806:                             }
 2807:                         }
 2808:                         $showuser .= &Apache::loncommon::aboutmewrapper(
 2809:                                            &Apache::loncommon::plainname($uname,
 2810:                                            $udom),$uname,$udom);
 2811: 		        if ($context eq 'replying') {
 2812: 		            $showuser .='</label>';
 2813: 		        }
 2814: 		        $showuser .= '</span>';
 2815:                         if (ref($recips) eq 'HASH') {
 2816: 		            push(@{$recips->{$type}},$showuser);
 2817:                         }
 2818:                     }
 2819:                 }
 2820:             }
 2821:         }
 2822:     }
 2823:     return $tonum;
 2824: }
 2825: 
 2826: sub recipients_link {
 2827:     my ($r,$content,$recipients) = @_;
 2828:     my ($broadcast_link,$show);
 2829:     if ((ref($content) eq 'HASH') && (ref($recipients) eq 'HASH')) {
 2830:         if (ref($recipients->{'course_broadcast'}) eq 'ARRAY') {
 2831:             if (@{$recipients->{'course_broadcast'}} > 0) {
 2832:                 $show = 'course';
 2833:             }
 2834:         } elsif (ref($recipients->{'group_cc_broadcast'}) eq 'ARRAY') {
 2835:             if (@{$recipients->{'group_cc_broadcast'}} > 0) {
 2836:                 $show = 'group_cc';
 2837:             }
 2838:         } elsif (ref($recipients->{'group_bcc_broadcast'}) eq 'ARRAY') {
 2839:             if (@{$recipients->{'group_bcc_broadcast'}} > 0) {
 2840:                 $show = 'group_bcc';
 2841:             }
 2842:         }
 2843:         if ($show) {
 2844:             my ($nothing,$height,$width,$start_page,$end_page,$body);
 2845:             $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 2846:             $height = 400;
 2847:             $width = 600;
 2848:             $start_page =
 2849:                 &Apache::loncommon::start_page('Broadcast List', undef,
 2850:                                                {only_body => 1,
 2851:                                                 js_ready  => 1,});
 2852:             $end_page = &Apache::loncommon::end_page({js_ready => 1,});
 2853:             $body = '<h3>'.&mt("Recipients of broadcast message").'</h3>'.
 2854:                     &Apache::loncommon::start_data_table();
 2855:             my $cell = 0;
 2856:             $body .= &Apache::loncommon::start_data_table_row();
 2857:             foreach my $item (@{$recipients->{$show.'_broadcast'}}) {
 2858:                 $item =~ s/'/\\'/g;
 2859:                 if (!($cell%2) && $cell > 0) {
 2860:                     $body .= &Apache::loncommon::end_data_table_row().
 2861:                              &Apache::loncommon::start_data_table_row();
 2862:                 }
 2863:                 $cell ++;
 2864:                 $body .= '<td>'.$cell.'&nbsp;'.$item.'&nbsp;&nbsp;</td>';
 2865:             }
 2866:             if ($cell%2) {
 2867:                 $body .= '<td>&nbsp;</td>';
 2868:             }
 2869:             $body .= &Apache::loncommon::end_data_table_row().
 2870:                      &Apache::loncommon::end_data_table();
 2871:             $body =~ s{</}{<\\/}g;
 2872:             $body =~ s{\n}{}g;
 2873:             $r->print(<<ENDJS);
 2874: <script type="text/javascript">
 2875: // <![CDATA[
 2876: function showBroadcastList() {
 2877:     var caller = this;
 2878:     var newWindow = null;
 2879:     try {
 2880:         newWindow =  window.open($nothing,"broadcast","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" );
 2881:     }
 2882:     catch(error) {
 2883:         writeWin(caller);
 2884:         return;
 2885:     }
 2886:     if (newWindow) {
 2887:         caller = newWindow;
 2888:     }
 2889:     writeWin(caller);
 2890:     return;
 2891: }
 2892: 
 2893: function writeWin(caller) {
 2894:     caller.document.writeln('$start_page $body $end_page');
 2895:     caller.document.close();
 2896:     caller.focus();
 2897: }
 2898: // ]]>
 2899: </script>
 2900: 
 2901: ENDJS
 2902:             $broadcast_link = 1;
 2903:         }
 2904:     }
 2905:     return $broadcast_link;
 2906: }
 2907: 
 2908: # =========================================================== Show the citation
 2909: 
 2910: sub displayresource {
 2911:     my %content=@_;
 2912: #
 2913: # If the recipient is in the same course that the message was sent from and
 2914: # has sufficient privileges, show "all details," else show citation
 2915: #
 2916:     if (($env{'request.course.id'} eq $content{'courseid'})
 2917:      && (&Apache::lonnet::allowed('vgr',$content{'courseid'}))) {
 2918:         my $symb;
 2919:         if (defined($content{'symb'})) {
 2920:             $symb = $content{'symb'};
 2921:         } else { 
 2922: 	    $symb=&Apache::lonnet::symbread($content{'baseurl'});
 2923:         }
 2924: # Could not get a symb, give up
 2925: 	unless ($symb) { return $content{'citation'}; }
 2926: # Have a symb, can render
 2927: 	return '<h2>'.&mt('Current attempts of student (if applicable)').'</h2>'.
 2928: 	    &Apache::loncommon::get_previous_attempt($symb,
 2929: 						     $content{'sendername'},
 2930: 						     $content{'senderdomain'},
 2931: 						     $content{'courseid'}).
 2932: 	    '<hr /><h2>'.&mt('Current screen output (if applicable)').'</h2>'.
 2933: 	    &Apache::loncommon::get_student_view($symb,
 2934: 						 $content{'sendername'},
 2935: 						 $content{'senderdomain'},
 2936: 						 $content{'courseid'}).
 2937: 	    '<h2>'.&mt('Correct Answer(s) (if applicable)').'</h2>'.
 2938: 	    &Apache::loncommon::get_student_answers($symb,
 2939: 						    $content{'sendername'},
 2940: 						    $content{'senderdomain'},
 2941: 						    $content{'courseid'});
 2942:     } elsif ($env{'user.adv'}) {
 2943: 	return $content{'citation'};
 2944:     }
 2945:     return '';
 2946: }
 2947: 
 2948: # ================================================================== The Header
 2949: 
 2950: sub header {
 2951:     my ($r,$title,$baseurl)=@_;
 2952:     my $extra = &Apache::loncommon::studentbrowser_javascript();
 2953:     if ($baseurl) {
 2954: 	$extra .= "<base href=\"".&Apache::lonnet::absolute_url()."/$baseurl\" />";
 2955:     }
 2956:     $r->print(&Apache::loncommon::start_page('Messages',
 2957:  					$extra));
 2958:     $r->print(&Apache::lonhtmlcommon::breadcrumbs
 2959:      		(($title?$title:'Send and display messages')));
 2960: }
 2961: 
 2962: # ---------------------------------------------------------------- Print header
 2963: 
 2964: sub printheader {
 2965:     my ($r,$url,$desc,$title,$baseurl)=@_;
 2966:     &Apache::lonhtmlcommon::add_breadcrumb
 2967: 	({href=>$url,
 2968: 	  text=>$desc});
 2969:     &header($r,$title,$baseurl);
 2970: }
 2971: 
 2972: # ------------------------------------------------------------ Store the comment
 2973: 
 2974: sub storecomment {
 2975:     my ($r)=@_;
 2976:     my $msgtxt=&Apache::lonfeedback::clear_out_html($env{'form.message'});
 2977:     my $cleanmsgtxt='';
 2978:     foreach my $line (split(/[\n\r]/,$msgtxt)) {
 2979: 	unless ($line=~/^\s*(\>|\&gt\;)/) {
 2980: 	    $cleanmsgtxt.=$line."\n";
 2981: 	}
 2982:     }
 2983:     my $key=&escape($env{'form.baseurl'}).'___'.time;
 2984:     &Apache::lonnet::put('nohist_stored_comments',{ $key => $cleanmsgtxt });
 2985: }
 2986: 
 2987: sub storedcommentlisting {
 2988:     my ($r)=@_;
 2989:     my %msgs=&Apache::lonnet::dump('nohist_stored_comments',undef,undef,
 2990:        '^'.&escape(&escape($env{'form.showcommentbaseurl'})));
 2991:     $r->print(&Apache::loncommon::start_page('Saved Comment Listing',undef,
 2992: 					     {'onlybody' => 1}));
 2993:     if ((keys %msgs)[0]=~/^error\:/) {
 2994: 	$r->print(&mt('No saved comments yet.'));
 2995:     } else {
 2996: 	my $found=0;
 2997: 	foreach my $key (sort(keys(%msgs))) {
 2998: 	    $r->print("\n".$msgs{$key}."<hr />");
 2999: 	    $found=1;
 3000: 	}
 3001: 	unless ($found) {
 3002: 	    $r->print(&mt('No saved comments yet for this resource.'));
 3003: 	}
 3004:     }
 3005: }
 3006: 
 3007: # ---------------------------------------------------------------- Send an email
 3008: 
 3009: sub sendoffmail {
 3010:     my ($r,$folder)=@_;
 3011:     my $suffix=&Apache::lonmsg::foldersuffix($folder);
 3012:     my $sendstatus='';
 3013:     my %msg_status;
 3014:     my $numsent = 0;
 3015:     my $nosentstore = 1;
 3016:     my $attachmenturl;
 3017:     my $now = time;
 3018:     my ($cdom,$cnum,$group);
 3019:     if (exists($env{'form.group'})) {
 3020:         $group = $env{'form.group'};
 3021:     }
 3022:     if (exists($env{'request.course.id'})) {
 3023:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3024:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3025:     }
 3026:     if ($env{'form.send'}) {
 3027:         if (!$env{'form.multiforward'}) { 
 3028:             if ($group eq '') {
 3029: 	        &printheader($r,'','Messages being sent.');
 3030:             } else {
 3031:                 $r->print(&groupmail_header('sending',$group));
 3032:             }
 3033:         }
 3034: 	$r->rflush();
 3035: 	my %content=();
 3036: 	undef %content;
 3037: 	if ($env{'form.forwid'}) {
 3038: 	    my $msgid=$env{'form.forwid'};
 3039: 	    my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
 3040: 	    %content=&Apache::lonmsg::unpackagemsg($message{$msgid},1,1);
 3041: 	    &statuschange($msgid,'forwarded',$folder);
 3042:             if ($content{'attachmenturl'} ne '') {
 3043:                 $attachmenturl = $content{'attachmenturl'};
 3044:             }
 3045: 	    $env{'form.message'} .= "\n\n-- Forwarded message --\n\n".
 3046: 		                    $content{'message'};
 3047: 	}
 3048: 	if ($env{'form.replyid'}) {
 3049: 	    my $msgid=$env{'form.replyid'};
 3050: 	    my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
 3051: 	    %content=&Apache::lonmsg::unpackagemsg($message{$msgid},1);
 3052: 	    &statuschange($msgid,'replied',$folder);
 3053: 	}
 3054: 
 3055: 	my $mode = $env{'form.sendmode'};
 3056: 	my (%toaddr,$tos,$cc,$bcc,$broadcast);
 3057: 
 3058: 	if ($mode eq 'group') {
 3059:             if (defined($env{'form.courserecips'})) {
 3060:                 my $courseusers = $env{'form.courserecips'};
 3061:                 $courseusers =~ s/^_\&\&\&_//;
 3062:                 my @to = split('_&&&_',$courseusers);
 3063:                 foreach my $dest (@to) {
 3064:                     my ($user,$domain) = split(/:/, $dest);
 3065:                     if (($user ne '') && ($domain ne '')) {
 3066:                         my $rec = $user.":".$domain;
 3067:                         $toaddr{$rec} = '';
 3068:                         $broadcast->{$rec} = '';
 3069:                     }
 3070:                 }
 3071:             }
 3072: 	} elsif ($mode eq 'upload') {
 3073:             $nosentstore = 0;
 3074: 	    foreach my $line (split(/[\n\r\f]+/,$env{'form.upfile'})) {
 3075:                 my ($rec,$txt) = ($line =~ /^([^:]+:[^:]+):(.*)$/);
 3076: 		if ($txt) {
 3077:                     $rec =~ s/^\s+//;
 3078:                     $rec =~ s/\s+$//;
 3079: 		    $toaddr{$rec}.=$txt."\n";
 3080:                     $broadcast->{$rec} = '';
 3081: 		}
 3082: 	    }
 3083: 	} else {
 3084: 	    if (($env{'form.recuname'} ne '') && ($env{'form.recdomain'} ne '')) {
 3085: 		$toaddr{$env{'form.recuname'}.':'.$env{'form.recdomain'}}='';
 3086:                 $tos->{$env{'form.recuname'}.':'.$env{'form.recdomain'}}='';
 3087: 	    }
 3088: 	}
 3089:         if ($env{'form.additionalrec_to'}) {
 3090:             foreach my $rec (split(/\s*,\s*/,$env{'form.additionalrec_to'})) {
 3091:                 my ($auname,$audom)=split(/:/,$rec);
 3092:                 if (($auname ne "") && ($audom ne "")) {
 3093:                     $toaddr{$auname.':'.$audom}='';
 3094:                     $tos->{$auname.':'.$audom}='';
 3095:                 }
 3096:             }
 3097:         }
 3098:         if ($env{'form.replying_to'}) {
 3099:             my @toreplies =
 3100:                 &Apache::loncommon::get_env_multiple('form.replying_to');
 3101:             foreach my $rec (@toreplies) {
 3102:                 my ($auname,$audom)=split(/:/,$rec);
 3103:                 if (($auname ne "") && ($audom ne "")) {
 3104:                     $toaddr{$auname.':'.$audom}='';
 3105:                     $tos->{$auname.':'.$audom}='';
 3106:                 }
 3107:             }
 3108:         }
 3109: 	if ($env{'form.additionalrec_cc'}) {
 3110: 	    foreach my $rec (split(/\s*,\s*/,$env{'form.additionalrec_cc'})) {
 3111: 		my ($auname,$audom)=split(/:/,$rec);
 3112: 		if (($auname ne "") && ($audom ne "")) {
 3113:                     $toaddr{$auname.':'.$audom}='';
 3114:                     if (!defined($tos->{$auname.':'.$audom})) {
 3115: 		        $cc->{$auname.':'.$audom}='';
 3116:                     }
 3117: 		}
 3118: 	    }
 3119: 	}
 3120:         if ($env{'form.replying_cc'}) {
 3121:             my @ccreplies =
 3122:                 &Apache::loncommon::get_env_multiple('form.replying_cc');
 3123:             foreach my $rec (@ccreplies) {
 3124:                 my ($auname,$audom)=split(/:/,$rec);
 3125:                 if (($auname ne "") && ($audom ne "")) {
 3126:                     $toaddr{$auname.':'.$audom}='';
 3127:                     if (!defined($tos->{$auname.':'.$audom})) {
 3128:                         $cc->{$auname.':'.$audom}='';
 3129:                     }
 3130:                 }
 3131:             }
 3132:         }
 3133:         if ($env{'form.replying_groupcc'}) {
 3134:             my @groupreplies =
 3135:                 &Apache::loncommon::get_env_multiple('form.replying_groupcc');
 3136:             foreach my $rec (@groupreplies) {
 3137:                 my ($auname,$audom)=split(/:/,$rec);
 3138:                 if (($auname ne "") && ($audom ne "")) {
 3139:                     $toaddr{$auname.':'.$audom}='';
 3140:                     if (!defined($tos->{$auname.':'.$audom})) {
 3141:                         $broadcast->{$auname.':'.$audom}='';
 3142:                     }
 3143:                 }
 3144:             }
 3145:         }
 3146:         if ($env{'form.additionalrec_bcc'}) {
 3147:             foreach my $rec (split(/\s*,\s*/,$env{'form.additionalrec_bcc'})) {
 3148:                 my ($auname,$audom)=split(/:/,$rec);
 3149:                 if (($auname ne "") && ($audom ne "")) {
 3150:                     $toaddr{$auname.':'.$audom}='';
 3151:                     if ((!defined($tos->{$auname.':'.$audom})) && 
 3152:                         (!defined($cc->{$auname.':'.$audom}))) {
 3153:                         $bcc->{$auname.':'.$audom}='';
 3154:                     }
 3155:                 }
 3156:             }
 3157:         }
 3158:         my $savemsg;
 3159:         my $msgtype;
 3160:         my %sentmessage;
 3161:         my $msgsubj=&Apache::lonfeedback::clear_out_html($env{'form.subject'},
 3162: 							 undef,1);
 3163:         if ((($env{'form.critmsg'}) || ($env{'form.sendbck'})) &&
 3164:             (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
 3165: 	     || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
 3166: 					 '/'.$env{'request.course.sec'})
 3167: 	     )) {
 3168:             $savemsg=&Apache::lonfeedback::clear_out_html($env{'form.message'},1);
 3169:             $msgtype = 'critical';
 3170:         } else {
 3171:             $savemsg=&Apache::lonfeedback::clear_out_html($env{'form.message'});
 3172:         }
 3173:         my %reciphash = (
 3174:                            to => $tos,
 3175:                            cc => $cc,
 3176:                            bcc => $bcc,
 3177:                         );
 3178:         if ($mode eq 'group') {
 3179:             if ($group eq '') {
 3180:                 $reciphash{'course_broadcast'} = $broadcast;
 3181:             } else {
 3182:                 if ($env{'form.groupmail'} eq 'cc') {
 3183:                     $reciphash{'group_cc_broadcast'} = $broadcast;
 3184:                 } else {
 3185:                     $reciphash{'group_bcc_broadcast'} = $broadcast;
 3186:                 }
 3187:             }
 3188:         }
 3189:         my ($recipid,$recipstatus) = 
 3190:             &Apache::lonmsg::store_recipients($msgsubj,$env{'user.name'},
 3191:                                        $env{'user.domain'},\%reciphash);
 3192:         if ($recipstatus ne 'ok') {
 3193:             &Apache::lonnet::logthis('Failed to store To, Bcc and Cc recipients for '.$env{'user.name'}.':'.$env{'user.domain'});
 3194:         }
 3195:         if ($env{'form.attachment'}) {
 3196:             if (length($env{'form.attachment'})<131072) {
 3197:                 $attachmenturl=&Apache::lonnet::userfileupload('attachment',undef,'feedback/'.$now);
 3198:             } else {
 3199:                 $r->print('<p><span class="LC_warning">'.&mt('Attachment not included - exceeded permitted length').'</span><br /></p>');
 3200:             }
 3201:         } elsif ($env{'form.multiforward'}) {
 3202:             if ($env{'form.attachmenturl'} ne '') {
 3203:                 $attachmenturl = $env{'form.attachmenturl'};
 3204:             }
 3205:         }
 3206:         my @recusers;
 3207:         my @recudoms;
 3208: 	foreach my $address (sort(keys(%toaddr))) {
 3209: 	    my ($recuname,$recdomain)=split(/\:/,$address);
 3210:             my $msgtxt = $savemsg;
 3211:             if ($toaddr{$address}) {
 3212: 	        $msgtxt.="\n".'<hr />'."\n".$toaddr{$address};
 3213:             }
 3214: 	    my @thismsg;
 3215: 	    if ($msgtype eq 'critical') {
 3216: 		$r->print(&mt('Sending critical message').' '.
 3217:                               $recuname.':'.$recdomain.': ');
 3218: 		@thismsg=
 3219: 		    &Apache::lonmsg::user_crit_msg($recuname,$recdomain,
 3220: 						   $msgsubj,$msgtxt,
 3221: 						   $env{'form.sendbck'},
 3222: 						   $env{'form.permanent'},
 3223: 						   \$sentmessage{$address},
 3224:                                                    $nosentstore,$recipid);
 3225: 	    } else {
 3226: 		$r->print(&mt('Sending').' '.$recuname.':'.$recdomain.': ');
 3227: 		@thismsg=
 3228: 		    &Apache::lonmsg::user_normal_msg($recuname,$recdomain,
 3229: 						     $msgsubj,$msgtxt,
 3230: 						     $content{'citation'},
 3231: 						     undef,$attachmenturl,
 3232: 						     $env{'form.permanent'},
 3233: 						     \$sentmessage{$address},
 3234:                                                      undef,undef,undef,
 3235:                                                      $nosentstore,$recipid);
 3236:             }
 3237: 	    $msg_status{$recuname.':'.$recdomain}=join(' ',@thismsg);
 3238: 	    if ($msg_status{$recuname.':'.$recdomain} =~ /(ok|con_delayed)/) {  
 3239: 	        $numsent++;
 3240:                 push(@recusers,$recuname);
 3241:                 push(@recudoms,$recdomain);
 3242: 	    }
 3243: 	    $sendstatus.=' '.join(' ',@thismsg);
 3244: 	}
 3245:         my $subj_prefix;
 3246:         if ($numsent > 0) {
 3247:             if (($env{'request.course.id'}) && 
 3248:                 (($mode eq 'group') ||
 3249:                  ($env{'form.courserecord'}) ||
 3250:                  ($msgtype eq 'critical')) ||
 3251:                 ($env{'form.replyid'} && 
 3252:                  (($content{'courseid'} ne '') && 
 3253:                   ($mode eq 'group')))) {
 3254:                 if ($msgtype eq 'critical') {
 3255:                     $subj_prefix = 'Critical.';
 3256:                 } elsif ($mode eq 'group') {
 3257:                     $subj_prefix = 'Broadcast.';
 3258:                 } else {
 3259:                     $subj_prefix = 'Archive';
 3260:                 }
 3261:                 my ($specialmsgid,$specialresult);
 3262:                 my $course_str;
 3263:                 if ($env{'form.replyid'}) {
 3264:                     if ($content{'courseid'} ne '') {
 3265:                         my %crsdesc = 
 3266:                             &Apache::lonnet::coursedescription($content{'courseid'},
 3267:                                                                {'one_time' => 1});
 3268:                         $course_str = &escape('['.$crsdesc{'num'}.':'.$crsdesc{'domain'}.']');
 3269:                     }
 3270:                 } elsif ($env{'request.course.id'}) {
 3271:                     $course_str = &escape('['.$cnum.':'.$cdom.']');
 3272:                 }
 3273:                 $specialresult = 
 3274:                     &Apache::lonmsg::user_normal_msg_raw($cnum,$cdom,
 3275:                         $subj_prefix.' '.$course_str,$savemsg,undef,undef,
 3276:                         $attachmenturl,undef,undef,\$specialmsgid,undef,undef,undef,
 3277:                         undef,undef,1);
 3278:                 $specialmsgid = &unescape($specialmsgid);
 3279:                 if ($specialresult eq 'ok') {
 3280:                     my ($stamp,$crssubj,$msgname,$msgdom,$msgcount,$context,$pid) =
 3281: 		        split(/\:/,&unescape($specialmsgid));
 3282: 
 3283:                     foreach my $recipient (sort(keys(%toaddr))) {
 3284:                         if ($msg_status{$recipient} =~ /\s*(ok|con_delayed)\s*/) {
 3285:                             my $usersubj = $subj_prefix.'['.$recipient.']';
 3286:                             my $usermsgid = 
 3287: 			        &Apache::lonmsg::buildmsgid($stamp,$usersubj,
 3288: 							    $msgname,$msgdom,
 3289: 							    $msgcount,$context,
 3290: 							    $pid);
 3291:                             &Apache::lonmsg::user_normal_msg_raw($cnum,$cdom,
 3292:                                 $subj_prefix.' ['.$recipient.']',$msgsubj,
 3293:                                 undef,undef,$attachmenturl,undef,$usermsgid,undef,
 3294:                                 undef,$specialmsgid,undef,undef,undef,1);
 3295:                         }
 3296:                     }
 3297:                     if (($mode ne 'upload') && (@recusers > 0)) {
 3298:                         &Apache::lonmsg::process_sent_mail($msgsubj,
 3299:                            $subj_prefix,$numsent,$stamp,$msgname,$msgdom,
 3300:                            $msgcount,$context,$pid,$savemsg,\@recusers,
 3301:                            \@recudoms,undef,$attachmenturl,'','','','',$recipid);
 3302:                     }
 3303:                 } else {
 3304:                     &Apache::lonnet::logthis('Failed to create record of critical, broadcast or archived message in '.$env{'course.'.$env{'request.course.id'}.'.num'}.' '&mt('at').' '.$env{'course.'.$env{'request.course.id'}.'.domain'}.' - no msgid generated');
 3305:                 }
 3306:             } else {
 3307:                 my $stamp = time;
 3308:                 my $msgcount = &Apache::lonmsg::get_uniq();
 3309:                 my $context = &Apache::lonmsg::get_course_context();
 3310:                 &Apache::lonmsg::process_sent_mail($msgsubj,$subj_prefix,
 3311:                        $numsent,$stamp,$env{'user.name'},
 3312:                        $env{'user.domain'},$msgcount,$context,
 3313:                        $$,$savemsg,\@recusers,\@recudoms,undef,$attachmenturl,
 3314:                        '','','','',$recipid);
 3315:             }
 3316:         }
 3317:         if (!$env{'form.multiforward'}) {
 3318:             if ($sendstatus=~/^(\s*(?:ok|con_delayed)\s*)*$/) {
 3319:                 my $message = &Apache::lonhtmlcommon::confirm_success(&mt('Completed.'));
 3320:                 $message = &Apache::loncommon::confirmwrapper($message);
 3321:                 $r->print($message);
 3322: 	        if ($env{'form.displayedcrit'}) {
 3323: 	            &discrit($r);
 3324:                 }
 3325:                 if ($group ne '') {
 3326:                     $r->print(&groupmail_sent($group,$cdom,$cnum)); 
 3327: 	        } else {
 3328: 	            &Apache::loncommunicate::menu($r);
 3329: 	        }
 3330:             } else {
 3331:                 my $message = &Apache::lonhtmlcommon::confirm_success(&mt('Could not deliver message'),1);
 3332:                 $message .= '<br />'.&mt('Please use the browser "Back" button and correct the recipient addresses ([_1]).',$sendstatus);
 3333:                 $message = &Apache::loncommon::confirmwrapper($message);
 3334:                 $r->print($message);
 3335:             }
 3336:         }
 3337:     } else {
 3338:         &printheader($r,'','Messages cancelled.');
 3339:         return 'cancelled';
 3340:     }
 3341:     return $sendstatus;
 3342: }
 3343: 
 3344: # ===================================================================== Handler
 3345: 
 3346: sub handler {
 3347:     my $r=shift;
 3348: 
 3349: # ----------------------------------------------------------- Set document type
 3350:     
 3351:     &Apache::loncommon::content_type($r,'text/html');
 3352:     $r->send_http_header;
 3353:     
 3354:     return OK if $r->header_only;
 3355:     
 3356: # --------------------------- Get query string for limited number of parameters
 3357:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 3358:         ['display','replyto','forward','markread','markdel','markunread',
 3359:          'sendreply','compose','sendmail','critical','recname','recdom',
 3360:          'recordftf','sortedby','block','folder','startdis','interdis',
 3361: 	 'showcommentbaseurl','dismode','group','subject','text','ref',
 3362:          'msgstatus']);
 3363:     $sqs='&amp;sortedby='.$env{'form.sortedby'};
 3364: 
 3365: # ------------------------------------------------------ They checked for email
 3366:     unless ($env{'form.block'}) {
 3367:         &Apache::lonnet::put('email_status',{'recnewemail'=>0});
 3368:     }
 3369: 
 3370: # ----------------------------------------------------------------- Breadcrumbs
 3371: 
 3372:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 3373:     &Apache::lonhtmlcommon::add_breadcrumb
 3374:         ({href=>"/adm/communicate",
 3375:           text=>"Messages",
 3376:           faq=>12,bug=>'Communication Tools',});
 3377: 
 3378: # ------------------------------------------------------------------ Get Folder
 3379: 
 3380:     my $folder=$env{'form.folder'};
 3381:     unless ($folder) { 
 3382: 	$folder=''; 
 3383:     } else {
 3384: 	$sqs.='&amp;folder='.&escape($folder);
 3385:     }
 3386: # ------------------------------------------------------------ Get Display Mode
 3387: 
 3388:     my $dismode=$env{'form.dismode'};
 3389:     unless ($dismode) { 
 3390: 	$dismode=''; 
 3391:     } else {
 3392: 	$sqs.='&amp;dismode='.&escape($dismode);
 3393:     }
 3394: 
 3395: # --------------------------------------------------------------------- Display
 3396:     my $msgstatus = $env{'form.msgstatus'};
 3397:     $startdis=$env{'form.startdis'};
 3398:     if ($startdis ne '') {
 3399:         $startdis--;
 3400:     }
 3401:     unless ($startdis) { $startdis=0; }
 3402: 
 3403:     if ($env{'form.firstview'}) {
 3404: 	$startdis=0;
 3405:     }
 3406:     if ($env{'form.lastview'}) {
 3407: 	$startdis=-1;
 3408:     }
 3409:     if ($env{'form.prevview'}) {
 3410: 	$startdis--;
 3411:     }
 3412:     if ($env{'form.nextview'}) {
 3413: 	$startdis++;
 3414:     }
 3415:     my $postedstartdis=$startdis+1;
 3416:     $sqs.='&amp;startdis='.$postedstartdis;
 3417: 
 3418: # --------------------------------------------------------------- Render Output
 3419: 
 3420:     if ($env{'form.display'}) {
 3421: 	&displaymessage($r,$env{'form.display'},$folder,$msgstatus);
 3422:     } elsif ($env{'form.replyto'}) {
 3423: 	&compout($r,'',$env{'form.replyto'},undef,undef,$folder,$dismode);
 3424:     } elsif ($env{'form.confirm'}) {
 3425: 	&printheader($r,'','Confirmed Receipt');
 3426: 	my $replying = 0;
 3427: 	foreach my $envkey (keys(%env)) {
 3428: 	    if ($envkey=~/^form\.(rep)?rec\_(.*)$/) {
 3429:                 my $repchk = $1;
 3430:        		my $msgid = $2;
 3431: 		$r->print('<b>'.&mt('Confirming Receipt').':</b> ');
 3432: 		my $result = &Apache::lonmsg::user_crit_received($msgid);
 3433:                 if ($result =~ /trans:\s+ok/) {
 3434:                     &statuschange($msgid,'read');
 3435:                 }
 3436:                 $r->print($result.'<br />');
 3437:                 if ($repchk eq 'rep') {
 3438: 		    &compout($r,'','','',$msgid);
 3439: 		    $replying = 1;
 3440:                 }
 3441: 	    }
 3442: 	}
 3443: 	if (!$replying) {
 3444: 	    &discrit($r);
 3445: 	}
 3446:     } elsif ($env{'form.critical'}) {
 3447: 	&printheader($r,'','Displaying Critical Messages');
 3448: 	&discrit($r);
 3449:     } elsif ($env{'form.forward'}) {
 3450: 	&compout($r,$env{'form.forward'},undef,undef,undef,$folder);
 3451:     } elsif ($env{'form.markdel'}) {
 3452: 	&printheader($r,'','Deleted Message');
 3453: 	my ($result,$msg) = 
 3454: 	    &statuschange($env{'form.markdel'},'deleted',$folder);
 3455: 	if (!$result) {
 3456:             my $message = &Apache::lonhtmlcommon::confirm_success(&mt('Failed to delete the message.'),1);
 3457:             $message .= '<p class="LC_error" style="font-size: inherit;">'.$msg.'</p>';
 3458:             $message = &Apache::loncommon::confirmwrapper($message);
 3459:             $r->print($message);
 3460: 	}
 3461: 	&Apache::loncommunicate::menu($r);
 3462: 	&disall($r,($folder?$folder:$dismode),$msgstatus);
 3463:     } elsif ($env{'form.markedaction'} eq 'markedforward') {
 3464:         my $total = 0;
 3465:         my @to_forward = &Apache::loncommon::get_env_multiple('form.delmark');
 3466:         foreach my $msgid (@to_forward) {
 3467:             &statuschange(&unescape($msgid),'forwarded',$folder);
 3468:             $total ++;
 3469:         }
 3470:         if ($total > 0) {
 3471:             &compout($r,undef,undef,undef,undef,$folder,$dismode,$total);
 3472:         }
 3473:     } elsif ($env{'form.markedaction'} eq 'markedread') {
 3474:         my $total = 0;
 3475:         my @to_markread = &Apache::loncommon::get_env_multiple('form.delmark');
 3476:         foreach my $msgid (@to_markread) {
 3477:             &statuschange(&unescape($msgid),'read',$folder);
 3478:             $total ++;
 3479:         }
 3480:         &printheader($r,'','Marked Messages Read');
 3481:         my $message = &Apache::lonhtmlcommon::confirm_success(&mt('Marked [quant,_1,message] read',$total));
 3482:         $message = &Apache::loncommon::confirmwrapper($message);
 3483:         $r->print($message);
 3484:       # $r->print('<p>');
 3485:         &Apache::loncommunicate::menu($r);
 3486:         &disall($r,($folder?$folder:$dismode),$msgstatus);
 3487:     } elsif ($env{'form.markedaction'} eq 'markedunread') {
 3488:         my $total = 0;
 3489:         my @to_markunread = &Apache::loncommon::get_env_multiple('form.delmark');
 3490:         foreach my $msgid (@to_markunread) {
 3491:             &statuschange(&unescape($msgid),'new',$folder);
 3492:             $total ++;
 3493:         }
 3494:         &printheader($r,'','Marked Messages Unread');
 3495:         my $message = &Apache::lonhtmlcommon::confirm_success(&mt('Marked [quant,_1,message] unread',$total));
 3496:         $message = &Apache::loncommon::confirmwrapper($message);
 3497:         $r->print($message);
 3498:       # $r->print('<p>');
 3499:         &Apache::loncommunicate::menu($r);
 3500:         &disall($r,($folder?$folder:$dismode),$msgstatus);
 3501:     } elsif ($env{'form.markedaction'} eq 'markedmove') {
 3502:         my $destfolder = $env{'form.movetofolder'};
 3503:         my %gotfolders = &Apache::lonmsg::get_user_folders();
 3504:         &printheader($r,'','Moved Messages');
 3505:         if (!defined($gotfolders{$destfolder})) {
 3506:             $r->print(&mt('Destination folder [_1] is not a valid folder',
 3507:                           '<span class="LC_filename">'.$destfolder.'</span>'));
 3508:         } else {
 3509: 	    my ($total,$failed,@failed_msg)=(0,0);
 3510:             my @to_move = &Apache::loncommon::get_env_multiple('form.delmark');
 3511:             foreach my $msgid (@to_move) {
 3512: 	        my ($result,$msg) = &movemsg(&unescape($msgid),$folder,
 3513: 			                     $env{'form.movetofolder'});
 3514: 	        if ($result) {
 3515: 		    $total++;
 3516: 	        } else {
 3517: 		    $failed++;
 3518: 		    push(@failed_msg,$msg);
 3519: 	        }
 3520: 	    }
 3521:             my $message = '';
 3522:             if ($failed) {
 3523:                 $message .= &Apache::lonhtmlcommon::confirm_success(&mt('Failed to move [quant,_1,message]',$failed),1);
 3524:                 $message .= '<p class="LC_error" style="font-size: inherit;">'.
 3525: 		            join("</p>\n<p class=\"LC_error\" style=\"font-size: inherit;\">",@failed_msg).
 3526: 		            "</p>\n";
 3527:             }
 3528:             $message .= &Apache::lonhtmlcommon::confirm_success(&mt('Moved [quant,_1,message]',$total));
 3529:             $message = &Apache::loncommon::confirmwrapper($message);
 3530:             $r->print($message);
 3531:           # $r->print('<p>');
 3532:         }
 3533: 	&Apache::loncommunicate::menu($r);
 3534: 	&disall($r,($folder?$folder:$dismode),$msgstatus);
 3535:     } elsif ($env{'form.markedaction'} eq 'markeddel') {
 3536: 	my ($total,$failed,@failed_msg)=(0,0);
 3537:         my @to_delete = &Apache::loncommon::get_env_multiple('form.delmark');
 3538:         foreach my $msgid (@to_delete) {
 3539: 	    my ($result,$msg) = &statuschange(&unescape($msgid),'deleted', 
 3540: 				              $folder);
 3541: 	    if ($result) {
 3542: 	        $total++;
 3543: 	    } else {
 3544: 	        $failed++;
 3545: 		push(@failed_msg,$msg);
 3546: 	    }
 3547: 	}
 3548: 	&printheader($r,'','Deleted Messages');
 3549:         my $message = '';
 3550: 	if ($failed) {
 3551:             $message .= &Apache::lonhtmlcommon::confirm_success(&mt('Failed to delete [quant,_1,message]',$failed),1);
 3552:             $message .= '<p class="LC_error" style="font-size: inherit;">'.
 3553: 		      join("</p>\n<p class=\"LC_error\" style=\"font-size: inherit;\">",@failed_msg).
 3554: 		      "</p>\n";
 3555: 	}
 3556:         $message .= &Apache::lonhtmlcommon::confirm_success(&mt('Deleted [quant,_1,message]',$total));
 3557:         $message = &Apache::loncommon::confirmwrapper($message);
 3558:         $r->print($message);
 3559:       # $r->print('<p>');
 3560: 	&Apache::loncommunicate::menu($r);
 3561: 	&disall($r,($folder?$folder:$dismode),$msgstatus);
 3562:     } elsif ($env{'form.markunread'}) {
 3563: 	&printheader($r,'','Marked Message as Unread');
 3564: 	&statuschange($env{'form.markunread'},'new');
 3565: 	&Apache::loncommunicate::menu($r);
 3566: 	&disall($r,($folder?$folder:$dismode),$msgstatus);
 3567:     } elsif ($env{'form.compose'}) {
 3568: 	&compout($r,'','',$env{'form.compose'});
 3569:     } elsif ($env{'form.recordftf'}) {
 3570: 	&facetoface($r,$env{'form.recordftf'});
 3571:     } elsif ($env{'form.block'}) {
 3572:         &examblock($r,$env{'form.block'});
 3573:     } elsif ($env{'form.sendmail'}) {
 3574:         if ($env{'form.multiforward'}) {
 3575:             &printheader($r,'','Messages being sent.');
 3576:             my $fixed_subj = $env{'form.subject'};
 3577:             my $suffix=&Apache::lonmsg::foldersuffix($folder);
 3578:             my (%sendresult,%forwardok,%forwardfail,$fwdcount);
 3579:             my @to_forward = &Apache::loncommon::get_env_multiple('form.delmark');
 3580:             foreach my $item (@to_forward) {
 3581:                 my $msgid=&unescape($item);
 3582:                 my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
 3583:                 my %content=&Apache::lonmsg::unpackagemsg($message{$msgid},1,1);
 3584:                 if ($env{'form.showorigsubj'}) {
 3585:                     $env{'form.subject'} = $fixed_subj.$content{'subject'};
 3586:                 } else {
 3587:                     $env{'form.subject'} = '';
 3588:                 }
 3589:                 my $uname = $content{'sendername'};
 3590:                 my $udom = $content{'senderdomain'};
 3591:                 &statuschange($msgid,'forwarded',$folder);
 3592:                 if ($env{'form.showorigsender'}) {
 3593:                     $env{'form.message'} = $env{'form.msgheader'}.' '.
 3594:                         &Apache::loncommon::plainname($uname,$udom).' ('.
 3595:                                            $uname.':'.$udom.')';
 3596:                 }
 3597:                 $env{'form.message'}.="\n\n-- Forwarded message --\n\n".
 3598:                                       $content{'message'};
 3599:                 $env{'form.attachmenturl'} = $content{'attachmenturl'};
 3600:                 $env{'form.multiforwid'} = $item;
 3601:                 $fwdcount ++;
 3602:                 $r->print($fwdcount.': '); 
 3603:                 $sendresult{$msgid} = &sendoffmail($r,$folder);
 3604:                 $r->print('<br />');
 3605:             }
 3606:             foreach my $key (keys(%sendresult)) {
 3607:                 if ($sendresult{$key} =~/^(\s*(?:ok|con_delayed)\s*)*$/) {
 3608:                     $forwardok{$key} = $sendresult{$key};
 3609:                 } else {
 3610:                     $forwardfail{$key} = $sendresult{$key}; 
 3611:                 }
 3612:             }
 3613:             if (keys(%forwardok) > 0) {
 3614:                 my $count = keys(%forwardok);
 3615:                 my $message = &Apache::lonhtmlcommon::confirm_success(&mt('[quant,_1,message] forwarded.',$count));
 3616:                 $message = &Apache::loncommon::confirmwrapper($message);
 3617:                 $r->print($message);
 3618:             }
 3619:             if (keys(%forwardfail) > 0) {
 3620:                 my $count = keys(%forwardfail);
 3621:                 my $message = &Apache::lonhtmlcommon::confirm_success(&mt('Could not forward [quant,_1,message].',$count),1);
 3622:                 foreach my $key (keys(%forwardfail)) {
 3623:                     $message .= '<br />'.&mt('Could not deliver forwarded message.').'</span> '.
 3624:                                 &mt('The recipient addresses may need to be corrected').' ('.$forwardfail{$key}.')';
 3625:                 }
 3626:                 $message = &Apache::loncommon::confirmwrapper($message);
 3627:                 $r->print($message);
 3628:             }
 3629:             &Apache::loncommunicate::menu($r);
 3630:         } else {
 3631: 	    &sendoffmail($r,$folder);
 3632:         }
 3633: 	if ($env{'form.storebasecomment'}) {
 3634: 	    &storecomment($r);
 3635:         }
 3636: 	if (($env{'form.rsspost'}) && ($env{'request.course.id'})) {
 3637: 	        &Apache::lonrss::addentry($env{'course.'.$env{'request.course.id'}.'.num'},
 3638: 				      $env{'course.'.$env{'request.course.id'}.'.domain'},
 3639: 				      'Course_Announcements',
 3640: 				      $env{'form.subject'},
 3641: 				      $env{'form.message'},'/adm/communicate','public');
 3642: 	}
 3643: 	if ((!exists($env{'form.group'})) && (!$env{'form.displayedcrit'})) {
 3644: 	    &disall($r,($folder?$folder:$dismode),$msgstatus);
 3645: 	}
 3646:     } elsif ($env{'form.newfolder'}) {
 3647: 	&printheader($r,'','New Folder');
 3648:         my $showfolder = $env{'form.newfolder'};
 3649: 	my ($makeresult,$warning) = &makefolder($env{'form.newfolder'});
 3650:         if ($makeresult eq 'ok') {
 3651:             my $message = &Apache::lonhtmlcommon::confirm_success(&mt('Folder "[_1]" created.',$showfolder));
 3652:             $message = &Apache::loncommon::confirmwrapper($message);
 3653:             $r->print($message);
 3654:         } else {
 3655:             my $message = &Apache::lonhtmlcommon::confirm_success(&mt('Creation failed.').' '.$makeresult.'<br />'.$warning,1);
 3656:             $message = &Apache::loncommon::confirmwrapper($message);
 3657:             $r->print($message);
 3658:             $showfolder = $folder;
 3659:         }
 3660:         &Apache::loncommunicate::menu($r);
 3661: 	&disall($r,$showfolder,$msgstatus);
 3662:     } elsif ($env{'form.showcommentbaseurl'}) {
 3663: 	&storedcommentlisting($r);
 3664:     } elsif ($env{'form.folderaction'} eq 'delete') {
 3665:         &printheader($r,'','Deleted Folder');
 3666:         my $showfolder = '';
 3667:         my $delresult = &deletefolder($folder);
 3668:         if ($delresult eq 'ok') {
 3669:             my $message = &Apache::lonhtmlcommon::confirm_success(&mt('Folder "[_1]" deleted.',$folder));
 3670:             $message = &Apache::loncommon::confirmwrapper($message);
 3671:             $r->print($message);
 3672:             $env{'form.folder'} = '';
 3673:         } else {
 3674:             my $message = &Apache::lonhtmlcommon::confirm_success(&mt('Deletion failed.').' '.$delresult,1);
 3675:             $message = &Apache::loncommon::confirmwrapper($message);
 3676:             $r->print($message);
 3677:             $showfolder = $folder;
 3678:         }
 3679:         &Apache::loncommunicate::menu($r);
 3680:         &disall($r,$showfolder,$msgstatus);
 3681:     } elsif ($env{'form.folderaction'} eq 'rename') {
 3682:         &printheader($r,'','Renamed Folder');
 3683:         my $showfolder = $env{'form.renamed'};
 3684:         my $renresult = &renamefolder($folder);
 3685:         if ($renresult eq 'ok') {
 3686:             my $message = &Apache::lonhtmlcommon::confirm_success(&mt('Folder "[_1]" renamed to "[_2]".',$folder,$showfolder));
 3687:             $message = &Apache::loncommon::confirmwrapper($message);
 3688:             $r->print($message);
 3689:         } else {
 3690:             my $message = &Apache::lonhtmlcommon::confirm_success(&mt('Renaming failed.').' '.$renresult,1);
 3691:             $message = &Apache::loncommon::confirmwrapper($message);
 3692:             $r->print($message);
 3693:             $showfolder = $folder;
 3694:         }
 3695:         &Apache::loncommunicate::menu($r);
 3696:         &disall($r,$showfolder,$msgstatus);
 3697:     } else {
 3698: 	&printheader($r,'','Display All Messages');
 3699: 	&Apache::loncommunicate::menu($r);
 3700: 	&disall($r,($folder?$folder:$dismode),$msgstatus);
 3701:     }
 3702:     $r->print(&Apache::loncommon::end_page());
 3703:     return OK;
 3704: }
 3705: # ================================================= Main program, reset counter
 3706: 
 3707: =pod
 3708: 
 3709: =cut
 3710: 
 3711: 1; 
 3712: 
 3713: __END__
 3714: 

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