File:  [LON-CAPA] / loncom / interface / lonmsgdisplay.pm
Revision 1.64: download - view: text, annotated - select for diffs
Wed Jan 17 18:05:57 2007 UTC (17 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_3_1, HEAD
Fix bug 5130.

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

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