File:  [LON-CAPA] / loncom / interface / lonmsgdisplay.pm
Revision 1.65: download - view: text, annotated - select for diffs
Mon Jan 22 21:51:05 2007 UTC (17 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_3_X, version_2_3_2, HEAD
If there are blocked messages display information about them when there are no other messages in the folder which pass the display filter.

When a folder is deleted, set the $env value for the "folder" form element to '', otherwise "Empty Folder" will be reported for the INBOX, even if that is not true.

    1: # The LearningOnline Network with CAPA
    2: # Routines for messaging display
    3: #
    4: # $Id: lonmsgdisplay.pm,v 1.65 2007/01/22 21:51:05 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::lonmsg: supports internal messaging
   37: 
   38: =head1 SYNOPSIS
   39: 
   40: lonmsg provides routines for sending messages, receiving messages, and
   41: a handler to allow users to read, send, and delete messages.
   42: 
   43: =head1 OVERVIEW
   44: 
   45: =head2 Messaging Overview
   46: 
   47: X<messages>LON-CAPA provides an internal messaging system similar to
   48: email, but customized for LON-CAPA's usage. LON-CAPA implements its
   49: own messaging system, rather then building on top of email, because of
   50: the features LON-CAPA messages can offer that conventional e-mail can
   51: not:
   52: 
   53: =over 4
   54: 
   55: =item * B<Critical messages>: A message the recipient B<must>
   56: acknowlegde receipt of before they are allowed to continue using the
   57: system, preventing a user from claiming they never got a message
   58: 
   59: =item * B<Receipts>: LON-CAPA can reliably send reciepts informing the
   60: sender that it has been read; again, useful for preventing students
   61: from claiming they did not see a message. (While conventional e-mail
   62: has some reciept support, it's sporadic, e-mail client-specific, and
   63: generally the receiver can opt to not send one, making it useless in
   64: this case.)
   65: 
   66: =item * B<Context>: LON-CAPA knows about the sender, such as where
   67: they are in a course. When a student mails an instructor asking for
   68: help on the problem, the instructor receives not just the student's
   69: question, but all submissions the student has made up to that point,
   70: the user's rendering of the problem, and the complete view the student
   71: saw of the resource, including discussion up to that point. Finally,
   72: the instructor is reading all of this inside of LON-CAPA, not their
   73: email program, so they have full access to LON-CAPA's grading
   74: interface, or other features they may wish to use in response to the
   75: student's query.
   76: 
   77: =item * B<Blocking>: LON-CAPA can block selected communication 
   78: features for students during an online exam. A course coordinator or
   79: instructor can set an open and close date/time for scheduled online
   80: exams in a course. If a user uses the LON-CAPA internal messaging 
   81: system to display e-mails during the scheduled blocking event,  
   82: display of all e-mail sent during the blocking period will be 
   83: suppressed, and a message of explanation, including details of the 
   84: currently active blocking periods will be displayed instead. A user 
   85: who has a course coordinator or instructor role in a course will be
   86: unaffected by any blocking periods for the course, unless the user
   87: also has a student role in the course, AND has selected the student role.
   88: 
   89: =back
   90: 
   91: Users can ask LON-CAPA to forward messages to conventional e-mail
   92: addresses on their B<PREF> screen, but generally, LON-CAPA messages
   93: are much more useful than traditional email can be made to be, even
   94: with HTML support.
   95: 
   96: Right now, this document will cover just how to send a message, since
   97: it is likely you will not need to programmatically read messages,
   98: since lonmsg already implements that functionality.
   99: 
  100: The routines used to package messages and unpackage messages are not
  101: only used by lonmsg when creating/extracting messages for LON-CAPA's
  102: internal messaging system, but also by lonnotify.pm which is available
  103: for use by Domain Coordinators to broadcast standard e-mail to specified
  104: users in their domain.  The XML packaging used in the two cases is very
  105: similar.  The differences are the use of <recuser>$uname</recuser> and 
  106: <recdomain>$udom</recdomain> in stored internal messages, compared 
  107: with <recipient username="$uname:$udom">$email</recipient> in stored
  108: Domain Coordinator e-mail for the storage of information about 
  109: recipients of the message/e-mail.
  110: 
  111: =head1 FUNCTIONS
  112: 
  113: =over 4
  114: 
  115: =cut
  116: 
  117: use strict;
  118: use Apache::lonnet;
  119: use HTML::TokeParser();
  120: use Apache::Constants qw(:common);
  121: use Apache::loncommon();
  122: use Apache::lontexconvert();
  123: use HTML::Entities();
  124: use Apache::lonlocal;
  125: use Apache::loncommunicate;
  126: use Apache::lonfeedback;
  127: use Apache::lonrss();
  128: use Apache::lonselstudent();
  129: use lib '/home/httpd/lib/perl/';
  130: use LONCAPA;
  131: 
  132: # Querystring component with sorting type
  133: my $sqs;
  134: my $startdis;
  135: 
  136: # ============================================================ List all folders
  137: 
  138: sub folderlist {
  139:     my ($folder,$msgstatus) = @_;
  140:     my %lt = &Apache::lonlocal::texthash(
  141:                 actn => 'Action',
  142:                 fold => 'Folder',
  143:                 show => 'Show',
  144:                 status => 'Message Status',
  145:                 go   => 'Go',
  146:                 nnff => 'New Name for Folder',
  147:                 newn => 'New Name',
  148:                 thfm => 'The folder may not be renamed',
  149:                 fmnb => 'folder may not be renamed as it is a folder provided by the system.',
  150:                 asth => 'as this name is already in use for a system-provided or user-defined folder.',
  151:                 the => 'The',
  152:                 tnfm => 'The new folder may not be named',
  153: 
  154:     );
  155: 
  156:     my %actions = &Apache::lonlocal::texthash(
  157:                                 view => 'View Folder',
  158:                                 rename => 'Rename Folder',
  159:                                 delete => 'Delete Folder',
  160:     );
  161:     $actions{'select_form_order'} = ['view','rename','delete'];
  162: 
  163:     my %statushash = &get_msgstatus_types();
  164: 
  165:     $statushash{'select_form_order'} = ['','new','read','replied','forwarded'];
  166: 
  167:     my %permfolders = &get_permanent_folders();
  168:     my $permlist = join("','",sort(keys(%permfolders)));
  169:     my ($permlistkeys,$permlistvals);
  170:     foreach my $key (sort(keys(%permfolders))) {
  171:         $permlistvals .= $permfolders{$key}."','";
  172:         $permlistkeys .= $key."','";
  173:     }
  174:     $permlistvals =~ s/','$//;
  175:     $permlistkeys =~ s/','$//;
  176:     my %gotfolders = &Apache::lonmsg::get_user_folders();
  177:     my %userfolders;
  178: 
  179:     foreach my $key (keys(%gotfolders)) {
  180:         $key =~ s/(['"])/\$1/g; #' stupid emacs
  181:         $userfolders{$key} = $key;
  182:     }
  183:     my @userorder = sort(keys(%userfolders));
  184:     my %formhash = (%permfolders,%userfolders);
  185:     my $folderlist = join("','",@userorder);
  186:     $folderlist .= "','".$permlistvals;
  187: 
  188:     $formhash{'select_form_order'} = ['','critical',@userorder,'sent','trash'];
  189:     my $output = qq|<script type="text/javascript">
  190: function folder_choice(targetform,caller) {
  191:     var permfolders_keys = new Array('$permlistkeys');
  192:     var permfolders_vals = new Array('$permlistvals');
  193:     var allfolders = new Array('$folderlist');
  194:     if (caller == 'change') {
  195:         if (targetform.folderaction.options[targetform.folderaction.selectedIndex].value == 'rename') {
  196:             for (var i=0; i<permfolders_keys.length; i++) {
  197:                 if (permfolders_keys[i] == targetform.folder.value) {
  198:                     alert("$lt{'the'} '"+permfolders_vals[i]+"' $lt{'fmnb'}");
  199:                     return;
  200:                 }
  201:             }
  202:             var foldername=prompt('$lt{'nnff'}','$lt{'newn'}');
  203:             if (foldername) {
  204:                 targetform.renamed.value=foldername;
  205:                 for (var i=0; i<allfolders.length; i++) {
  206:                     if (allfolders[i] == foldername) {
  207:                         alert("$lt{'thfm'} '"+foldername+"' $lt{'asth'}");
  208:                         return;
  209:                     }
  210:                 }
  211:                 targetform.submit();
  212:             }
  213:         }
  214:         else {
  215:             targetform.submit();
  216:         }
  217:     }
  218:     if (caller == 'new') {
  219:         var newname=targetform.newfolder.value;
  220:         if (newname) {
  221:             for (var i=0; i<allfolders.length; i++) {
  222:                 if (allfolders[i] == newname) {
  223:                     alert("$lt{'tnfm'} '"+newname+"' $lt{'asth'}");
  224:                     return;
  225:                 }
  226:             }
  227:             targetform.submit();
  228:         }
  229:     }
  230: }
  231: </script>|;
  232:     my %show = ('select_form_order' => [10,20,50,100,200],
  233: 		map {$_=>$_} (10,20,50,100,200));
  234: 		
  235: 		   
  236:     $output .= '
  237: <form method="post" action="/adm/email" name="folderlist">
  238: <table border="0" cellspacing="2" cellpadding="2">
  239:  <tr>
  240:   <td align="left">
  241:    <table border="0" cellspacing="2" cellpadding="2">
  242:     <tr>
  243:      <td align="center"><b>'.$lt{'fold'}.'</b><br />'."\n".
  244:          &Apache::loncommon::select_form($folder,'folder',%formhash).'
  245:      </td>
  246:      <td align="center"><b>'.$lt{'show'}.'</b><br />'."\n".
  247:          &Apache::loncommon::select_form($env{'form.interdis'},'interdis',
  248: 					 %show).'
  249:      </td>
  250:      <td align="center"><b>'.$lt{'status'}.'</b><br />'."\n".
  251:        &Apache::loncommon::select_form($msgstatus,'msgstatus',%statushash).'
  252:      </td>
  253:      <td align="center"><b>'.$lt{'actn'}.'</b><br />'.
  254:          &Apache::loncommon::select_form('view','folderaction',%actions).'
  255:      </td><td><br />'.
  256:     '<input type="button" value="'.$lt{'go'}.'" onClick="javascript:folder_choice(this.form,'."'change'".');" />
  257:      </td>
  258:     </tr>
  259:    </table>
  260:   </td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
  261:   <td align="right">
  262:    <table><tr><td><br />
  263:     <input type="button" value="'.&mt('Make New Folder').
  264:     '" onClick="javascript:folder_choice(this.form,'."'new'".');" /></td>'.
  265:     '<td align="center"><b>'.&mt('New Folder').'</b><br />'.
  266:     '<input type="text" size="15" name="newfolder" value="" />
  267:     </td></tr></table>
  268:   </td>
  269:  </tr>
  270: </table>'."\n".
  271:     '<input type="hidden" name="sortedby" value="'.$env{'form.sortedby'}.'" />'.
  272:     '<input type="hidden" name="renamed" value="" />'.
  273:         ($folder=~/^critical/?'</form>':'');
  274:     return $output;
  275: }
  276: 
  277: sub get_permanent_folders {
  278:     my %permfolders = 
  279: 	&Apache::lonlocal::texthash(''         => 'INBOX',
  280: 				    'trash'    => 'TRASH',
  281: 				    'critical' => 'Critical',
  282: 				    'sent'     => 'Sent Messages',
  283: 				    );
  284:     return %permfolders;
  285: }
  286: 
  287: sub get_msgstatus_types {
  288:     my %statushash = &Apache::lonlocal::texthash(
  289:                                 '' => 'Any',
  290:                                 new => 'Unread',
  291:                                 read => 'Read',
  292:                                 replied => 'Replied to',
  293:                                 forwarded => 'Forwarded',
  294:     );
  295:     return %statushash;
  296: }
  297: 
  298: sub scrollbuttons {
  299:     my ($start,$maxdis,$first,$finish,$total,$msgstatus)=@_;
  300:     unless ($total>0) { return ''; }
  301:     $start++; $maxdis++;$first++;$finish++;
  302: 
  303:     my %statushash = &get_msgstatus_types();
  304:     my $status;
  305:     if ($msgstatus eq '') {
  306:         $status = &mt('All');
  307:     } else {
  308:         $status = $statushash{$msgstatus};
  309:     }
  310:     return
  311:    '<b>'.&mt('Page').'</b>: '. 
  312:    '<input type="submit" name="firstview" value="'.&mt('First').'" />'.
  313:    '<input type="submit" name="prevview" value="'.&mt('Previous').'" />'.
  314:    '<input type="text" size="5" name="startdis" value="'.$start.'" onChange="this.form.submit()" /> of '.$maxdis.
  315:    '<input type="submit" name="nextview" value="'.&mt('Next').'" />'.
  316:    '<input type="submit" name="lastview" value="'.&mt('Last').'" /><br />'.
  317:    &mt('<b>[_1] messages</b>: showing messages [_2] through [_3] of [_4].',$status,$first,$finish,$total).'</form>';
  318: }
  319: # =============================================================== Status Change
  320: 
  321: sub statuschange {
  322:     my ($msgid,$newstatus,$folder)=@_;
  323:     my $suffix=&Apache::lonmsg::foldersuffix($folder);
  324:     my %status=&Apache::lonnet::get('email_status'.$suffix,[$msgid]);
  325:     if ($status{$msgid}=~/^error\:/) { $status{$msgid}=''; }
  326:     unless ($status{$msgid}) { $status{$msgid}='new'; }
  327:     unless (($status{$msgid} eq 'replied') || 
  328:             ($status{$msgid} eq 'forwarded')) {
  329: 	&Apache::lonnet::put('email_status'.$suffix,{$msgid => $newstatus});
  330:     }
  331:     if (($newstatus eq 'deleted') || ($newstatus eq 'new')) {
  332: 	&Apache::lonnet::put('email_status'.$suffix,{$msgid => $newstatus});
  333:     }
  334:     if ($newstatus eq 'deleted') {
  335: 	return &movemsg($msgid,$folder,'trash');
  336:     }
  337:     return ;
  338: }
  339: 
  340: # ============================================================= Make new folder
  341: 
  342: sub makefolder {
  343:     my ($newfolder) = @_;
  344:     my %permfolders = &get_permanent_folders();
  345:     my %userfolders = &Apache::lonmsg::get_user_folders();
  346:     my ($outcome,$warning);
  347:     if (defined($userfolders{$newfolder})) {
  348:         return &mt('The folder name: "[_1]" is already in use for an existing folder.',$newfolder);
  349:     }
  350:     foreach my $perm (keys(%permfolders)) {
  351:         if ($permfolders{$perm} eq $newfolder) {
  352:             return &mt('The folder name: "[_1]" is already used for one of the folders automatically generated by the system.',$newfolder);
  353:         }
  354:     } 
  355:     if (&get_msgfolder_lock() eq 'ok') {
  356:         my %counter_hash = &Apache::lonnet::get('email_folders',["\0".'idcount']);
  357:         my $lastcount = $counter_hash{"\0".'idcount'};
  358:         my $folder_id = $lastcount + 1;
  359:         while (defined($userfolders{$folder_id})) {
  360:             $folder_id ++;
  361:         }
  362:         my %folderinfo = ( id      => $folder_id,
  363:                            created => time, );
  364:         $outcome =  
  365: 	    &Apache::lonnet::put('email_folders',{$newfolder => \%folderinfo,
  366: 						  "\0".'idcount' => $folder_id});
  367:         my $releaseresult = &release_msgfolder_lock();
  368:         if ($releaseresult ne 'ok') {
  369:             $warning = $releaseresult;
  370:         }
  371:     } else {
  372:         $outcome = 
  373: 	    &mt('Error - could not obtain lock on email folders record.');
  374:     }
  375:     return ($outcome,$warning);
  376: }
  377: 
  378: # ============================================================= Delete folder
  379: 
  380: sub deletefolder {
  381:     my ($folder)=@_;
  382:     my %permfolders = &get_permanent_folders();
  383:     if (defined($permfolders{$folder})) {
  384:         return &mt('The folder "[_1]" may not be deleted',$folder); 
  385:     }
  386:     my %userfolders = &Apache::lonmsg::get_user_folders();
  387:     if (!defined($userfolders{$folder})) {
  388:         return &mt('The folder "[_1]" does not exist so deletion is not required.',
  389:                    $folder);
  390:     }
  391:     # check folder is empty;
  392:     my $suffix=&Apache::lonmsg::foldersuffix($folder);
  393:     my @messages = &Apache::lonnet::getkeys('nohist_email'.$suffix);
  394:     if (@messages > 0) {
  395:         return &mt('The folder "[_1]" contains messages so it may not be deleted.',$folder).
  396:                '<br />'.
  397:                &mt('Delete or move the messages to a different folder first.');
  398:     }
  399:     my $delresult = &Apache::lonnet::del('email_folders',[$folder]);
  400:     return $delresult;
  401: }
  402: 
  403: sub renamefolder {
  404:     my ($folder) = @_;
  405:     my $newname = $env{'form.renamed'};
  406:     my %permfolders = &get_permanent_folders();
  407:     if ($env{'form.renamed'} eq '') {
  408:         return &mt('The folder "[_1]" may not be renamed to "[_2]" as the new name you requested is an invalid name.',$folder,$newname);
  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 $result;
  520:     my ($course_personnel,
  521: 	$current_members,
  522: 	$expired_members,
  523: 	$future_members) = 
  524: 	    &Apache::lonselstudent::get_people_in_class($env{'request.course.sec'});
  525:     unshift @$current_members, (@$course_personnel);
  526:     my %defaultUsers;
  527:     
  528:     $result .= '<input type="hidden" name="sendmode" value="group" />'."\n";
  529: 
  530:     $result .= &Apache::lonselstudent::render_student_list($current_members,
  531: 							   "compemail",
  532: 							   "current",
  533: 							   \%defaultUsers,
  534: 							   1,"selectedusers",1);
  535: 
  536:     $result .= &Apache::lonselstudent::render_student_list($expired_members,
  537: 							   "compemail",
  538: 							   "expired",
  539: 							   \%defaultUsers,
  540: 							   1, "selectedusers",0);
  541:     $result .= &Apache::lonselstudent::render_student_list($future_members,
  542: 							   "compemail",
  543: 							   "future",
  544: 							   \%defaultUsers,
  545: 							   1, "selectedusers", 0);
  546:     return $result;
  547: }
  548: 
  549: sub disgroup {
  550:     my ($cdom,$cnum,$group,$viewgrps,$editgrps) = @_;
  551:     my $result;
  552:     #  Needs to be in a course
  553:     if (!($env{'request.course.fn'})) {
  554:         $result = &mt('Error: you must have a course role selected to be able to send a broadcast message to a group in the course.');
  555:         return $result;
  556:     }
  557:     if ($cdom eq '' || $cnum eq '') {
  558:         $result = &mt('Error: could not determine domain or number of course');
  559:         return $result;
  560:     }
  561:     my ($memberinfo,$numitems) =
  562:                  &Apache::longroup::group_memberlist($cdom,$cnum,$group,{},[]);
  563:     my @statustypes = ('active');
  564:     if ($viewgrps || $editgrps) {
  565:         push(@statustypes,('future','previous'));
  566:     }
  567:     if (keys(%{$memberinfo}) == 0) {
  568:         $result = &mt('As this group has no members, there are no '.
  569:                       'recipients to select.');
  570:         return $result;
  571:     } else {
  572:         $result = &mt('Select message recipients from the group members listed below.<br />');  
  573:         my %Sortby = (
  574:                          active   => {},
  575:                          previous => {},
  576:                          future   => {},
  577:                      );
  578:         my %lt = &Apache::lonlocal::texthash(
  579:                                      'name'     => 'Name',
  580:                                      'usnm'     => 'Username',
  581:                                      'doma'     => 'Domain',
  582:                                      'active'   => 'Active Members',
  583:                                      'previous' => 'Former Members',
  584:                                      'future'   => 'Future Members',
  585:                                     );
  586:         foreach my $user (sort(keys(%{$memberinfo}))) {
  587:             my $status = $$memberinfo{$user}{status};
  588:             if ($env{'form.'.$status.'.sortby'} eq 'fullname') {
  589:                 push(@{$Sortby{$status}{$$memberinfo{$user}{fullname}}},$user);
  590:             } elsif ($env{'form.'.$status.'.sortby'} eq 'username') {
  591:                 push(@{$Sortby{$status}{$$memberinfo{$user}{uname}}},$user);
  592:             } elsif ($env{'form.'.$status.'.sortby'} eq 'domain') {
  593:                 push(@{$Sortby{$status}{$$memberinfo{$user}{udom}}},$user);
  594:             } else {
  595:                 push(@{$Sortby{$status}{$$memberinfo{$user}{fullname}}},$user);
  596:             }
  597:         }
  598:         $result .= &group_check_uncheck();
  599:         $result .= '<table border="0" cellspacing="8" cellpadding="2">'.
  600:                    '<tr>';
  601:         foreach my $status (@statustypes)  {
  602:             if (ref($numitems) eq 'HASH') {
  603:                 if ((defined($$numitems{$status})) && ($$numitems{$status})) {
  604:                     $result.='<td valign="top">'.
  605:                              '<fieldset><legend><b>'.$lt{$status}.
  606:                              '</b></legend><nobr>'.
  607:                              '<input type="button" value="'.&mt('Check All').'" '.
  608:                              'onclick="javascript:toggleAll('."'".$status."','check'".')" />'.
  609:                              '&nbsp;&nbsp;'.
  610:                              '<input type="button" value="'.&mt('Uncheck All').'" '.
  611:                              'onclick="javascript:toggleAll('."'".$status."','uncheck'".')" />'.
  612:                              '</nobr></fieldset><br />'.
  613:                              &Apache::loncommon::start_data_table().
  614:                              &Apache::loncommon::start_data_table_header_row();
  615:                     $result .= "<th>$lt{'name'}</a></th>".
  616:                                "<th>$lt{'usnm'}</a></th>".
  617:                                "<th>$lt{'doma'}</a></th>".
  618:                     &Apache::loncommon::end_data_table_header_row();
  619:                     foreach my $key (sort(keys(%{$Sortby{$status}}))) {
  620:                         foreach my $user (@{$Sortby{$status}{$key}}) {
  621:                             $result .=
  622:                                 &Apache::loncommon::start_data_table_row().
  623:                                 '<td><input type="checkbox" '.
  624:                                 'name="selectedusers_forminput" value="'.
  625:                                 $user.':'.$status.'" />'.
  626:                                 $$memberinfo{$user}{'fullname'}.'</td>'.
  627:                                 '<td>'.$$memberinfo{$user}{'uname'}.'</td>'.
  628:                                 '<td>'.$$memberinfo{$user}{'udom'}.'</td>'.
  629:                                 &Apache::loncommon::end_data_table_row();
  630:                         }
  631:                     }
  632:                     $result .= &Apache::loncommon::end_data_table();
  633:                 }
  634:             }
  635:             $result .= '</td><td>&nbsp;&nbsp;</td>';
  636:         }
  637:         $result .= '</tr></table>';
  638:     }
  639:     return $result;
  640: }
  641: 
  642: sub group_check_uncheck {
  643:     my $output = qq|
  644: <script type="text/javascript">
  645: function toggleAll(caller,action) {
  646:     var pattern = new RegExp(":"+caller+"\$");
  647:     if (typeof(document.compemail.selectedusers_forminput.length)=="undefined") {
  648:         if (document.compemail.selectedusers_forminput.value.match(pattern)) {
  649:             if (action == 'check') {
  650:                 document.groupmail.selectedusers_forminput.checked = true;
  651:             } else {
  652:                 document.groupmail.selectedusers_forminput.checked = false;
  653:             }
  654:         }
  655:     } else {
  656:         for (var i=0; i<document.compemail.selectedusers_forminput.length; i++) {
  657:             if (document.compemail.selectedusers_forminput[i].value.match(pattern)) {
  658:                 if (action == 'check') {
  659:                     document.compemail.selectedusers_forminput[i].checked = true;
  660:                 } else {
  661:                     document.compemail.selectedusers_forminput[i].checked = false;
  662:                 }
  663:             }
  664:         }
  665:     }
  666: }
  667: </script>
  668:     |;
  669: }
  670: 
  671: sub groupmail_header {
  672:     my ($action,$group,$cdom,$cnum) = @_;
  673:     my ($description,$refarg);
  674:     if (!$cdom || !$cnum) {
  675:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  676:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  677:     }
  678:     if (exists($env{'form.ref'})) {
  679:         $refarg = 'ref='.$env{'form.ref'};
  680:     }
  681:     if (!$group) {
  682:         $group = $env{'form.group'};
  683:     }
  684:     if ($group eq '') {
  685:         return  '';
  686:     } else {
  687:         my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum,$group);
  688:         if (defined($curr_groups{$group})) {
  689:             my %groupinfo =
  690:                     &Apache::longroup::get_group_settings($curr_groups{$group});
  691:             $description = &unescape($groupinfo{'description'});
  692:         }
  693:     }
  694:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  695:     if ($refarg) {
  696:         &Apache::lonhtmlcommon::add_breadcrumb
  697:             ({href=>"/adm/coursegroups",
  698:               text=>"Groups",
  699:               title=>"View course groups"});
  700:     }
  701:     &Apache::lonhtmlcommon::add_breadcrumb
  702:         ({href=>"/adm/$cdom/$cnum/$group/smppg?$refarg",
  703:           text=>"Group: $description",
  704:           title=>"Go to group's home page"},
  705:          {href=>"/adm/email?compose=group&amp;group=".
  706:                 "$env{'form.group'}&amp;$refarg",
  707:           text=>"Send a Message in a Group",
  708:           title=>"Compose Group Email Message"},);
  709:     if ($action eq 'sending') {
  710:             &Apache::lonhtmlcommon::add_breadcrumb
  711:                          ({text=>"Messages being sent.",
  712:                            title=>"Messages sent"},);
  713:     }
  714:     my $groupheader = &Apache::loncommon::start_page('Group Email');
  715:     $groupheader .= &Apache::lonhtmlcommon::breadcrumbs
  716:                 ('Group - '.$env{'form.group'}.' Email');
  717:     return $groupheader;
  718: }
  719: 
  720: sub groupmail_sent {
  721:     my ($group,$cdom,$cnum) = @_;
  722:     my $refarg;
  723:     if (exists($env{'form.ref'})) {
  724:         $refarg = 'ref='.$env{'form.ref'};
  725:     }
  726:     my $output .= '<br /><br /><a href="/adm/email?compose=group&amp;group='.
  727:                   $group.'&amp;'.$refarg.'">'.
  728:                   &mt('Send another group email').'</a>'.'&nbsp;&nbsp;&nbsp;'.
  729:                   '<a href="/adm/'.$cdom.'/'.$cnum.'/'.$group.'/smppg?'.
  730:                   $refarg.'">'. &mt('Return to group page').'</a>';
  731:     return $output;
  732: }
  733: 
  734: # ==================================================== Display Critical Message
  735: 
  736: sub discrit {
  737:     my $r=shift;
  738:     my $header = '<h1><font color="red">'.&mt('Critical Messages').'</font></h1>'.
  739:         '<form action="/adm/email" method="POST">'.
  740:         '<input type="hidden" name="confirm" value="true" />';
  741:     my %what=&Apache::lonnet::dump('critical');
  742:     my $result = '';
  743:     foreach my $key (sort(keys(%what))) {
  744:         my %content=&Apache::lonmsg::unpackagemsg($what{$key});
  745:         next if ($content{'senderdomain'} eq '');
  746:         $result.='<hr />'.&mt('From').': <b>'.
  747: &Apache::loncommon::aboutmewrapper(
  748:  &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).'</b> ('.
  749: $content{'sendername'}.':'.
  750:             $content{'senderdomain'}.') '.$content{'time'}.
  751:             '<br />'.&mt('Subject').': '.$content{'subject'}.
  752:             '<br /><pre>'.
  753:               &Apache::lontexconvert::msgtexconverted($content{'message'}).
  754:             '</pre><small>'.
  755: &mt('You have to confirm that you received this message. After confirmation, this message will be moved to your regular inbox').
  756:             '</small><br />'.
  757:             '<input type="submit" name="rec_'.$key.'" value="'.&mt('Confirm Receipt').'" />'.
  758:             '<input type="submit" name="reprec_'.$key.'" '.
  759:                   'value="'.&mt('Confirm Receipt and Reply').'" />';
  760:     }
  761:     # Check to see if there were any messages.
  762:     if ($result eq '') {
  763:         $result = "<h2>".&mt('You have no critical messages.')."</h2>".
  764: 	    '<a href="/adm/roles">'.&mt('Select a course').'</a><br />'.
  765:             '<a href="/adm/email">'.&mt('Communicate').'</a>';
  766:     } else {
  767:         $r->print($header);
  768:     }
  769:     $r->print($result);
  770:     $r->print('<input type="hidden" name="displayedcrit" value="true" /></form>');
  771: }
  772: 
  773: sub sortedmessages {
  774:     my ($blocked,$startblock,$endblock,$numblocked,$folder,$msgstatus) = @_;
  775:     my $suffix=&Apache::lonmsg::foldersuffix($folder);
  776:     my @messages = &Apache::lonnet::getkeys('nohist_email'.$suffix);
  777:     #unpack the varibles and repack into temp for sorting
  778:     my @temp;
  779:     my %descriptions;
  780:     my %status_cache = 
  781: 	&Apache::lonnet::get('email_status'.&Apache::lonmsg::foldersuffix($folder),\@messages);
  782: 
  783:     my $get_received;
  784:     if ($folder eq 'sent' 
  785: 	&& ($env{'form.sortedby'} =~ m/^(rev)?(user|domain)$/)) {
  786: 	$get_received = 1;
  787:     }
  788: 
  789:     foreach my $msgid (@messages) {
  790: 	my $esc_msgid=&escape($msgid);
  791: 	my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$fromcid,$processid,$symb,$error) =
  792: 	    &Apache::lonmsg::unpackmsgid($esc_msgid,$folder,undef,
  793: 					 \%status_cache);
  794:         next if ($msgstatus ne '' && $msgstatus ne $status);
  795:         my $description = &get_course_desc($fromcid,\%descriptions);
  796: 	my @temp1 = ($sendtime,$shortsubj,$fromname,$fromdomain,$status,
  797: 		     $esc_msgid,$description);
  798: 	if ($get_received) {
  799: 	    my %message = &Apache::lonnet::get('nohist_email'.$suffix,
  800: 					       [$msgid]);
  801: 	    my %content = &Apache::lonmsg::unpackagemsg($message{$msgid});
  802: 	    push(@temp1,$content{'recuser'},$content{'recdomain'});
  803: 	}
  804:         # Check whether message was sent during blocking period.
  805:         if ($sendtime >= $startblock && ($sendtime <= $endblock && $endblock > 0) ) {
  806:             $$blocked{$msgid} = 'ON';
  807:             $$numblocked ++;
  808:         } else { 
  809:             push @temp ,\@temp1;
  810:         }
  811:     }
  812:     #default sort
  813:     @temp = sort  {$a->[0] <=> $b->[0]} @temp;    
  814:     if ($env{'form.sortedby'} eq "date"){
  815:         @temp = sort  {$a->[0] <=> $b->[0]} @temp;    
  816:     }
  817:     if ($env{'form.sortedby'} eq "revdate"){
  818:     	@temp = sort  {$b->[0] <=> $a->[0]} @temp; 
  819:     }
  820:     if ($env{'form.sortedby'} eq "user"){
  821: 	if ($get_received) {
  822: 	    @temp = sort  {lc($a->[7][0]) cmp lc($b->[7][0])} @temp;
  823: 	} else {
  824: 	    @temp = sort  {lc($a->[2])    cmp lc($b->[2])}    @temp;
  825: 	}
  826:     }
  827:     if ($env{'form.sortedby'} eq "revuser"){
  828: 	if ($get_received) {
  829: 	    @temp = sort  {lc($b->[7][0]) cmp lc($a->[7][0])} @temp;
  830: 	} else {
  831: 	    @temp = sort  {lc($b->[2])    cmp lc($a->[2])}    @temp;
  832: 	}
  833:     }
  834:     if ($env{'form.sortedby'} eq "domain"){
  835: 	if ($get_received) {
  836: 	    @temp = sort  {$a->[8][0] cmp $b->[8][0]} @temp;
  837: 	} else {
  838: 	    @temp = sort  {$a->[3]    cmp $b->[3]}    @temp;
  839: 	}
  840:     }
  841:     if ($env{'form.sortedby'} eq "revdomain"){
  842: 	if ($get_received) {
  843: 	    @temp = sort  {$b->[8][0] cmp $a->[8][0]} @temp;
  844: 	} else {
  845: 	    @temp = sort  {$b->[3]    cmp $a->[3]}    @temp;
  846: 	}
  847:     }
  848:     if ($env{'form.sortedby'} eq "subject"){
  849:         @temp = sort  {lc($a->[1]) cmp lc($b->[1])} @temp;
  850:     }
  851:     if ($env{'form.sortedby'} eq "revsubject"){
  852:         @temp = sort  {lc($b->[1]) cmp lc($a->[1])} @temp;
  853:     }
  854:     if ($env{'form.sortedby'} eq "course"){
  855:         @temp = sort  {lc($a->[6]) cmp lc($b->[6])} @temp;
  856:     }
  857:     if ($env{'form.sortedby'} eq "revcourse"){
  858:         @temp = sort  {lc($b->[6]) cmp lc($a->[6])} @temp;
  859:     }
  860:     if ($env{'form.sortedby'} eq "status"){
  861:         @temp = sort  {$a->[4] cmp $b->[4]} @temp;
  862:     }
  863:     if ($env{'form.sortedby'} eq "revstatus"){
  864:         @temp = sort  {$b->[4] cmp $a->[4]} @temp;
  865:     }
  866:     return @temp;
  867: }
  868: 
  869: sub get_course_desc {
  870:     my ($fromcid,$descriptions) = @_;
  871:     my $description;
  872:     if (!$fromcid) {
  873:         return $description;
  874:     } else {
  875:         if (defined($$descriptions{$fromcid})) {
  876:             $description = $$descriptions{$fromcid};
  877:         } else {
  878:             if (defined($env{'course.'.$fromcid.'.description'})) {
  879:                 $description = $env{'course.'.$fromcid.'.description'};
  880:             } else {
  881:                 my %courseinfo=&Apache::lonnet::coursedescription($fromcid);
  882:                 $description = $courseinfo{'description'};
  883:             }
  884:             $$descriptions{$fromcid} = $description;
  885:         }
  886:         return $description;
  887:     }
  888: }
  889: 
  890: # ======================================================== Display all messages
  891: 
  892: sub disall {
  893:     my ($r,$folder,$msgstatus)=@_;
  894:     my %saveable = ('folder'    => 'scalar',
  895: 		    'msgstatus' => 'scalar',
  896: 		    'sortedby'  => 'scalar',
  897: 		    'interdis'  => 'scalar',
  898: 		    );
  899:     &Apache::loncommon::store_settings('user','mail',\%saveable);
  900:     &Apache::loncommon::restore_settings('user','mail',\%saveable);
  901:     $folder    ||= $env{'form.folder'};
  902:     $msgstatus ||= $env{'form.msgstatus'};
  903:     $env{'form.interdis'} ||= 20;
  904: 
  905:     $r->print(&folderlist($folder,$msgstatus));
  906:     if ($folder eq 'critical') {
  907: 	&discrit($r);
  908:     } else {
  909: 	&disfolder($r,$folder,$msgstatus);
  910:     }
  911: }
  912: 
  913: # ============================================================ Display a folder
  914: 
  915: sub disfolder {
  916:     my ($r,$folder,$msgstatus)=@_;
  917:     my %statushash = &get_msgstatus_types();
  918:     my %blocked = ();
  919:     my %setters = ();
  920:     my $numblocked = 0;
  921:     my ($startblock,$endblock) = &Apache::loncommon::blockcheck(\%setters,'com');
  922:     my %lt = &Apache::lonlocal::texthash(
  923:                       sede => 'Select a destination folder to which the messages will be moved.',
  924:                       nome => 'No messages have been selected to apply ths action to.',
  925:                       chec => 'Check the checkbox for at least one message.',  
  926:     );
  927:     my $jscript = &Apache::loncommon::check_uncheck_jscript();
  928:     $r->print(<<ENDDISHEADER);
  929: <script type="text/javascript">
  930:     $jscript
  931: 
  932:     function checkfoldermove() {
  933:         if (document.disall.checkedaction.options[document.disall.checkedaction.selectedIndex].value == 'markedmove') {
  934:             if (document.disall.movetofolder.options[document.disall.movetofolder.selectedIndex].value == "") {
  935:                 alert("$lt{'sede'}");
  936:                 return;
  937:             }
  938:         }
  939:         return; 
  940:     }
  941: 
  942:     function validate_checkedaction() {
  943:         document.disall.markedaction.value = document.disall.checkedaction.options[document.disall.checkedaction.selectedIndex].value;
  944:         if (document.disall.checkedaction.options[document.disall.checkedaction.selectedIndex].value == 'markedmove') {
  945:             if (document.disall.movetofolder.options[document.disall.movetofolder.selectedIndex].value == "") {
  946:                 alert("$lt{'sede'}");
  947:                 return;
  948:             } 
  949:         }
  950:         var checktotal = 0;
  951:         if (document.forms.disall.delmark.length > 0) {
  952:             for (var i=0; i<document.forms.disall.delmark.length; i++) {
  953:                 if (document.forms.disall.delmark[i].checked) {
  954:                     checktotal ++;
  955:                 }
  956:             }
  957:         } else {
  958:             if (document.forms.disall.delmark.checked) {
  959:                 checktotal ++;
  960:             }
  961:         }   
  962:         if (checktotal == 0) {
  963:             alert("$lt{'nome'}\\n$lt{'chec'}");
  964:             return;
  965:         }
  966:         document.disall.submit();
  967:     }
  968: 
  969: </script>
  970: ENDDISHEADER
  971: 
  972:     my $fsqs='&folder='.$folder;
  973:     my @temp=&sortedmessages(\%blocked,$startblock,$endblock,\$numblocked,$folder,$msgstatus);
  974:     my $totalnumber=$#temp+1;
  975:     if ($totalnumber < 1) {
  976:         if ($msgstatus eq '') {
  977: 	    $r->print('<h2>'.&mt('Empty Folder').'</h2>');
  978:         } elsif ($msgstatus eq 'replied') {
  979:             $r->print('<h2>'.&mt('You have not replied to any messages in this folder.').'</h2>');
  980:         } else { 
  981:             $r->print('<h2>'.&mt('There are no '.lc($statushash{$msgstatus}).' messages in this folder.').'</h2>');
  982:         }
  983:         if ($numblocked > 0) {
  984:             $r->print(&blocked_in_folder($numblocked,$startblock,$endblock,
  985:                                          \%setters));
  986:         }
  987: 	return;
  988:     }
  989:     my $interdis = $env{'form.interdis'};
  990:     my $number=int($totalnumber/$interdis);
  991:     if ($totalnumber%$interdis == 0) {
  992: 	$number--; 
  993:     }
  994: 
  995:     if (($startdis<0) || ($startdis>$number)) { $startdis=$number; }
  996:     my $firstdis=$interdis*$startdis;
  997:     if ($firstdis>$#temp) { $firstdis=$#temp-$interdis+1; }
  998:     my $lastdis=$firstdis+$interdis-1;
  999:     if ($lastdis>$#temp) { $lastdis=$#temp; }
 1000:     $r->print(&scrollbuttons($startdis,$number,$firstdis,$lastdis,$totalnumber,$msgstatus));
 1001:     $r->print('<form method="post" name="disall" action="/adm/email">'.
 1002: 	      '<table class="LC_mail_list"><tr><th colspan="1">&nbsp;</th><th>');
 1003:     if ($env{'form.sortedby'} eq "revdate") {
 1004: 	$r->print('<a href = "?sortedby=date'.$fsqs.'">'.&mt('Date').'</a></th>');
 1005:     } else {
 1006: 	$r->print('<a href = "?sortedby=revdate'.$fsqs.'">'.&mt('Date').'</a></th>');
 1007:     }
 1008:     $r->print('<th>');
 1009:     if ($env{'form.sortedby'} eq "revuser") {
 1010: 	$r->print('<a href = "?sortedby=user'.$fsqs.'">'.&mt('Username').'</a>');
 1011:     } else {
 1012: 	$r->print('<a href = "?sortedby=revuser'.$fsqs.'">'.&mt('Username').'</a>');
 1013:     }
 1014:     $r->print('</th><th>');
 1015:     if ($env{'form.sortedby'} eq "revdomain") {
 1016: 	$r->print('<a href = "?sortedby=domain'.$fsqs.'">'.&mt('Domain').'</a>');
 1017:     } else {
 1018: 	$r->print('<a href = "?sortedby=revdomain'.$fsqs.'">'.&mt('Domain').'</a>');
 1019:     }
 1020:     $r->print('</th><th>');
 1021:     if ($env{'form.sortedby'} eq "revsubject") {
 1022: 	$r->print('<a href = "?sortedby=subject'.$fsqs.'">'.&mt('Subject').'</a>');
 1023:     } else {
 1024:     	$r->print('<a href = "?sortedby=revsubject'.$fsqs.'">'.&mt('Subject').'</a>');
 1025:     }
 1026:     $r->print('</th><th>');
 1027:     if ($env{'form.sortedby'} eq "revcourse") {
 1028:         $r->print('<a href = "?sortedby=course'.$fsqs.'">'.&mt('Course').'</a>');
 1029:     } else {
 1030:         $r->print('<a href = "?sortedby=revcourse'.$fsqs.'">'.&mt('Course').'</a>');
 1031:     }
 1032:     $r->print('</th><th>');
 1033:     if ($env{'form.sortedby'} eq "revstatus") {
 1034: 	$r->print('<a href = "?sortedby=status'.$fsqs.'">'.&mt('Status').'</a></th>');
 1035:     } else {
 1036:      	$r->print('<a href = "?sortedby=revstatus'.$fsqs.'">'.&mt('Status').'</a></th>');
 1037:     }
 1038:     $r->print("</tr>\n");
 1039: 
 1040:     my $suffix = &Apache::lonmsg::foldersuffix($folder);
 1041:     for (my $n=$firstdis;$n<=$lastdis;$n++) {
 1042: 	my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$origID,
 1043: 	    $description,$recv_name,$recv_domain)= 
 1044: 		@{$temp[$n]};
 1045: 	if (($status ne 'deleted') && defined($sendtime) && $sendtime!~/error/) {
 1046: 	    if ($status eq 'new') {
 1047: 		$r->print('<tr class="LC_mail_new">');
 1048: 	    } elsif ($status eq 'read') {
 1049: 		$r->print('<tr class="LC_mail_read">');
 1050: 	    } elsif ($status eq 'replied') {
 1051: 		$r->print('<tr class="LC_mail_replied">'); 
 1052: 	    } else {
 1053: 		$r->print('<tr class="LC_mail_other">');
 1054: 	    }
 1055: 	    my ($dis_name,$dis_domain) = ($fromname,$fromdomain);
 1056: 	    if ($folder eq 'sent') {
 1057: 		if (defined($recv_name) && !defined($recv_domain)) {
 1058: 		    $dis_name   = join('<br />',@{$recv_name});
 1059: 		    $dis_domain = join('<br />',@{$recv_domain});
 1060: 		} else {
 1061: 		    my $msg_id  = &unescape($origID);
 1062: 		    my %message = &Apache::lonnet::get('nohist_email'.$suffix,
 1063: 						       [$msg_id]);
 1064: 		    my %content = &Apache::lonmsg::unpackagemsg($message{$msg_id});
 1065: 		    $dis_name   = join('<br />',@{$content{'recuser'}});
 1066: 		    $dis_domain = join('<br />',@{$content{'recdomain'}});
 1067: 		}
 1068: 	    }
 1069:             my $localsenttime = &Apache::lonlocal::locallocaltime($sendtime);
 1070:             my $count = $n +1;
 1071: 	    $r->print('<td align="right"><nobr>'.(($status eq 'new')?'<b>':'').
 1072:                       $count.'.'.(($status eq 'new')?'</b>':'').'&nbsp;'.
 1073:                       '<input type="checkbox" name="delmark"'. 
 1074:                       ' value="'.$origID.'" /></nobr></td>');
 1075:             foreach my $item ($localsenttime,$dis_name,$dis_domain,$shortsubj) {
 1076:                 $r->print('<td>'.(($status eq 'new')?'<b>':'').
 1077:                           '<a href="/adm/email?display='.$origID.$sqs.'">'.
 1078:                           $item.(($status eq 'new')?'</b>':'').'</td>');
 1079:             }
 1080:             my $showstatus;
 1081:             my %statushash = &get_msgstatus_types();
 1082:             if ($status eq '') {
 1083:                 $showstatus = '';
 1084:             } else {
 1085:                 $showstatus = $statushash{$status};
 1086:             }
 1087: 	    $r->print('<td>'.(($status eq 'new')?'<b>':'').$description.
 1088:                       (($status eq 'new')?'</b>':'').'</td><td>'.
 1089:                       (($status eq 'new')?'<b>':'').$showstatus.
 1090:                       (($status eq 'new')?'</b>':'').'</td></tr>'."\n");
 1091: 	} elsif ($status eq 'deleted') {
 1092: # purge
 1093: 	    my ($result,$msg) = 
 1094: 		&movemsg(&unescape($origID),$folder,'trash');
 1095: 	    
 1096: 	}
 1097:     }   
 1098:     $r->print("</table>\n");
 1099:     $r->print('<table border="0" cellspacing="2" cellpadding="2">
 1100:  <tr>
 1101:   <td>'.
 1102:   '<input type="button" onclick="javascript:checkAll(document.disall.delmark)" value="'.&mt('Check All').'" /><br />'."\n".
 1103:   '<input type="button" onclick="javascript:uncheckAll(document.disall.delmark)" value="'.&mt('Uncheck All').'" />'."\n".
 1104:   '<input type="hidden" name="sortedby" value="'.$env{'form.sortedby'}.'" /></td><td>&nbsp;</td>'."\n".
 1105:   '<td align="center"><b>'.&mt('Action').'</b><br />'."\n".
 1106:   '  <select name="checkedaction" onchange="javascript:checkfoldermove()">'."\n");
 1107: 
 1108:     if ($folder ne 'trash') {
 1109:         $r->print('    <option value="markeddel">'.&mt('Delete').'</option>'."\n");
 1110:     }
 1111:     if ($msgstatus ne 'read') {
 1112:         $r->print('    <option value="markedread">'.&mt('Mark Read').'</option>."\n"');
 1113:     }
 1114:     if ($msgstatus ne 'unread') {
 1115:         $r->print('    <option value="markedunread">'.&mt('Mark Unread').'</option>'."\n");
 1116:     }
 1117:     $r->print('   <option value="markedforward">'.&mt('Forward').'</option>'."\n");
 1118: 
 1119:     my %gotfolders = &Apache::lonmsg::get_user_folders();
 1120:     if (keys(%gotfolders) > 0) {
 1121:         $r->print('   <option value="markedmove">'.&mt('Move to Folder ->').
 1122:                   '</option>');
 1123:     }
 1124:     $r->print("\n".'</select></td>'."\n");
 1125: 
 1126:     if (keys(%gotfolders) > 0) {
 1127:         $r->print('<td align="center"><b>'.&mt('Destination folder').'<b><br />');
 1128: 	my %userfolders;
 1129:         foreach my $key (keys(%gotfolders)) {
 1130:             $userfolders{$key} = $key;
 1131:         }
 1132:         $userfolders{''} = "";
 1133:         $r->print(&Apache::loncommon::select_form('','movetofolder',%userfolders).
 1134:                   '</td>');
 1135:     }
 1136:     $r->print('<td>&nbsp;</td><td>&nbsp;&nbsp;'.
 1137:               '<input type="button" name="go" value="'.&mt('Go').
 1138:               '" onclick="javascript:validate_checkedaction()"/></td>'."\n".
 1139:               '</tr></table>');
 1140:     my $postedstartdis=$startdis+1;
 1141:     $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>');
 1142:     if ($numblocked > 0) {
 1143:         $r->print(&blocked_in_folder($numblocked,$startblock,$endblock,
 1144:                                      \%setters));
 1145:     }
 1146: }
 1147: 
 1148: sub blocked_in_folder {
 1149:     my ($numblocked,$startblock,$endblock,$setters) = @_;
 1150:     my $beginblock = &Apache::lonlocal::locallocaltime($startblock);
 1151:     my $finishblock = &Apache::lonlocal::locallocaltime($endblock);
 1152:     my $output = '<br /><br />'.
 1153:                   &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);
 1154:     $output .= &Apache::loncommon::build_block_table($startblock,$endblock,
 1155:                                                      $setters);
 1156:     return $output;
 1157: }
 1158: 
 1159: # ============================================================== Compose output
 1160: 
 1161: sub compout {
 1162:     my ($r,$forwarding,$replying,$broadcast,$replycrit,$folder,$dismode,
 1163:         $multiforward)=@_;
 1164:     my $suffix=&Apache::lonmsg::foldersuffix($folder);
 1165:     my ($cdom,$cnum,$group,$refarg);
 1166:     if (exists($env{'form.group'})) {
 1167:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1168:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1169:         $group = $env{'form.group'};
 1170:         my $action = 'composing';
 1171:         $r->print(&groupmail_header($action,$group,$cdom,$cnum));
 1172:     } elsif ($broadcast eq 'individual') {
 1173: 	&printheader($r,'/adm/email?compose=individual',
 1174: 	     'Send a Message');
 1175:     } elsif ($broadcast) {
 1176: 	&printheader($r,'/adm/email?compose=group',
 1177: 	     'Broadcast Message');
 1178:     } elsif ($forwarding) {
 1179: 	&Apache::lonhtmlcommon::add_breadcrumb
 1180:         ({href=>"/adm/email?display=".&escape($forwarding),
 1181:           text=>"Display Message"});
 1182: 	&printheader($r,'/adm/email?forward='.&escape($forwarding),
 1183: 	     'Forwarding a Message');
 1184:     } elsif ($replying) {
 1185: 	&Apache::lonhtmlcommon::add_breadcrumb
 1186:         ({href=>"/adm/email?display=".&escape($replying),
 1187:           text=>"Display Message"});
 1188: 	&printheader($r,'/adm/email?replyto='.&escape($replying),
 1189: 	     'Replying to a Message');
 1190:     } elsif ($replycrit) {
 1191: 	$r->print('<h3>'.&mt('Replying to a Critical Message').'</h3>');
 1192: 	$replying=$replycrit;
 1193:     } elsif ($multiforward) {
 1194:         &Apache::lonhtmlcommon::add_breadcrumb
 1195:         ({href=>"/adm/email?folder=".&escape($folder),
 1196:           text=>"Display All Messages"});
 1197:         &printheader($r,'/adm/email?compose=multiforward',
 1198:              'Forwarding Multiple Messages');
 1199:         $r->print(&mt('Each of the <b>[quant,_1,message]</b> you checked will be forwarded to the recipient(s) you select below.',$multiforward).'<br />');
 1200:     } else {
 1201: 	&printheader($r,'/adm/email?compose=upload',
 1202: 	     'Distribute from Uploaded File');
 1203:     }
 1204: 
 1205:     my $dispcrit='';
 1206:     my $dissub='';
 1207:     my $dismsg='';
 1208:     my $disbase='';
 1209:     my $func=&mt('Send New');
 1210:     my %lt=&Apache::lonlocal::texthash('us'  => 'Username',
 1211: 				       'do'  => 'Domain',
 1212: 				       'ad'  => 'Additional Recipients',
 1213: 				       'sb'  => 'Subject',
 1214: 				       'ca'  => 'Cancel',
 1215: 				       'ma'  => 'Mail',
 1216:                                        'msg' => 'Messages',
 1217:                                        'gen' => 'Generate messages from a file',
 1218:                                        'gmt' => 'General message text',
 1219:                                        'tff' => 'The file format for the uploaded portion of the message is',
 1220:                                        'uas' => 'Upload and Send',
 1221:                                       );
 1222:     if (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
 1223: 	|| &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
 1224: 				    '/'.$env{'request.course.sec'})) {
 1225: 	 my $crithelp = Apache::loncommon::help_open_topic("Course_Critical_Message");
 1226:          $dispcrit=
 1227:  '<p><label><input type="checkbox" name="critmsg" /> '.&mt('Send as critical message').'</label> ' . $crithelp . 
 1228:  '</p><p>'.
 1229:  '<label><input type="checkbox" name="sendbck" /> '.&mt('Send as critical message').'  ' .
 1230:  &mt('and return receipt') . '</label>' . $crithelp . 
 1231:  '</p><p><label><input type="checkbox" name="permanent" /> '.
 1232: &mt('Send copy to permanent email address (if known)').'</label></p>'.
 1233: '<p><label><input type="checkbox" name="rsspost" /> '.
 1234: 		  &mt('Include in course RSS newsfeed').'</label></p>';
 1235:      }
 1236:     my %message;
 1237:     my %content;
 1238:     my $defdom=$env{'user.domain'};
 1239:     if ($forwarding) {
 1240: 	%message=&Apache::lonnet::get('nohist_email'.$suffix,[$forwarding]);
 1241: 	%content=&Apache::lonmsg::unpackagemsg($message{$forwarding},$folder);
 1242: 	$dispcrit.='<input type="hidden" name="forwid" value="'.
 1243: 	    $forwarding.'" />';
 1244: 	$func=&mt('Forward');
 1245: 	
 1246: 	$dissub=&mt('Forwarding').': '.$content{'subject'};
 1247: 	$dismsg=&mt('Forwarded message from').' '.
 1248: 	    $content{'sendername'}.' '.&mt('at').' '.$content{'senderdomain'};
 1249: 	if ($content{'baseurl'}) {
 1250: 	    $disbase='<input type="hidden" name="baseurl" value="'.&escape($content{'baseurl'}).'" />';
 1251: 	}
 1252:     }
 1253:     if ($replying) {
 1254: 	%message=&Apache::lonnet::get('nohist_email'.$suffix,[$replying]);
 1255: 	%content=&Apache::lonmsg::unpackagemsg($message{$replying},$folder);
 1256: 	$dispcrit.='<input type="hidden" name="replyid" value="'.
 1257: 	    $replying.'" />';
 1258: 	$func=&mt('Send Reply to');
 1259: 	
 1260: 	$dissub=&mt('Reply').': '.$content{'subject'};       
 1261: 	$dismsg='> '.$content{'message'};
 1262: 	$dismsg=~s/\r/\n/g;
 1263: 	$dismsg=~s/\f/\n/g;
 1264: 	$dismsg=~s/\n+/\n\> /g;
 1265: 	if ($content{'baseurl'}) {
 1266: 	    $disbase='<input type="hidden" name="baseurl" value="'.&escape($content{'baseurl'}).'" />';
 1267: 	    if ($env{'user.adv'}) {
 1268: 		$disbase.='<label><input type="checkbox" name="storebasecomment" />'.&mt('Store message for re-use').
 1269: 		    '</label> <a href="/adm/email?showcommentbaseurl='.
 1270: 		    &escape($content{'baseurl'}).'" target="comments">'.
 1271: 		    &mt('Show re-usable messages').'</a><br />';
 1272: 	    }
 1273: 	}
 1274:     }
 1275:     my $citation=&displayresource(%content);
 1276:     my ($can_grp_broadcast,$viewgrps,$editgrps);
 1277:     if ($env{'form.recdom'}) { $defdom=$env{'form.recdom'}; }
 1278:     if ($env{'form.text'}) { $dismsg=$env{'form.text'}; }
 1279:     if ($env{'form.subject'}) { $dissub=$env{'form.subject'}; }
 1280:     $r->print(
 1281:                 '<form action="/adm/email"  name="compemail" method="post"'.
 1282:                 ' enctype="multipart/form-data">'."\n".
 1283:                 '<input type="hidden" name="sendmail" value="on" />'."\n");
 1284:     if ($broadcast eq 'group' && $env{'form.group'} ne '') {
 1285:         $can_grp_broadcast = 
 1286:                 &Apache::lonnet::allowed('sgb',$env{'request.course.id'}.'/'.
 1287:                                          $group);
 1288:         $viewgrps = 
 1289:                &Apache::lonnet::allowed('vcg',$env{'request.course.id'}.
 1290:                ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''));
 1291:         $editgrps = 
 1292:                &Apache::lonnet::allowed('mdg',$env{'request.course.id'}.
 1293:                ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''));
 1294:         if ($viewgrps || $editgrps || $can_grp_broadcast) {
 1295:             $r->print(&disgroup($cdom,$cnum,$group,$viewgrps,$editgrps));
 1296:         }
 1297:     }
 1298:     $r->print('<table>');
 1299:     if (($broadcast eq 'group') && ($group ne '') && 
 1300:         (!$can_grp_broadcast && !$viewgrps && !$editgrps)) {
 1301:         $r->print(&recipient_input_row($cdom,%lt));
 1302:     } 
 1303:     if (($broadcast ne 'group') && ($broadcast ne 'upload')) {
 1304: 	if ($replying) {
 1305: 	    $r->print('<tr><td colspan="2">'.&mt('Replying to').' '.
 1306: 		      &Apache::loncommon::aboutmewrapper(
 1307: 							 &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).' ('.
 1308: 		      $content{'sendername'}.':'.
 1309: 		      $content{'senderdomain'}.')'.
 1310: 		      '<input type="hidden" name="recuname" value="'.$content{'sendername'}.'" />'.
 1311: 		      '<input type="hidden" name="recdomain" value="'.$content{'senderdomain'}.'" />'.
 1312: 		      '</td></tr>');
 1313: 	} else {
 1314:             $r->print(&recipient_input_row($defdom,%lt));
 1315:         }
 1316:     }
 1317:     my $latexHelp = Apache::loncommon::helpLatexCheatsheet();
 1318:     my $subj_size;
 1319:     if ($multiforward) {
 1320:         $r->print(&additional_rec_row(\%lt));
 1321:         $r->print('<tr><td colspan="2">'.
 1322:                   &mt('Unless you choose otherwise:').'<ul><li>'.
 1323:         &mt("The subject in each forwarded message will be <i>'Forwarding:'</i> followed by the original subject.").'</li><li>'.
 1324:         &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>');
 1325:         $func=&mt('Forward');
 1326:         $dissub = &mt('Forwarding').': ';
 1327:         $subj_size = '10';
 1328:         my $extra = '&lt;'.&mt('original subject').'&gt;&nbsp;&nbsp;&nbsp;'.
 1329:                     '<input type="radio" name="showorigsubj" value="1" checked="checked" />'.&mt('Yes').'&nbsp;<input type="radio" name="showorigsubj" value="0" />'.&mt('No');
 1330:         $dismsg = &mt('Forwarded message from ').' ';
 1331:         my $sender = &mt("sender's name");
 1332:         $r->print(&msg_subject_row($dissub,\%lt,$subj_size,$extra));
 1333:         $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>
 1334: </table>
 1335: <br />'.
 1336: $latexHelp.
 1337: &mt("Any new text to display before the text of the original messages:").'<br />
 1338: <textarea name="message" id="message" cols="80" rows="5" wrap="hard">
 1339: </textarea></p><br />');
 1340:         my @to_forward = &Apache::loncommon::get_env_multiple('form.delmark');
 1341:         foreach my $msg (@to_forward) {
 1342:             $r->print('<input type="hidden" name="delmark" value="'.$msg.'" />');
 1343:         }
 1344:         $r->print(&submit_button_row($folder,$dismode,$func.' '.$lt{'msg'},
 1345:                                      \%lt));
 1346:     } elsif ($broadcast ne 'upload') {
 1347:         $subj_size = '50';
 1348:         $r->print(&additional_rec_row(\%lt));
 1349:         $r->print(&msg_subject_row($dissub,\%lt,$subj_size));
 1350:         $r->print(<<"ENDCOMP");
 1351: </table>
 1352: $latexHelp
 1353: <textarea name="message" id="message" cols="80" rows="15" wrap="hard">$dismsg
 1354: </textarea></p><br />
 1355: $dispcrit
 1356: $disbase
 1357: ENDCOMP
 1358:         $r->print(&submit_button_row($folder,$dismode,$func.' '.$lt{'ma'},
 1359:                                      \%lt));
 1360:         $r->print($citation);
 1361:         if (exists($env{'form.ref'})) {
 1362:             $r->print('<input type="hidden" name="ref" value="'.
 1363:                       $env{'form.ref'}.'" />');
 1364:         }
 1365:         if (exists($env{'form.group'})) {
 1366:             $r->print('<input type="hidden" name="group" value="'.
 1367:                       $env{'form.group'}.'" />');
 1368:         }
 1369:     } else { # $broadcast is 'upload'
 1370: 	$r->print(<<ENDBLOCK);
 1371: <input type="hidden" name="sendmode" value="upload" />
 1372: <input type="hidden" name="send" value="on" />
 1373: <h3>$lt{'gen'}</h3>
 1374: <p>
 1375: Subject: <input type="text" size="50" name="subject" />
 1376: </p>
 1377: <p>$lt{'gmt'}:<br />
 1378: <textarea name="message" id="message" cols="60" rows="10" wrap="hard">$dismsg
 1379: </textarea></p>
 1380: <p>
 1381: $lt{'tff'}:
 1382: ENDBLOCK
 1383:        $r->print('
 1384: <pre>'."\n".
 1385: &mt('username1:domain1: text')."\n".
 1386: &mt('username2:domain2: text')."\n".
 1387: &mt('username3:domain1: text')."\n".
 1388: '</pre>
 1389: </p>
 1390: <p>
 1391: '.&mt('The messages will be assembled from all lines with the respective'."\n".'<tt>username:domain</tt>, and appended to the general message text.'));
 1392:         $r->print(<<ENDUPLOAD);
 1393: </p>
 1394: <p>
 1395: <input type="file" name="upfile" size="40" /></p><p>
 1396: $dispcrit
 1397: <input type="submit" value="$lt{'uas'}" /></p>
 1398: ENDUPLOAD
 1399:     }
 1400:     if ($broadcast eq 'group') {
 1401:        if ($group eq '') {
 1402:            my $studentsel = &discourse();
 1403:            $r->print($studentsel);
 1404:        }
 1405:     }
 1406:     if ($env{'form.displayedcrit'}) {
 1407: 	$r->print('<input type="hidden" name="displayedcrit" value="true" />');
 1408:     }
 1409:     $r->print('</form>'.
 1410: 	      &Apache::lonfeedback::generate_preview_button('compemail','message').
 1411: 	      &Apache::lonhtmlcommon::htmlareaselectactive('message'));
 1412: }
 1413: 
 1414: # ---------------------------------------------------- Display all face to face
 1415: 
 1416: sub recipient_input_row {
 1417:     my ($dom,%lt) = @_;
 1418:     my $domform = &Apache::loncommon::select_dom_form($dom,'recdomain');
 1419:     my $selectlink=
 1420:       &Apache::loncommon::selectstudent_link('compemail','recuname',
 1421:                                              'recdomain');
 1422:     my $output = <<"ENDREC";
 1423: <tr><td>$lt{'us'}:</td><td><input type="text" size="12" name="recuname" value="$env{'form.recname'}" /></td><td rowspan="2">$selectlink</td></tr>
 1424: <tr><td>$lt{'do'}:</td>
 1425: <td>$domform</td></tr>
 1426: ENDREC
 1427:     return $output;
 1428: }
 1429: 
 1430: sub additional_rec_row {
 1431:     my ($lt) = @_;
 1432:     my $output = <<"ENDADD";
 1433: <tr><td>$lt->{'ad'}:<br /><tt>username:domain,username:domain, ...
 1434: </tt></td><td>
 1435: <input type="text" size="50" name="additionalrec" /></td></tr>
 1436: ENDADD
 1437:     return $output;
 1438: }
 1439: 
 1440: sub submit_button_row {
 1441:     my ($folder,$dismode,$sendtext,$lt) = @_;
 1442:     my $output = qq| 
 1443: <input type="hidden" name="folder" value="$folder" />
 1444: <input type="hidden" name="dismode" value="$dismode" />
 1445: <input type="submit" name="send" value="$sendtext" />
 1446: <input type="submit" name="cancel" value="$lt->{'ca'}" /><hr />
 1447: |;
 1448:     return $output;
 1449: }
 1450: 
 1451: sub msg_subject_row {
 1452:     my ($dissub,$lt,$subj_size,$extra) = @_;
 1453:     my $output = '<tr><td>'.$lt->{'sb'}.':</td><td><input type="text" size="'.
 1454:                  $subj_size.'" name="subject" value="'.$dissub.'" />'.$extra.
 1455:                  '</td></tr>';
 1456:     return $output;
 1457: }
 1458: 
 1459: sub retrieve_instructor_comments {
 1460:     my ($user,$domain)=@_;
 1461:     my $target=$env{'form.grade_target'};
 1462:     if (! $env{'request.course.id'}) { return; }
 1463:     if (! &Apache::lonnet::allowed('dff',$env{'request.course.id'})
 1464: 	&& ! &Apache::lonnet::allowed('dff',$env{'request.course.id'}.
 1465: 				      '/'.$env{'request.course.sec'})) {
 1466: 	return;
 1467:     }
 1468:     my %records=&Apache::lonnet::dump('nohist_email',
 1469: 			 $env{'course.'.$env{'request.course.id'}.'.domain'},
 1470: 			 $env{'course.'.$env{'request.course.id'}.'.num'},
 1471:                          '%255b'.$user.'%253a'.$domain.'%255d');
 1472:     my $result='';
 1473:     foreach my $key (sort(keys(%records))) {
 1474:         my %content=&Apache::lonmsg::unpackagemsg($records{$key});
 1475:         next if ($content{'senderdomain'} eq '');
 1476:         next if ($content{'subject'} !~ /^Record/);
 1477: 	# &Apache::lonfeedback::newline_to_br(\$content{'message'});
 1478: 	$result.='Recorded by '.
 1479:             $content{'sendername'}.':'.$content{'senderdomain'}."\n";
 1480:         $result.=
 1481:             &Apache::lontexconvert::msgtexconverted($content{'message'})."\n";
 1482:      }
 1483:     return $result;
 1484: }
 1485: 
 1486: sub disfacetoface {
 1487:     my ($r,$user,$domain)=@_;
 1488:     my $target=$env{'form.grade_target'};
 1489:     unless ($env{'request.course.id'}) { return; }
 1490:     if  (!&Apache::lonnet::allowed('dff',$env{'request.course.id'})
 1491: 	 && ! &Apache::lonnet::allowed('dff',$env{'request.course.id'}.
 1492: 				       '/'.$env{'request.course.sec'})) {
 1493: 	$r->print(&mt('Not allowed'));
 1494: 	return;
 1495:     }
 1496:     my %records=&Apache::lonnet::dump('nohist_email',
 1497: 			 $env{'course.'.$env{'request.course.id'}.'.domain'},
 1498: 			 $env{'course.'.$env{'request.course.id'}.'.num'},
 1499:                          '%255b'.$user.'%253a'.$domain.'%255d');
 1500:     my $result='';
 1501:     foreach my $key (sort(keys(%records))) {
 1502:         my %content=&Apache::lonmsg::unpackagemsg($records{$key});
 1503:         next if ($content{'senderdomain'} eq '');
 1504: 	&Apache::lonfeedback::newline_to_br(\$content{'message'});
 1505:         if ($content{'subject'}=~/^Record/) {
 1506: 	    $result.='<h3>'.&mt('Record').'</h3>';
 1507:         } elsif ($content{'subject'}=~/^Broadcast/) {
 1508:             $result .='<h3>'.&mt('Broadcast Message').'</h3>';
 1509:             if ($content{'subject'}=~/^Broadcast\./) {
 1510:                 if (defined($content{'coursemsgid'})) {
 1511:                     my $crsmsgid = &escape($content{'coursemsgid'});
 1512:                     my $broadcast_message = &general_message($crsmsgid);
 1513:                     $content{'message'} = '<b>'.&mt('Subject').': '.$content{'message'}.'</b><br />'.$broadcast_message;
 1514:                 } else {
 1515:                     %content=&Apache::lonmsg::unpackagemsg($content{'message'});
 1516:                     $content{'message'} =
 1517:                     '<b>'.&mt('Subject').': '.$content{'subject'}.'</b><br />'.
 1518:                     $content{'message'};
 1519:                 }
 1520:             }    
 1521:         } else {
 1522:             $result.='<h3>'.&mt('Critical Message').'</h3>';
 1523:             if (defined($content{'coursemsgid'})) {
 1524:                 my $crsmsgid=&escape($content{'coursemsgid'});
 1525:                 my $critical_message = &general_message($crsmsgid);
 1526:                 $content{'message'} = '<b>'.&mt('Subject').': '.$content{'message'}.'</b><br />'.$critical_message;
 1527:             } else {
 1528:                 %content=&Apache::lonmsg::unpackagemsg($content{'message'});
 1529:                 $content{'message'}=
 1530:                 '<b>'.&mt('Subject').': '.$content{'subject'}.'</b><br />'.
 1531: 		$content{'message'};
 1532:             }
 1533:         }
 1534:         $result.=&mt('By').': <b>'.
 1535: &Apache::loncommon::aboutmewrapper(
 1536:  &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).'</b> ('.
 1537: $content{'sendername'}.':'.
 1538:             $content{'senderdomain'}.') '.$content{'time'}.
 1539:             '<br /><pre>'.
 1540:               &Apache::lontexconvert::msgtexconverted($content{'message'}).
 1541: 	      '</pre>';
 1542:      }
 1543:     # Check to see if there were any messages.
 1544:     if ($result eq '') {
 1545:         my $lctype = lc(&Apache::loncommon::course_type());
 1546: 	if ($target ne 'tex') { 
 1547: 	    $r->print("<p><b>".&mt('No notes, face-to-face discussion records, critical messages, or broadcast messages in this [_1].',$lctype)."</b></p>");
 1548: 	} else {
 1549: 	    $r->print('\textbf{'.&mt('No notes, face-to-face discussion records, critical messages or broadcast messages in this [_1].',$lctype).'}\\\\');
 1550: 	}
 1551:     } else {
 1552:        $r->print($result);
 1553:     }
 1554: }
 1555: 
 1556: sub general_message {
 1557:     my ($crsmsgid) = @_;
 1558:     my %general_content;
 1559:     if ($crsmsgid) { 
 1560:         my %course_content = &Apache::lonnet::get('nohist_email',[$crsmsgid],
 1561:                            $env{'course.'.$env{'request.course.id'}.'.domain'},
 1562:                            $env{'course.'.$env{'request.course.id'}.'.num'});
 1563:         %general_content = &Apache::lonmsg::unpackagemsg($course_content{$crsmsgid});
 1564:     }
 1565:     return $general_content{'message'};
 1566: }
 1567: 
 1568: # ---------------------------------------------------------------- Face to face
 1569: 
 1570: sub facetoface {
 1571:     my ($r,$stage)=@_;
 1572:     if (!&Apache::lonnet::allowed('dff',$env{'request.course.id'})
 1573: 	&& ! &Apache::lonnet::allowed('dff',$env{'request.course.id'}.
 1574: 				      '/'.$env{'request.course.sec'})) {
 1575: 	$r->print(&mt('Not allowed'));
 1576: 	return;
 1577:     }
 1578:     my $crstype = &Apache::loncommon::course_type();
 1579:     my $leaders = ($crstype eq 'Group') ? 'coordinators and leaders'
 1580:                                         : 'faculty and staff';
 1581:     &printheader($r,
 1582: 		 '/adm/email?recordftf=query',
 1583: 		 "User Notes, Face-to-Face, Critical Messages, Broadcast Messages");
 1584: # from query string
 1585: 
 1586:     if ($env{'form.recname'}) { $env{'form.recuname'}=$env{'form.recname'}; }
 1587:     if ($env{'form.recdom'}) { $env{'form.recdomain'}=$env{'form.recdom'}; }
 1588: 
 1589:     my $defdom=$env{'user.domain'};
 1590: # already filled in
 1591:     if ($env{'form.recdomain'}) { $defdom=$env{'form.recdomain'}; }
 1592: # generate output
 1593:     my $domform = &Apache::loncommon::select_dom_form($defdom,'recdomain');
 1594:     my $stdbrws = &Apache::loncommon::selectstudent_link
 1595: 	('stdselect','recuname','recdomain');
 1596:     my %lt=&Apache::lonlocal::texthash('user' => 'Username',
 1597: 				       'dom' => 'Domain',
 1598: 				       'head' => "User Notes, Records of Face-To-Face Discussions, Critical Messages, and Broadcast Messages in $crstype",
 1599: 				       'subm' => 'Retrieve discussion and message records',
 1600: 				       'newr' => 'New Record (record is visible to '.lc($crstype).' '.$leaders.')',
 1601: 				       'post' => 'Post this Record');
 1602:     $r->print(<<"ENDTREC");
 1603: <h3>$lt{'head'}</h3>
 1604: <form method="post" action="/adm/email" name="stdselect">
 1605: <input type="hidden" name="recordftf" value="retrieve" />
 1606: <table>
 1607: <tr><td>$lt{'user'}:</td><td><input type="text" size="12" name="recuname" value="$env{'form.recuname'}" /></td>
 1608: <td rowspan="2">
 1609: $stdbrws
 1610: <input type="submit" value="$lt{'subm'}" /></td>
 1611: </tr>
 1612: <tr><td>$lt{'dom'}:</td>
 1613: <td>$domform</td></tr>
 1614: </table>
 1615: </form>
 1616: ENDTREC
 1617:     if (($stage ne 'query') &&
 1618:         ($env{'form.recdomain'}) && ($env{'form.recuname'})) {
 1619:         chomp($env{'form.newrecord'});
 1620:         if ($env{'form.newrecord'}) {
 1621: 	    &Apache::lonmsg::store_instructor_comment($env{'form.newrecord'},
 1622: 						      $env{'form.recuname'},
 1623: 						      $env{'form.recdomain'});
 1624:         }
 1625:         $r->print('<h3>'.&Apache::loncommon::plainname($env{'form.recuname'},
 1626: 				     $env{'form.recdomain'}).'</h3>');
 1627:         &disfacetoface($r,$env{'form.recuname'},$env{'form.recdomain'});
 1628: 	$r->print(<<ENDRHEAD);
 1629: <form method="post" action="/adm/email">
 1630: <input name="recdomain" value="$env{'form.recdomain'}" type="hidden" />
 1631: <input name="recuname" value="$env{'form.recuname'}" type="hidden" />
 1632: ENDRHEAD
 1633:         $r->print(<<ENDBFORM);
 1634: <hr />$lt{'newr'}<br />
 1635: <textarea name="newrecord" cols="80" rows="10" wrap="hard"></textarea>
 1636: <br />
 1637: <input type="hidden" name="recordftf" value="post" />
 1638: <input type="submit" value="$lt{'post'}" />
 1639: </form>
 1640: ENDBFORM
 1641:     }
 1642: }
 1643: 
 1644: # ----------------------------------------------------------- Blocking during exams
 1645: 
 1646: sub examblock {
 1647:     my ($r,$action) = @_;
 1648:     unless ($env{'request.course.id'}) { return;}
 1649:     if (!&Apache::lonnet::allowed('dcm',$env{'request.course.id'})
 1650: 	&& ! &Apache::lonnet::allowed('dcm',$env{'request.course.id'}.
 1651: 				      '/'.$env{'request.course.sec'})) {
 1652: 	$r->print('Not allowed');
 1653: 	return;
 1654:     }
 1655:     my $usertype = (&Apache::loncommon::course_type() eq 'Group') ? 'members'
 1656: 	                                                          : 'students';
 1657:     my %lt=&Apache::lonlocal::texthash(
 1658:             'comb' => 'Communication Blocking',
 1659:             'cbds' => 'Communication blocking during scheduled exams',
 1660:             'desc' => "You can use communication blocking to prevent $usertype enrolled in this course 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, please be careful that you select the correct start and end times for your scheduled exam when setting or modifying these parameters.",
 1661:              'mecb' => 'Modify existing communication blocking periods',
 1662:              'ncbc' => 'No communication blocks currently stored',
 1663:              'stor' => 'Store',
 1664:     );
 1665: 
 1666:     my %ltext = &Apache::lonlocal::texthash(
 1667:             'dura' => 'Duration',
 1668:             'setb' => 'Set by',
 1669:             'even' => 'Event',
 1670:             'blck' => 'Blocked?',
 1671:             'actn' => 'Action',
 1672:             'star' => 'Start',
 1673:             'endd' => 'End'
 1674:     );
 1675: 
 1676:     &printheader($r,'/adm/email?block=display',$lt{'comb'});
 1677:     $r->print('<h3>'.$lt{'cbds'}.'</h3>');
 1678: 
 1679:     if ($action eq 'store') {
 1680:         &blockstore($r);
 1681:     }
 1682: 
 1683:     $r->print($lt{'desc'}.'<br /><br />
 1684:                <form name="blockform" method="post" action="/adm/email?block=store">
 1685:              ');
 1686: 
 1687:     $r->print('<h4>'.$lt{'mecb'}.'</h4>');
 1688:     my %records = ();
 1689:     my $blockcount = 0;
 1690:     my $parmcount = 0;
 1691:     &get_blockdates(\%records,\$blockcount);
 1692:     if ($blockcount > 0) {
 1693:         $parmcount = &display_blocker_status($r,\%records,\%ltext);
 1694:     } else {
 1695:         $r->print($lt{'ncbc'}.'<br /><br />');
 1696:     }
 1697:     &display_addblocker_table($r,$parmcount,\%ltext);
 1698:     my $end_page=&Apache::loncommon::end_page();
 1699:     $r->print(<<"END");
 1700: <br />
 1701: <input type="hidden" name="blocktotal" value="$blockcount" />
 1702: <input type ="submit" value="$lt{'stor'}" />
 1703: </form>
 1704: $end_page
 1705: END
 1706:     return;
 1707: }
 1708: 
 1709: sub blockstore {
 1710:     my $r = shift;
 1711:     my %lt=&Apache::lonlocal::texthash(
 1712:             'tfcm' => 'The following changes were made',
 1713:             'ncwm' => 'No changes were made.' 
 1714:     );
 1715:     my %adds = ();
 1716:     my %removals = ();
 1717:     my %cancels = ();
 1718:     my $modtotal = 0;
 1719:     my $canceltotal = 0;
 1720:     my $addtotal = 0;
 1721:     my %blocking = ();
 1722:     $r->print('<h3>'.$lt{'head'}.'</h3>');
 1723:     foreach my $envkey (keys(%env)) {
 1724:         if ($envkey =~ m/^form\.modify_(\d+)$/) {
 1725:             $adds{$1} = $1;
 1726:             $removals{$1} = $1;
 1727:             $modtotal ++;
 1728:         } elsif ($envkey =~ m/^form\.cancel_(\d+)$/) {
 1729:             $cancels{$1} = $1;
 1730:             unless ( defined($removals{$1}) ) {
 1731:                 $removals{$1} = $1;
 1732:                 $canceltotal ++;
 1733:             }
 1734:         } elsif ($envkey =~ m/^form\.add_(\d+)$/) {
 1735:             $adds{$1} = $1;
 1736:             $addtotal ++;
 1737:         } 
 1738:     }
 1739: 
 1740:     foreach my $key (keys(%removals)) {
 1741:         my $hashkey = $env{'form.key_'.$key};
 1742:         &Apache::lonnet::del('comm_block',["$hashkey"],
 1743:                          $env{'course.'.$env{'request.course.id'}.'.domain'},
 1744:                          $env{'course.'.$env{'request.course.id'}.'.num'}
 1745:                          );
 1746:     }
 1747:     foreach my $key (keys(%adds)) {
 1748:         unless ( defined($cancels{$key}) ) {
 1749:             my ($newstart,$newend) = &get_dates_from_form($key);
 1750:             my $newkey = $newstart.'____'.$newend;
 1751:             my $blocktypes = &get_block_choices($key);
 1752:             $blocking{$newkey} = {
 1753:                           setter => $env{'user.name'}.':'.$env{'user.domain'},
 1754:                           event  => &escape($env{'form.title_'.$key}),
 1755:                           blocks => $blocktypes,
 1756:                         };
 1757:         }
 1758:     }
 1759:     if ($addtotal + $modtotal > 0) {
 1760:         &Apache::lonnet::put('comm_block',\%blocking,
 1761:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 1762:                      $env{'course.'.$env{'request.course.id'}.'.num'}
 1763:                      );
 1764:     }
 1765:     my $chgestotal = $canceltotal + $modtotal + $addtotal;
 1766:     if ($chgestotal > 0) {
 1767:         $r->print($lt{'tfcm'}.'<ul>');
 1768:         if ($canceltotal > 0) {
 1769:             $r->print('<li>'.&mt('[quant,_1,communication blocking period was,communication blocking periods were] removed.',$canceltotal).'</li>');
 1770:         }
 1771:         if ($modtotal > 0) {
 1772:             $r->print('<li>'.&mt('[quant,_1,communication blocking period was,communication blocking periods were] modified.',$modtotal).'</li>');
 1773:         }
 1774:         if ($addtotal > 0) {
 1775:             $r->print('<li>'.&mt('[quant,_1,communication blocking period was,communication blocking periods were] added.',$addtotal).'</li>');
 1776:         }
 1777:         $r->print('</ul>');
 1778:     } else {
 1779:         $r->print($lt{'ncwm'});
 1780:     }
 1781:     $r->print('<br />');
 1782:     return;
 1783: }
 1784: 
 1785: sub get_dates_from_form {
 1786:     my $item = shift;
 1787:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate_'.$item);
 1788:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate_'.$item);
 1789:     return ($startdate,$enddate);
 1790: }
 1791: 
 1792: sub get_blockdates {
 1793:     my ($records,$blockcount) = @_;
 1794:     $$blockcount = 0;
 1795:     %{$records} = &Apache::lonnet::dump('comm_block',
 1796:                          $env{'course.'.$env{'request.course.id'}.'.domain'},
 1797:                          $env{'course.'.$env{'request.course.id'}.'.num'}
 1798:                          );
 1799:     $$blockcount = keys(%{$records});
 1800: 
 1801:     if ((keys(%{$records}))[0] =~ /^error: 2 /) {
 1802: 	$records = {};
 1803: 	$$blockcount = 0;
 1804:     }
 1805: }
 1806: 
 1807: sub get_block_choices {
 1808:     my $item = shift;
 1809:     my $blocklist;
 1810:     my ($typeorder,$types) = &blocktype_text();
 1811:     foreach my $type (@{$typeorder}) {
 1812:         if ($env{'form.'.$type.'_'.$item}) {
 1813:             $blocklist->{$type} = 'on'; 
 1814:         } else {
 1815:             $blocklist->{$type} = 'off';
 1816:         }
 1817:     }
 1818:     return $blocklist;
 1819: }
 1820: 
 1821: sub display_blocker_status {
 1822:     my ($r,$records,$ltext) = @_;
 1823:     my $parmcount = 0;
 1824:   
 1825:     my %lt = &Apache::lonlocal::texthash(
 1826:         'modi' => 'Modify',
 1827:         'canc' => 'Cancel',
 1828:     );
 1829:     my ($typeorder,$types) = &blocktype_text();
 1830:     $r->print(&Apache::loncommon::start_data_table());
 1831:     $r->print(<<"END");
 1832:   <tr>
 1833:     <th>$ltext->{'dura'}</th>
 1834:     <th>$ltext->{'setb'}</th>
 1835:     <th>$ltext->{'even'}</th>
 1836:     <th>$ltext->{'blck'}</th>
 1837:     <th>$ltext->{'actn'}?</th>
 1838:   </tr>
 1839: END
 1840:     foreach my $record (sort(keys(%{$records}))) {
 1841:         my $onchange = 'onFocus="javascript:window.document.forms['.
 1842:                        "'blockform'].elements['modify_".$parmcount."'].".
 1843:                        'checked=true;"';
 1844:         my ($start,$end) = split(/____/,$record);
 1845:         my $startform = &Apache::lonhtmlcommon::date_setter('blockform','startdate_'.$parmcount,$start,$onchange);
 1846:         my $endform = &Apache::lonhtmlcommon::date_setter('blockform','enddate_'.$parmcount,$end,$onchange);
 1847: 	
 1848: 	my ($setuname,$setudom,$title,$blocks) = 
 1849: 	    &Apache::loncommon::parse_block_record($$records{$record});
 1850: 	$title = &HTML::Entities::encode($title,'"<>&');
 1851:         my $settername = 
 1852:            &Apache::loncommon::aboutmewrapper(
 1853:                            &Apache::loncommon::plainname($setuname,$setudom),
 1854:                            $setuname,$setudom);
 1855:         $r->print(&Apache::loncommon::start_data_table_row());
 1856:         $r->print(<<"END");
 1857:         <td>$ltext->{'star'}:&nbsp;$startform<br/>$ltext->{'endd'}:&nbsp;&nbsp;$endform</td>
 1858:         <td>$settername</td>
 1859:         <td><input type="text" name="title_$parmcount" size="15" value="$title" /><input type="hidden" name="key_$parmcount" value="$record" /></td>
 1860:         <td>
 1861: END
 1862:         foreach my $block (@{$typeorder}) {
 1863:             my $blockstatus = '';
 1864:             if ($blocks->{$block} eq 'on') {
 1865:                 $blockstatus = 'checked="true"';
 1866:             }
 1867:             $r->print('<label><input type="checkbox" name="'.$block.'_'.$parmcount.'" '.$blockstatus.' value="1" />'.$types->{$block}.'</label><br />');
 1868:         }
 1869:         $r->print(<<"END");
 1870:         </td>      
 1871:         <td><label>$lt{'modi'}?&nbsp;<input type="checkbox" name="modify_$parmcount" /></label><br /><label>$lt{'canc'}?&nbsp;&nbsp;<input type="checkbox" name="cancel_$parmcount" /></label>
 1872: END
 1873:         $r->print(&Apache::loncommon::end_data_table_row());
 1874:         $parmcount++;
 1875:     }
 1876:     $r->print(<<"END");
 1877: </table>
 1878: <br />
 1879: <br />
 1880: END
 1881:     return $parmcount;
 1882: }
 1883: 
 1884: sub display_addblocker_table {
 1885:     my ($r,$parmcount,$ltext) = @_;
 1886:     my $start = time;
 1887:     my $end = $start + (60 * 60 * 2); #Default is an exam of 2 hours duration.
 1888:     my $onchange = 'onFocus="javascript:window.document.forms['.
 1889:                    "'blockform'].elements['add_".$parmcount."'].".
 1890:                    'checked=true;"';
 1891:     my $startform = &Apache::lonhtmlcommon::date_setter('blockform','startdate_'.$parmcount,$start,$onchange);
 1892:     my $endform = &Apache::lonhtmlcommon::date_setter('blockform','enddate_'.$parmcount,$end,$onchange);
 1893:     my %lt = &Apache::lonlocal::texthash(
 1894:         'addb' => 'Add block',
 1895:         'exam' => 'e.g., Exam 1',
 1896:         'addn' => 'Add new communication blocking periods'
 1897:     );
 1898:     my ($typeorder,$types) = &blocktype_text();
 1899:     $r->print(<<"END");
 1900: <h4>$lt{'addn'}</h4> 
 1901: END
 1902:     $r->print(&Apache::loncommon::start_data_table());
 1903:     $r->print(<<"END");
 1904:    <tr>
 1905:      <th>$ltext->{'dura'}</th>
 1906:      <th>$ltext->{'even'} $lt{'exam'}</th>
 1907:      <th>$ltext->{'blck'}</th>
 1908:      <th>$ltext->{'actn'}?</th>
 1909:    </tr>
 1910: END
 1911:     $r->print(&Apache::loncommon::start_data_table_row());
 1912:     $r->print(<<"END");
 1913:      <td>$ltext->{'star'}:&nbsp;$startform<br />$ltext->{'endd'}:&nbsp;&nbsp;$endform</td>
 1914:      <td><input type="text" name="title_$parmcount" size="15" value="" /></td>
 1915:      <td>
 1916: END
 1917:     foreach my $block (@{$typeorder}) {
 1918:         $r->print('<label><input type="checkbox" name="'.$block.'_'.$parmcount.'" value="1" />'.$types->{$block}.'</label><br />');
 1919:      }
 1920:      $r->print(<<"END");
 1921:      </td> 
 1922:      <td><label>$lt{'addb'}?&nbsp;<input type="checkbox" name="add_$parmcount" value="1" /></label></td>
 1923: END
 1924:     $r->print(&Apache::loncommon::end_data_table_row());
 1925:     $r->print(&Apache::loncommon::end_data_table());
 1926:     return;
 1927: }
 1928: 
 1929: sub blocktype_text {
 1930:     my %types = &Apache::lonlocal::texthash(
 1931:         'com' => 'Messaging',
 1932:         'chat' => 'Chat',
 1933:         'boards' => 'Discussion',
 1934:         'port' => 'Portfolio',
 1935:         'groups' => 'Groups',
 1936:         'blogs' => 'Blogs',
 1937:     );
 1938:     my $typeorder = ['com','chat','boards','port','groups','blogs'];
 1939:     return ($typeorder,\%types);
 1940: }
 1941: 
 1942: # ----------------------------------------------------------- Display a message
 1943: 
 1944: sub displaymessage {
 1945:     my ($r,$msgid,$folder,$msgstatus)=@_;
 1946:     my $suffix=&Apache::lonmsg::foldersuffix($folder);
 1947:     my %blocked = ();
 1948:     my %setters = ();
 1949:     my $numblocked = 0;
 1950:     my $crstype = &Apache::loncommon::course_type();
 1951: 
 1952: # info to generate "next" and "previous" buttons and check if message is blocked
 1953:     my ($startblock,$endblock) = &Apache::loncommon::blockcheck(\%setters,'com');
 1954:     my @messages=&sortedmessages(\%blocked,$startblock,$endblock,\$numblocked,$folder,$msgstatus);
 1955:     if ( $blocked{$msgid} eq 'ON' ) {
 1956:         &printheader($r,'/adm/email',&mt('Display a Message'));
 1957:         $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.'));
 1958:         &build_block_table($r,$startblock,$endblock,\%setters);
 1959:         return;
 1960:     }
 1961:     if ($msgstatus eq '') {
 1962:         &statuschange($msgid,'read',$folder);
 1963:     }
 1964:     my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
 1965:     my %content=&Apache::lonmsg::unpackagemsg($message{$msgid});
 1966: 
 1967:     my $counter=0;
 1968:     $r->print('<pre>');
 1969:     my $escmsgid=&escape($msgid);
 1970:     foreach (@messages) {
 1971: 	if ($_->[5] eq $escmsgid){
 1972: 	    last;
 1973: 	}
 1974: 	$counter++;
 1975:     }
 1976:     $r->print('</pre>');
 1977:     my $number_of_messages = scalar(@messages); #subtract 1 for last index
 1978: # start output
 1979:     &printheader($r,'/adm/email?display='.&escape($msgid),'Display a Message','',$content{'baseurl'});
 1980:     my %courseinfo=&Apache::lonnet::coursedescription($content{'courseid'});
 1981: # Functions
 1982:     $r->print('<table border="2" width="100%"><tr bgcolor="#FFFFAA"><td>'.&mt('Functions').':</td>'.
 1983: 	      '<td><a href="/adm/email?replyto='.&escape($msgid).$sqs.
 1984: 	      '"><b>'.&mt('Reply').'</b></a></td>'.
 1985: 	      '<td><a href="/adm/email?forward='.&escape($msgid).$sqs.
 1986: 	      '"><b>'.&mt('Forward').'</b></a></td>'.
 1987: 	      '<td><a href="/adm/email?markunread='.&escape($msgid).$sqs.
 1988: 	      '"><b>'.&mt('Mark Unread').'</b></a></td>'.
 1989: 	      '<td><a href="/adm/email?markdel='.&escape($msgid).$sqs.
 1990: 	      '"><b>'.&mt('Delete').'</b></a></td>'.
 1991: 	      '<td><a href="/adm/email?'.$sqs.
 1992: 	      '"><b>'.&mt('Back to Folder Display').'</b></a></td>');
 1993:     if ($counter > 0){
 1994: 	$r->print('<td><a href="/adm/email?display='.$messages[$counter-1]->[5].$sqs.
 1995: 		  '"><b>'.&mt('Previous').'</b></a></td>');
 1996:     }
 1997:     if ($counter < $number_of_messages - 1){
 1998: 	$r->print('<td><a href="/adm/email?display='.$messages[$counter+1]->[5].$sqs.
 1999: 		  '"><b>'.&mt('Next').'</b></a></td>');
 2000:     }
 2001:     $r->print('</tr></table>');
 2002:     my $symb;
 2003:     if (defined($content{'symb'})) {
 2004:         $symb = $content{'symb'};
 2005:     } elsif (defined($content{'baseurl'})) {
 2006:         $symb=&Apache::lonnet::symbread($content{'baseurl'});
 2007:     }
 2008:     if ($env{'user.adv'}) {
 2009: 	$r->print('<table border="2" width="100%"><tr bgcolor="#FFAAAA"><td>'.&mt('Currently available actions (will open extra window)').':</td>');
 2010: 	if (&Apache::lonnet::allowed('vgr',$env{'request.course.id'})) {
 2011: 		$r->print('<td><b>'.&Apache::loncommon::track_student_link(&mt('View recent activity'),$content{'sendername'},$content{'senderdomain'},'check').'</b></td>');
 2012: 	    }
 2013: 	if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) && $symb) {
 2014: 	    $r->print('<td><b>'.&Apache::loncommon::pprmlink(&mt('Set/Change parameters'),$content{'sendername'},$content{'senderdomain'},$symb,'check').'</b></td>');
 2015: 	}
 2016: 	if (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}) && $symb) {
 2017: 	    $r->print('<td><b>'.&Apache::loncommon::pgrdlink(&mt('Set/Change grades'),$content{'sendername'},$content{'senderdomain'},$symb,'check').'</b></td>');
 2018: 	}
 2019: 	$r->print('</tr></table>');
 2020:     }
 2021:     my $tolist;
 2022:     my @recipients = ();
 2023:     for (my $i=0; $i<@{$content{'recuser'}}; $i++) {
 2024:         $recipients[$i] =  &Apache::loncommon::aboutmewrapper(
 2025:            &Apache::loncommon::plainname($content{'recuser'}[$i],
 2026:                                       $content{'recdomain'}[$i]),
 2027:               $content{'recuser'}[$i],$content{'recdomain'}[$i]).
 2028:        ' ('.$content{'recuser'}[$i].' at '.$content{'recdomain'}[$i].') ';
 2029:     }
 2030:     $tolist = join(', ',@recipients);
 2031:     my ($restitle,$baseurl,$refers_to);
 2032:     if (defined($content{'resource_title'})) {
 2033:         $restitle = $content{'resource_title'};
 2034:     } else {
 2035:         if (defined($content{'baseurl'})) {
 2036:             $restitle = &Apache::lonnet::gettitle($content{'baseurl'});
 2037:         }
 2038:     }
 2039:     if (defined($content{'baseurl'})) {
 2040:         $baseurl = &Apache::lonenc::check_encrypt($content{'baseurl'});
 2041:     }
 2042:     $r->print('<br /><b>'.&mt('Subject').':</b> '.$content{'subject'}.
 2043: 	      ($folder ne 'sent'?'<br /><b>'.&mt('From').':</b> '.
 2044: 	      &Apache::loncommon::aboutmewrapper(
 2045: 						 &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),
 2046: 						 $content{'sendername'},$content{'senderdomain'}).' ('.
 2047: 	      $content{'sendername'}.' at '.
 2048: 	      $content{'senderdomain'}.') ':'<br /><b>'.&mt('To').':</b> '.
 2049:               $tolist).
 2050: 	      ($content{'courseid'}?'<br /><b>'.&mt($crstype).':</b> '.$courseinfo{'description'}.
 2051: 	       ($content{'coursesec'}?' ('.&mt('Section').': '.$content{'coursesec'}.')':''):'').
 2052: 	      '<br /><b>'.&mt('Time').':</b> '.$content{'time'});
 2053:     if ($baseurl) {
 2054:         if (defined($content{'courseid'}) && defined($env{'request.course.id'})) {
 2055:             if ($content{'courseid'} eq $env{'request.course.id'}) {
 2056:                 my $symblink;
 2057:                 my $showsymb = &Apache::lonenc::check_decrypt($symb);
 2058:                 my $showurl = &Apache::lonenc::check_decrypt($baseurl);
 2059:                 my $encrypturl = &Apache::lonnet::EXT('resource.0.encrypturl',
 2060:                               $showsymb,$env{'user.domain'},$env{'user.name'});
 2061:                 if ($symb) {
 2062:                     if ($encrypturl =~ /^yes$/i && !$env{'request.role.adv'}) {
 2063:                         $showsymb = &Apache::lonenc::check_encrypt($symb);
 2064:                     }
 2065:                     $symblink = '?symb='.$showsymb;
 2066:                 }
 2067:                 if ($encrypturl =~ /^yes$/i && !$env{'request.role.adv'}) {
 2068:                     $showurl = $baseurl;
 2069:                 }
 2070:                 $r->print('<br /><b>'.&mt('Refers to').':</b> <a href="'.$showurl.$symblink.'">'.$restitle.'</a>');
 2071:                 $refers_to = 1;
 2072:             }
 2073:         }
 2074:         if (!$refers_to) {
 2075:             if ($baseurl =~ m-^/enc/-) {
 2076:                 if (defined($content{'courseid'})) {
 2077:                     if (!$env{'request.course.id'}) {
 2078:                         my $unencurl =
 2079:                            &Apache::lonenc::unencrypted($baseurl,
 2080:                                                         $content{'courseid'});
 2081:                         if ($unencurl ne '') {
 2082:                             if (&Apache::lonnet::allowed('bre',$unencurl)) {
 2083:                                 $r->print('<br /><b>'.&mt('Refers to').
 2084:                                           ':</b> <a href="'.$unencurl.'">'.
 2085:                                           $restitle.'</a>');
 2086:                             }
 2087:                         }
 2088:                     }
 2089:                 }
 2090:             } else {
 2091:                 if (&Apache::lonnet::allowed('bre',$baseurl)) {
 2092:                     $r->print('<br /><b>'.&mt('Refers to').
 2093:                               ':</b> <a href="'.$baseurl.
 2094:                               '">'.$restitle.'</a>');
 2095:                 }
 2096:             }
 2097:         }
 2098:     }
 2099:     $r->print('<p><pre>'.
 2100: 	      &Apache::lontexconvert::msgtexconverted($content{'message'},1).
 2101: 	      '</pre><hr />'.&displayresource(%content).'</p>');
 2102:     return;
 2103: }
 2104: 
 2105: # =========================================================== Show the citation
 2106: 
 2107: sub displayresource {
 2108:     my %content=@_;
 2109: #
 2110: # If the recipient is in the same course that the message was sent from and
 2111: # has sufficient privileges, show "all details," else show citation
 2112: #
 2113:     if (($env{'request.course.id'} eq $content{'courseid'})
 2114:      && (&Apache::lonnet::allowed('vgr',$content{'courseid'}))) {
 2115:         my $symb;
 2116:         if (defined($content{'symb'})) {
 2117:             $symb = $content{'symb'};
 2118:         } else { 
 2119: 	    $symb=&Apache::lonnet::symbread($content{'baseurl'});
 2120:         }
 2121: # Could not get a symb, give up
 2122: 	unless ($symb) { return $content{'citation'}; }
 2123: # Have a symb, can render
 2124: 	return '<h2>'.&mt('Current attempts of student (if applicable)').'</h2>'.
 2125: 	    &Apache::loncommon::get_previous_attempt($symb,
 2126: 						     $content{'sendername'},
 2127: 						     $content{'senderdomain'},
 2128: 						     $content{'courseid'}).
 2129: 	    '<hr /><h2>'.&mt('Current screen output (if applicable)').'</h2>'.
 2130: 	    &Apache::loncommon::get_student_view($symb,
 2131: 						 $content{'sendername'},
 2132: 						 $content{'senderdomain'},
 2133: 						 $content{'courseid'}).
 2134: 	    '<h2>'.&mt('Correct Answer(s) (if applicable)').'</h2>'.
 2135: 	    &Apache::loncommon::get_student_answers($symb,
 2136: 						    $content{'sendername'},
 2137: 						    $content{'senderdomain'},
 2138: 						    $content{'courseid'});
 2139:     } elsif ($env{'user.adv'}) {
 2140: 	return $content{'citation'};
 2141:     }
 2142:     return '';
 2143: }
 2144: 
 2145: # ================================================================== The Header
 2146: 
 2147: sub header {
 2148:     my ($r,$title,$baseurl)=@_;
 2149:     
 2150:     my $extra = &Apache::loncommon::studentbrowser_javascript();
 2151:     if ($baseurl) {
 2152: 	$extra .= "<base href=\"".&Apache::lonnet::absolute_url()."/$baseurl\" />";
 2153:     }
 2154:     $r->print(&Apache::loncommon::start_page('Communication and Messages',
 2155:  					$extra));
 2156:     $r->print(&Apache::lonhtmlcommon::breadcrumbs
 2157:      		(($title?$title:'Communication and Messages')));
 2158: }
 2159: 
 2160: # ---------------------------------------------------------------- Print header
 2161: 
 2162: sub printheader {
 2163:     my ($r,$url,$desc,$title,$baseurl)=@_;
 2164:     &Apache::lonhtmlcommon::add_breadcrumb
 2165: 	({href=>$url,
 2166: 	  text=>$desc});
 2167:     &header($r,$title,$baseurl);
 2168: }
 2169: 
 2170: # ------------------------------------------------------------ Store the comment
 2171: 
 2172: sub storecomment {
 2173:     my ($r)=@_;
 2174:     my $msgtxt=&Apache::lonfeedback::clear_out_html($env{'form.message'});
 2175:     my $cleanmsgtxt='';
 2176:     foreach my $line (split(/[\n\r]/,$msgtxt)) {
 2177: 	unless ($line=~/^\s*(\>|\&gt\;)/) {
 2178: 	    $cleanmsgtxt.=$line."\n";
 2179: 	}
 2180:     }
 2181:     my $key=&escape($env{'form.baseurl'}).'___'.time;
 2182:     &Apache::lonnet::put('nohist_stored_comments',{ $key => $cleanmsgtxt });
 2183: }
 2184: 
 2185: sub storedcommentlisting {
 2186:     my ($r)=@_;
 2187:     my %msgs=&Apache::lonnet::dump('nohist_stored_comments',undef,undef,
 2188:        '^'.&escape(&escape($env{'form.showcommentbaseurl'})));
 2189:     $r->print(&Apache::loncommon::start_page('Stored Comment Listing',undef,
 2190: 					     {'onlybody' => 1}));
 2191:     if ((keys %msgs)[0]=~/^error\:/) {
 2192: 	$r->print(&mt('No stored comments yet.'));
 2193:     } else {
 2194: 	my $found=0;
 2195: 	foreach my $key (sort(keys(%msgs))) {
 2196: 	    $r->print("\n".$msgs{$key}."<hr />");
 2197: 	    $found=1;
 2198: 	}
 2199: 	unless ($found) {
 2200: 	    $r->print(&mt('No stored comments yet for this resource.'));
 2201: 	}
 2202:     }
 2203: }
 2204: 
 2205: # ---------------------------------------------------------------- Send an email
 2206: 
 2207: sub sendoffmail {
 2208:     my ($r,$folder)=@_;
 2209:     my $suffix=&Apache::lonmsg::foldersuffix($folder);
 2210:     my $sendstatus='';
 2211:     my %specialmsg_status;
 2212:     my $numspecial = 0;
 2213:     my ($cdom,$cnum,$group);
 2214:     if (exists($env{'form.group'})) {
 2215:         $group = $env{'form.group'};
 2216:     }
 2217:     if (exists($env{'request.course.id'})) {
 2218:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2219:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2220:     }
 2221:     if ($env{'form.send'}) {
 2222:         if (!$env{'form.multiforward'}) { 
 2223:             if ($group eq '') {
 2224: 	        &printheader($r,'','Messages being sent.');
 2225:             } else {
 2226:                 $r->print(&groupmail_header('sending',$group));
 2227:             }
 2228:         }
 2229: 	$r->rflush();
 2230: 	my %content=();
 2231: 	undef %content;
 2232: 	if ($env{'form.forwid'}) {
 2233: 	    my $msgid=$env{'form.forwid'};
 2234: 	    my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
 2235: 	    %content=&Apache::lonmsg::unpackagemsg($message{$msgid},1);
 2236: 	    &statuschange($msgid,'forwarded',$folder);
 2237: 	    $env{'form.message'}.="\n\n-- Forwarded message --\n\n".
 2238: 		$content{'message'};
 2239: 	}
 2240: 	if ($env{'form.replyid'}) {
 2241: 	    my $msgid=$env{'form.replyid'};
 2242: 	    my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
 2243: 	    %content=&Apache::lonmsg::unpackagemsg($message{$msgid},1);
 2244: 	    &statuschange($msgid,'replied',$folder);
 2245: 	}
 2246: 
 2247: 	my @to =
 2248: 	    &Apache::loncommon::get_env_multiple('form.selectedusers_forminput');
 2249: 	my $mode = $env{'form.sendmode'};
 2250: 
 2251: 	my %toaddr;
 2252: 	if (@to) {
 2253: 	    foreach my $dest (@to) {
 2254: 		my ($user,$domain) = split(/:/, $dest);
 2255: 		if (($user ne '') && ($domain ne '')) {
 2256: 		    my $address = $user.":".$domain; # How the code below expects it.
 2257: 		    $toaddr{$address} = '';
 2258: 		}
 2259: 	    }
 2260: 	}
 2261: 
 2262: 	if ($env{'form.sendmode'} eq 'group') {
 2263: 	     foreach my $address (keys(%env)) {
 2264: 	 	if ($address=~/^form\.send\_to\_\&\&\&[^\&]*\&\&\&\_(.+)$/) {
 2265: 	 	    $toaddr{$1}='';
 2266: 	 	}
 2267: 	    }
 2268: 	} elsif ($env{'form.sendmode'} eq 'upload') {
 2269: 	    foreach my $line (split(/[\n\r\f]+/,$env{'form.upfile'})) {
 2270:                 my ($rec,$txt) = ($line =~ /^([^:]+:[^:]+):(.*)$/);
 2271: 		if ($txt) {
 2272:                     $rec =~ s/^\s+//;
 2273:                     $rec =~ s/\s+$//;
 2274: 		    $toaddr{$rec}.=$txt."\n";
 2275: 		}
 2276: 	    }
 2277: 	} else {
 2278: 	    if (($env{'form.recuname'} ne '') && ($env{'form.recdomain'} ne '')) {
 2279: 		$toaddr{$env{'form.recuname'}.':'.$env{'form.recdomain'}}='';
 2280: 	    }
 2281: 	}
 2282: 	if ($env{'form.additionalrec'}) {
 2283: 	    foreach my $rec (split(/\,/,$env{'form.additionalrec'})) {
 2284: 		my ($auname,$audom)=split(/:/,$rec);
 2285: 		if (($auname ne "") && ($audom ne "")) {
 2286: 		    $toaddr{$auname.':'.$audom}='';
 2287: 		}
 2288: 	    }
 2289: 	}
 2290: 
 2291:         my $savemsg;
 2292:         my $msgtype;
 2293:         my %sentmessage;
 2294:         my $msgsubj=&Apache::lonfeedback::clear_out_html($env{'form.subject'},
 2295: 							 undef,1);
 2296:         if ((($env{'form.critmsg'}) || ($env{'form.sendbck'})) &&
 2297:             (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
 2298: 	     || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
 2299: 					 '/'.$env{'request.course.sec'})
 2300: 	     )) {
 2301:             $savemsg=&Apache::lonfeedback::clear_out_html($env{'form.message'},1);
 2302:             $msgtype = 'critical';
 2303:         } else {
 2304:             $savemsg=&Apache::lonfeedback::clear_out_html($env{'form.message'});
 2305:         }
 2306: 	
 2307: 	foreach my $address (sort(keys(%toaddr))) {
 2308: 	    my ($recuname,$recdomain)=split(/\:/,$address);
 2309:             my $msgtxt = $savemsg;
 2310: 	    if ($toaddr{$address}) { $msgtxt.='<hr />'.$toaddr{$address}; }
 2311: 	    my @thismsg;
 2312: 	    if ($msgtype eq 'critical') {
 2313: 		$r->print(&mt('Sending critical message').' '.
 2314:                               $recuname.':'.$recdomain.': ');
 2315: 		@thismsg=
 2316: 		    &Apache::lonmsg::user_crit_msg($recuname,$recdomain,
 2317: 						   $msgsubj,$msgtxt,
 2318: 						   $env{'form.sendbck'},
 2319: 						   $env{'form.permanent'},
 2320: 						   \$sentmessage{$address});
 2321: 	    } else {
 2322: 		$r->print(&mt('Sending').' '.$recuname.':'.$recdomain.': ');
 2323: 		@thismsg=
 2324: 		    &Apache::lonmsg::user_normal_msg($recuname,$recdomain,
 2325: 						     $msgsubj,$msgtxt,
 2326: 						     $content{'citation'},
 2327: 						     undef,undef,
 2328: 						     $env{'form.permanent'},
 2329: 						     \$sentmessage{$address});
 2330:             }
 2331: 	    if (($env{'request.course.id'}) && (($msgtype eq 'critical') || 
 2332:                                          ($env{'form.sendmode'} eq 'group'))) {
 2333: 	        $specialmsg_status{$recuname.':'.$recdomain} =
 2334: 		    join(' ',@thismsg);
 2335: 		foreach my $result (@thismsg) {
 2336: 		    if ($result eq 'ok' || $result eq 'con_delayed') {
 2337: 			$numspecial++;
 2338: 		    }
 2339: 		}
 2340: 	    }
 2341: 	    $sendstatus.=' '.join(' ',@thismsg);
 2342: 	}
 2343:         if (($env{'request.course.id'}) && (($env{'form.sendmode'} eq 'group')
 2344:                                               || ($msgtype eq 'critical'))) {
 2345:             my $subj_prefix;
 2346:             if ($msgtype eq 'critical') {
 2347:                 $subj_prefix = 'Critical.';
 2348:             } else {
 2349:                 $subj_prefix = 'Broadcast.';
 2350:             }
 2351:             my ($specialmsgid,$specialresult);
 2352:             my $course_str = &escape('['.$cnum.':'.$cdom.']');
 2353: 
 2354:             if ($numspecial) {
 2355:                 $specialresult = &Apache::lonmsg::user_normal_msg_raw($cnum,$cdom,$subj_prefix.
 2356:                     ' '.$course_str,$savemsg,undef,undef,undef,
 2357:                     undef,undef,\$specialmsgid);
 2358:                 $specialmsgid = &unescape($specialmsgid);
 2359:             }
 2360:             if ($specialresult eq 'ok') {
 2361:                 my $record_sent;
 2362:                 my @recusers;
 2363:                 my @recudoms;
 2364:                 my ($stamp,$crssubj,$msgname,$msgdom,$msgcount,$context,$pid) =
 2365: 		    split(/\:/,&unescape($specialmsgid));
 2366: 
 2367:                 foreach my $recipient (sort(keys(%toaddr))) {
 2368:                     if ($specialmsg_status{$recipient} eq 'ok') {
 2369:                         my $usersubj = $subj_prefix.'['.$recipient.']';
 2370:                         my $usermsgid = 
 2371: 			    &Apache::lonmsg::buildmsgid($stamp,$usersubj,
 2372: 							$msgname,$msgdom,
 2373: 							$msgcount,$context,
 2374: 							$pid);
 2375:                         &Apache::lonmsg::user_normal_msg_raw($cnum,$cdom,$subj_prefix.
 2376:                                              ' ['.$recipient.']',$msgsubj,undef,
 2377:                         undef,undef,undef,$usermsgid,undef,undef,$specialmsgid);
 2378:                         my ($uname,$udom) = split(/:/,$recipient);
 2379:                         push(@recusers,$uname);
 2380:                         push(@recudoms,$udom);
 2381:                     }
 2382:                 }
 2383:                 if (@recusers) {
 2384:                     my $specialmessage;
 2385:                     my $sentsubj = 
 2386: 			$subj_prefix.' ('.$numspecial.' sent) '.$msgsubj;
 2387:                     $sentsubj = &HTML::Entities::encode($sentsubj,'<>&"');
 2388:                     my $sentmsgid = 
 2389: 			&Apache::lonmsg::buildmsgid($stamp,$sentsubj,$msgname,
 2390: 						    $msgdom,$msgcount,$context,
 2391: 						    $pid);
 2392:                     ($specialmsgid,$specialmessage) = &Apache::lonmsg::packagemsg($msgsubj,$savemsg,
 2393:                             undef,undef,undef,\@recusers,\@recudoms,$sentmsgid);
 2394:                     $record_sent = &Apache::lonmsg::store_sent_mail($specialmsgid,$specialmessage);
 2395:                 }
 2396:             } else {
 2397:                 &Apache::lonnet::logthis('Failed to create record of critical message or broadcast in '.$env{'course.'.$env{'request.course.id'}.'.num'}.' at '.$env{'course.'.$env{'request.course.id'}.'.domain'}.' - no msgid generated');
 2398:             }
 2399:         }
 2400:     } else {
 2401: 	&printheader($r,'','No messages sent.'); 
 2402:     }
 2403:     if (!$env{'form.multiforward'}) { 
 2404:         if ($sendstatus=~/^(\s*(?:ok|con_delayed)\s*)*$/) {
 2405: 	    $r->print('<br /><span class="LC_success">'.&mt('Completed.').
 2406:                       '</span>');
 2407: 	    if ($env{'form.displayedcrit'}) {
 2408: 	        &discrit($r);
 2409:             }
 2410:             if ($group ne '') {
 2411:                 $r->print(&groupmail_sent($group,$cdom,$cnum)); 
 2412: 	    } else {
 2413: 	        &Apache::loncommunicate::menu($r);
 2414: 	    }
 2415:         } else {
 2416: 	    $r->print('<p><span class="LC_error">'.&mt('Could not deliver message').'</span> '.
 2417: 		  &mt('Please use the browser "Back" button and correct the recipient addresses '."($sendstatus)").'</p>');
 2418:         }
 2419:     }
 2420:     return $sendstatus;
 2421: }
 2422: 
 2423: # ===================================================================== Handler
 2424: 
 2425: sub handler {
 2426:     my $r=shift;
 2427: 
 2428: # ----------------------------------------------------------- Set document type
 2429:     
 2430:     &Apache::loncommon::content_type($r,'text/html');
 2431:     $r->send_http_header;
 2432:     
 2433:     return OK if $r->header_only;
 2434:     
 2435: # --------------------------- Get query string for limited number of parameters
 2436:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 2437:         ['display','replyto','forward','markread','markdel','markunread',
 2438:          'sendreply','compose','sendmail','critical','recname','recdom',
 2439:          'recordftf','sortedby','block','folder','startdis','interdis',
 2440: 	 'showcommentbaseurl','dismode','group','subject','text','ref',
 2441:          'msgstatus']);
 2442:     $sqs='&sortedby='.$env{'form.sortedby'};
 2443: 
 2444: # ------------------------------------------------------ They checked for email
 2445:     unless ($env{'form.block'}) {
 2446:         &Apache::lonnet::put('email_status',{'recnewemail'=>0});
 2447:     }
 2448: 
 2449: # ----------------------------------------------------------------- Breadcrumbs
 2450: 
 2451:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 2452:     &Apache::lonhtmlcommon::add_breadcrumb
 2453:         ({href=>"/adm/communicate",
 2454:           text=>"Communication/Messages",
 2455:           faq=>12,bug=>'Communication Tools',});
 2456: 
 2457: # ------------------------------------------------------------------ Get Folder
 2458: 
 2459:     my $folder=$env{'form.folder'};
 2460:     unless ($folder) { 
 2461: 	$folder=''; 
 2462:     } else {
 2463: 	$sqs.='&folder='.&escape($folder);
 2464:     }
 2465: # ------------------------------------------------------------ Get Display Mode
 2466: 
 2467:     my $dismode=$env{'form.dismode'};
 2468:     unless ($dismode) { 
 2469: 	$dismode=''; 
 2470:     } else {
 2471: 	$sqs.='&amp;dismode='.&escape($dismode);
 2472:     }
 2473: 
 2474: # --------------------------------------------------------------------- Display
 2475:     my $msgstatus = $env{'form.msgstatus'};
 2476:     $startdis=$env{'form.startdis'};
 2477:     if ($startdis ne '') {
 2478:         $startdis--;
 2479:     }
 2480:     unless ($startdis) { $startdis=0; }
 2481: 
 2482:     if ($env{'form.firstview'}) {
 2483: 	$startdis=0;
 2484:     }
 2485:     if ($env{'form.lastview'}) {
 2486: 	$startdis=-1;
 2487:     }
 2488:     if ($env{'form.prevview'}) {
 2489: 	$startdis--;
 2490:     }
 2491:     if ($env{'form.nextview'}) {
 2492: 	$startdis++;
 2493:     }
 2494:     my $postedstartdis=$startdis+1;
 2495:     $sqs.='&startdis='.$postedstartdis;
 2496: 
 2497: # --------------------------------------------------------------- Render Output
 2498: 
 2499:     if ($env{'form.display'}) {
 2500: 	&displaymessage($r,$env{'form.display'},$folder,$msgstatus);
 2501:     } elsif ($env{'form.replyto'}) {
 2502: 	&compout($r,'',$env{'form.replyto'},undef,undef,$folder,$dismode);
 2503:     } elsif ($env{'form.confirm'}) {
 2504: 	&printheader($r,'','Confirmed Receipt');
 2505: 	my $replying = 0;
 2506: 	foreach my $envkey (keys(%env)) {
 2507: 	    if ($envkey=~/^form\.rec\_(.*)$/) {
 2508: 		$r->print('<b>'.&mt('Confirming Receipt').':</b> '.
 2509: 			  &Apache::lonmsg::user_crit_received($1).'<br>');
 2510: 	    }
 2511: 	    if ($envkey=~/^form\.reprec\_(.*)$/) {
 2512: 		my $msgid=$1;
 2513: 		$r->print('<b>'.&mt('Confirming Receipt').':</b> '.
 2514: 			  &Apache::lonmsg::user_crit_received($msgid).'<br>');
 2515: 		&compout($r,'','','',$msgid);
 2516: 		$replying = 1;
 2517: 	    }
 2518: 	}
 2519: 	if (!$replying) {
 2520: 	    &discrit($r);
 2521: 	}
 2522:     } elsif ($env{'form.critical'}) {
 2523: 	&printheader($r,'','Displaying Critical Messages');
 2524: 	&discrit($r);
 2525:     } elsif ($env{'form.forward'}) {
 2526: 	&compout($r,$env{'form.forward'},undef,undef,undef,$folder);
 2527:     } elsif ($env{'form.markdel'}) {
 2528: 	&printheader($r,'','Deleted Message');
 2529: 	my ($result,$msg) = 
 2530: 	    &statuschange($env{'form.markdel'},'deleted',$folder);
 2531: 	if (!$result) {
 2532: 	    $r->print('<p class="LC_error">'.
 2533: 		      &mt('Failed to delete the message.').'</p>'.
 2534: 		      '<p class="LC_error">'.$msg."</p>\n");
 2535: 	}
 2536: 	&Apache::loncommunicate::menu($r);
 2537: 	&disall($r,($folder?$folder:$dismode),$msgstatus);
 2538:     } elsif ($env{'form.markedaction'} eq 'markedforward') {
 2539:         my $total = 0;
 2540:         my @to_forward = &Apache::loncommon::get_env_multiple('form.delmark');
 2541:         foreach my $msgid (@to_forward) {
 2542:             &statuschange(&unescape($msgid),'forwarded',$folder);
 2543:             $total ++;
 2544:         }
 2545:         if ($total > 0) {
 2546:             &compout($r,undef,undef,undef,undef,$folder,$dismode,$total);
 2547:         }
 2548:     } elsif ($env{'form.markedaction'} eq 'markedread') {
 2549:         my $total = 0;
 2550:         my @to_markread = &Apache::loncommon::get_env_multiple('form.delmark');
 2551:         foreach my $msgid (@to_markread) {
 2552:             &statuschange(&unescape($msgid),'read',$folder);
 2553:             $total ++;
 2554:         }
 2555:         &printheader($r,'','Marked Messages Read');
 2556:         $r->print(&mt('Marked [_1] message(s) read',$total).'<p>');
 2557:         &Apache::loncommunicate::menu($r);
 2558:         &disall($r,($folder?$folder:$dismode),$msgstatus);
 2559:     } elsif ($env{'form.markedaction'} eq 'markedunread') {
 2560:         my $total = 0;
 2561:         my @to_markunread = &Apache::loncommon::get_env_multiple('form.delmark');
 2562:         foreach my $msgid (@to_markunread) {
 2563:             &statuschange(&unescape($msgid),'new',$folder);
 2564:             $total ++;
 2565:         }
 2566:         &printheader($r,'','Marked Messages Unread');
 2567:         $r->print(&mt('Marked [_1] message(s) unread',$total).'<p>');
 2568:         &Apache::loncommunicate::menu($r);
 2569:         &disall($r,($folder?$folder:$dismode),$msgstatus);
 2570:     } elsif ($env{'form.markedaction'} eq 'markedmove') {
 2571:         my $destfolder = $env{'form.movetofolder'};
 2572:         my %gotfolders = &Apache::lonmsg::get_user_folders();
 2573:         &printheader($r,'','Moved Messages');
 2574:         if (!defined($gotfolders{$destfolder})) {
 2575:             $r->print(&mt('Destination folder [_1] is not a valid folder',
 2576:                       $destfolder));
 2577:         } else {
 2578: 	    my ($total,$failed,@failed_msg)=(0,0);
 2579:             my @to_move = &Apache::loncommon::get_env_multiple('form.delmark');
 2580:             foreach my $msgid (@to_move) {
 2581: 	        my ($result,$msg) = &movemsg(&unescape($msgid),$folder,
 2582: 			                     $env{'form.movetofolder'});
 2583: 	        if ($result) {
 2584: 		    $total++;
 2585: 	        } else {
 2586: 		    $failed++;
 2587: 		    push(@failed_msg,$msg);
 2588: 	        }
 2589: 	    }
 2590: 	    if ($failed) {
 2591: 	        $r->print('<p class="LC_error">
 2592:                           '.&mt('Failed to move [_1] message(s)',$failed).
 2593: 		      '</p>');
 2594: 	        $r->print('<p class="LC_error">'.
 2595: 	   	          join("</p>\n<p class=\"LC_error\">",@failed_msg).
 2596: 		          "</p>\n");
 2597: 	    }
 2598: 	    $r->print(&mt('Moved [_1] message(s)',$total).'<p>');
 2599:         }
 2600: 	&Apache::loncommunicate::menu($r);
 2601: 	&disall($r,($folder?$folder:$dismode),$msgstatus);
 2602:     } elsif ($env{'form.markedaction'} eq 'markeddel') {
 2603: 	my ($total,$failed,@failed_msg)=(0,0);
 2604:         my @to_delete = &Apache::loncommon::get_env_multiple('form.delmark');
 2605:         foreach my $msgid (@to_delete) {
 2606: 	    my ($result,$msg) = &statuschange(&unescape($msgid),'deleted', 
 2607: 				              $folder);
 2608: 	    if ($result) {
 2609: 	        $total++;
 2610: 	    } else {
 2611: 	        $failed++;
 2612: 		push(@failed_msg,$msg);
 2613: 	    }
 2614: 	}
 2615: 	&printheader($r,'','Deleted Messages');
 2616: 	if ($failed) {
 2617: 	    $r->print('<p class="LC_error">
 2618:                           '.&mt('Failed to delete [_1] message(s)',$failed).
 2619: 		      '</p>');
 2620: 	    $r->print('<p class="LC_error">'.
 2621: 		      join("</p>\n<p class=\"LC_error\">",@failed_msg).
 2622: 		      "</p>\n");
 2623: 	}
 2624: 	$r->print(&mt('Deleted [_1] message(s)',$total).'<p>');
 2625: 	&Apache::loncommunicate::menu($r);
 2626: 	&disall($r,($folder?$folder:$dismode),$msgstatus);
 2627:     } elsif ($env{'form.markunread'}) {
 2628: 	&printheader($r,'','Marked Message as Unread');
 2629: 	&statuschange($env{'form.markunread'},'new');
 2630: 	&Apache::loncommunicate::menu($r);
 2631: 	&disall($r,($folder?$folder:$dismode),$msgstatus);
 2632:     } elsif ($env{'form.compose'}) {
 2633: 	&compout($r,'','',$env{'form.compose'});
 2634:     } elsif ($env{'form.recordftf'}) {
 2635: 	&facetoface($r,$env{'form.recordftf'});
 2636:     } elsif ($env{'form.block'}) {
 2637:         &examblock($r,$env{'form.block'});
 2638:     } elsif ($env{'form.sendmail'}) {
 2639:         if ($env{'form.multiforward'}) {
 2640:             &printheader($r,'','Messages being sent.');
 2641:             my $fixed_subj = $env{'form.subject'};
 2642:             my $suffix=&Apache::lonmsg::foldersuffix($folder);
 2643:             my (%sendresult,%forwardok,%forwardfail,$fwdcount);
 2644:             my @to_forward = &Apache::loncommon::get_env_multiple('form.delmark');
 2645:             foreach my $item (@to_forward) {
 2646:                 my $msgid=&unescape($item);
 2647:                 my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
 2648:                 my %content=&Apache::lonmsg::unpackagemsg($message{$msgid},1);
 2649:                 if ($env{'form.showorigsubj'}) {
 2650:                     $env{'form.subject'} = $fixed_subj.$content{'subject'};
 2651:                 } else {
 2652:                     $env{'form.subject'} = '';
 2653:                 }
 2654:                 my $uname = $content{'sendername'};
 2655:                 my $udom = $content{'senderdomain'};
 2656:                 &statuschange($msgid,'forwarded',$folder);
 2657:                 if ($env{'form.showorigsender'}) {
 2658:                     $env{'form.message'} = $env{'form.msgheader'}.' '.
 2659:                         &Apache::loncommon::plainname($uname,$udom).' ('.
 2660:                                            $uname.':'.$udom.')';
 2661:                 }
 2662:                 $env{'form.message'} .= "\n\n-- Forwarded message --\n\n".
 2663:                                         $content{'message'};
 2664:                 $fwdcount ++;
 2665:                 $r->print($fwdcount.': '); 
 2666:                 $sendresult{$msgid} = &sendoffmail($r,$folder);
 2667:                 $r->print('<br />');
 2668:             }
 2669:             foreach my $key (keys(%sendresult)) {
 2670:                 if ($sendresult{$key} =~/^(\s*(?:ok|con_delayed)\s*)*$/) {
 2671:                     $forwardok{$key} = $sendresult{$key};
 2672:                 } else {
 2673:                     $forwardfail{$key} = $sendresult{$key}; 
 2674:                 }
 2675:             }
 2676:             if (keys(%forwardok) > 0) {
 2677:                 my $count = keys(%forwardok);
 2678:                 $r->print('<br /><span class="LC_success">'.
 2679:                           &mt('[quant,_1,message] forwarded.',$count).
 2680:                           '</span>');
 2681:             }
 2682:             if (keys(%forwardfail) > 0) {
 2683:                 my $count = keys(%forwardfail);
 2684:                 $r->print('<p><span class="LC_error">'.
 2685:                           &mt('Could not forward [quant,_1,message].',$count).
 2686:                           '</span> ');
 2687:                 foreach my $key (keys(%forwardfail)) {
 2688:                     $r->print(&mt('Could not deliver forwarded message.').'</span> '.
 2689:                               &mt('The recipient addresses may need to be corrected').' ('.$forwardfail{$key}.').<br /><br />');
 2690:                 }
 2691:             }
 2692:             &Apache::loncommunicate::menu($r);
 2693:         } else {
 2694: 	    &sendoffmail($r,$folder);
 2695:         }
 2696: 	if ($env{'form.storebasecomment'}) {
 2697: 	    &storecomment($r);
 2698:         }
 2699: 	if (($env{'form.rsspost'}) && ($env{'request.course.id'})) {
 2700: 	        &Apache::lonrss::addentry($env{'course.'.$env{'request.course.id'}.'.num'},
 2701: 				      $env{'course.'.$env{'request.course.id'}.'.domain'},
 2702: 				      'Course_Announcements',
 2703: 				      $env{'form.subject'},
 2704: 				      $env{'form.message'},'/adm/communicate','public');
 2705: 	}
 2706: 	if ((!exists($env{'form.group'})) && (!$env{'form.displayedcrit'})) {
 2707: 	    &disall($r,($folder?$folder:$dismode),$msgstatus);
 2708: 	}
 2709:     } elsif ($env{'form.newfolder'}) {
 2710: 	&printheader($r,'','New Folder');
 2711:         my $showfolder = $env{'form.newfolder'};
 2712: 	my ($makeresult,$warning) = &makefolder($env{'form.newfolder'});
 2713:         if ($makeresult eq 'ok') {
 2714:             $r->print(&mt('Mail folder "[_1]" created.',$showfolder).'<br />');
 2715:         } else {
 2716:             $r->print(&mt('Creation failed.').' '.$makeresult.'<br />'.
 2717:                       $warning);
 2718:             $showfolder = $folder;
 2719:         }
 2720:         &Apache::loncommunicate::menu($r);
 2721: 	&disall($r,$showfolder,$msgstatus);
 2722:     } elsif ($env{'form.showcommentbaseurl'}) {
 2723: 	&storedcommentlisting($r);
 2724:     } elsif ($env{'form.folderaction'} eq 'delete') {
 2725:         &printheader($r,'','Deleted Folder');
 2726:         my $showfolder = '';
 2727:         my $delresult = &deletefolder($folder);
 2728:         if ($delresult eq 'ok') {
 2729:             $r->print(&mt('Mail folder "[_1]" deleted.',$folder).'<br />');
 2730:             $env{'form.folder'} = '';
 2731:         } else {
 2732:             $r->print(&mt('Deletion failed.').' '.$delresult.'<br />');
 2733:             $showfolder = $folder;
 2734:         }
 2735:         &Apache::loncommunicate::menu($r);
 2736:         &disall($r,$showfolder,$msgstatus);
 2737:     } elsif ($env{'form.folderaction'} eq 'rename') {
 2738:         &printheader($r,'','Renamed Folder');
 2739:         my $showfolder = $env{'form.renamed'};
 2740:         my $renresult = &renamefolder($folder);
 2741:         if ($renresult eq 'ok') {
 2742:             $r->print(&mt('Mail folder "[_1]" renamed "[_2]".',$folder,$showfolder).'<br />');
 2743:         } else {
 2744:             $r->print(&mt('Renaming failed.').' '.$renresult.'<br />');
 2745:             $showfolder = $folder;
 2746:         }
 2747:         &Apache::loncommunicate::menu($r);
 2748:         &disall($r,$showfolder,$msgstatus);
 2749:     } else {
 2750: 	&printheader($r,'','Display All Messages');
 2751: 	&Apache::loncommunicate::menu($r);
 2752: 	&disall($r,($folder?$folder:$dismode),$msgstatus);
 2753:     }
 2754:     $r->print(&Apache::loncommon::end_page());
 2755:     return OK;
 2756: }
 2757: # ================================================= Main program, reset counter
 2758: 
 2759: =pod
 2760: 
 2761: =back
 2762: 
 2763: =cut
 2764: 
 2765: 1; 
 2766: 
 2767: __END__
 2768: 

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