File:  [LON-CAPA] / loncom / interface / lonmsgdisplay.pm
Revision 1.68: download - view: text, annotated - select for diffs
Thu Mar 1 09:30:58 2007 UTC (17 years, 2 months ago) by www
Branches: MAIN
CVS tags: HEAD
Style police needs to replace all instances

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

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