File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.173.2.2: download - view: text, annotated - select for diffs
Mon Jun 19 09:36:14 2006 UTC (17 years, 11 months ago) by albertel
Branches: version_2_1_X
Diff to branchpoint 1.173: preferred, unified
- backport lonmsg.pm 1.185 lonmsgdisplay 1.31

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

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