File:  [LON-CAPA] / loncom / interface / lonmsgdisplay.pm
Revision 1.196: download - view: text, annotated - select for diffs
Tue Jan 18 17:33:13 2022 UTC (2 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Bug 6955
 -  If IP-based blocking set in domain config is in effect for user's
    current IP address, and 'Messaging 'is among blocked functions:
   (a) 'Send Feedback' (in course context), for resource(s) which allow it
       is only messaging mechanism available to users with out 'evb' priv.
   (b) Subject and Content for messages sent to instructor(s) via 'Send Feedback'
       are replaced in user's Sent Folder with: "Not shown due to IP block".

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

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