File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.175: download - view: text, annotated - select for diffs
Wed Mar 15 17:05:00 2006 UTC (18 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#4699 - checking section 1 was also checking 10 11 etc

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

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