File:  [LON-CAPA] / loncom / interface / lonmsgdisplay.pm
Revision 1.136: download - view: text, annotated - select for diffs
Mon Oct 12 08:01:08 2009 UTC (14 years, 7 months ago) by amueller
Branches: MAIN
CVS tags: HEAD
-lonaboutme, lontemplate, loncommon, lonmsgdisplay: HTML Validation
-lonaboutme: new delimiter fro quoting the image tag, because from this line I lost the correct
   syntax highlighting for my favorite vim-editor.
-lonmsgdisplay: put target in the argument list of disfacetoface function, to force that I'm interested in a
 tex target. When printing lonaboutme page with facetoface discussion env{form.grade_target} has an empty value.

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

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