File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.142: download - view: text, annotated - select for diffs
Sun May 15 01:11:32 2005 UTC (19 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
COM: still forgetful about which folder I was in
GRDS: Added "Grading" to the Validate Button (confused me at first)
GRDS: Able to override the don't-reset-correct safeguard with checkbox

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

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