File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.141: download - view: text, annotated - select for diffs
Mon Apr 11 21:51:43 2005 UTC (19 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: version_1_99_0_tmcc, HEAD
Adding course_id to msgid for LON-CAPA COM messages (uses course context of sender). Fixes to display of ungraded items, and change in parameters extracted from msgid to filter for course messages.

    1: # The LearningOnline Network with CAPA
    2: # Routines for messaging
    3: #
    4: # $Id: lonmsg.pm,v 1.141 2005/04/11 21:51:43 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: package Apache::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:     my $srcsuffix=&foldersuffix($srcfolder);
  617:     my $trgsuffix=&foldersuffix($trgfolder);
  618: 
  619: # Copy message
  620:     my %message=&Apache::lonnet::get('nohist_email'.$srcsuffix,[$msgid]);
  621:     &Apache::lonnet::put('nohist_email'.$trgsuffix,{$msgid => $message{$msgid}});
  622: 
  623: # Copy status
  624:     unless ($trgfolder eq 'trash') {
  625: 	my %status=&Apache::lonnet::get('email_status'.$srcsuffix,[$msgid]);
  626: 	&Apache::lonnet::put('email_status'.$trgsuffix,{$msgid => $status{$msgid}});
  627:     }
  628: # Delete orginals
  629:     &Apache::lonnet::del('nohist_email'.$srcsuffix,[$msgid]);
  630:     &Apache::lonnet::del('email_status'.$srcsuffix,[$msgid]);
  631: }
  632: 
  633: # ======================================================= Display a course list
  634: 
  635: sub discourse {
  636:     my $r=shift;
  637:     my $classlist = &Apache::loncoursedata::get_classlist();
  638:     my $now=time;
  639:     my %lt=&Apache::lonlocal::texthash('cfa' => 'Check All',
  640:             'cfs' => 'Check Section/Group',
  641:             'cfn' => 'Uncheck All');
  642:     $r->print(<<ENDDISHEADER);
  643: <input type="hidden" name="sendmode" value="group" />
  644: <script>
  645:     function checkall() {
  646: 	for (i=0; i<document.forms.compemail.elements.length; i++) {
  647:             if 
  648:           (document.forms.compemail.elements[i].name.indexOf('send_to_')==0) {
  649: 	      document.forms.compemail.elements[i].checked=true;
  650:             }
  651:         }
  652:     }
  653: 
  654:     function checksec() {
  655: 	for (i=0; i<document.forms.compemail.elements.length; i++) {
  656:             if 
  657:           (document.forms.compemail.elements[i].name.indexOf
  658:            ('send_to_&&&'+document.forms.compemail.chksec.value)==0) {
  659: 	      document.forms.compemail.elements[i].checked=true;
  660:             }
  661:         }
  662:     }
  663: 
  664:     function uncheckall() {
  665: 	for (i=0; i<document.forms.compemail.elements.length; i++) {
  666:             if 
  667:           (document.forms.compemail.elements[i].name.indexOf('send_to_')==0) {
  668: 	      document.forms.compemail.elements[i].checked=false;
  669:             }
  670:         }
  671:     }
  672: </script>
  673: <input type="button" onClick="checkall()" value="$lt{'cfa'}" />&nbsp;
  674: <input type="button" onClick="checksec()" value="$lt{'cfs'}" />
  675: <input type="text" size="5" name="chksec" />&nbsp;
  676: <input type="button" onClick="uncheckall()" value="$lt{'cfn'}" />
  677: <p>
  678: ENDDISHEADER
  679:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
  680:     $r->print('<table>');
  681:     foreach my $role (sort keys %coursepersonnel) {
  682:         foreach (split(/\,/,$coursepersonnel{$role})) {
  683:             my ($puname,$pudom)=split(/\:/,$_);
  684:             $r->print('<tr><td><label>'.
  685:                       '<input type="checkbox" name="send_to_&&&&&&_'.
  686:                       $puname.':'.$pudom.'" /> '.
  687:                       &Apache::loncommon::plainname($puname,$pudom).
  688:                       '</label></td>'.
  689:                       '<td>('.$_.'),</td><td><i>'.$role.'</i></td></tr>');
  690:         }
  691:     }
  692:     $r->print('</table><table>');
  693:     my $sort = sub {
  694: 	my $aname=lc($classlist->{$a}[&Apache::loncoursedata::CL_FULLNAME()]);
  695: 	if (!$aname) { $aname=$a; }
  696: 	my $bname=lc($classlist->{$b}[&Apache::loncoursedata::CL_FULLNAME()]);
  697: 	if (!$bname) { $bname=$b; }
  698: 	return $aname cmp $bname;
  699:     };
  700:     foreach my $student (sort $sort (keys(%{$classlist}))) {
  701: 	my $info=$classlist->{$student};
  702:         my ($sname,$sdom,$status,$fullname,$section) =
  703:             (@{$info}[&Apache::loncoursedata::CL_SNAME(),
  704:                       &Apache::loncoursedata::CL_SDOM(),
  705:                       &Apache::loncoursedata::CL_STATUS(),
  706:                       &Apache::loncoursedata::CL_FULLNAME(),
  707:                       &Apache::loncoursedata::CL_SECTION()]);
  708:         next if ($status ne 'Active');
  709:         my $key = 'send_to_&&&'.$section.'&&&_'.$student;
  710:         if (! defined($fullname) || $fullname eq '') { $fullname = $sname; }
  711:         $r->print('<tr><td><label>'.
  712:                   qq{<input type="checkbox" name="$key" />}.('&nbsp;'x2).
  713:                   $fullname.'</label></td><td>'.$sname.'@'.$sdom.'</td><td>'.$section.
  714:                   '</td></tr>');
  715:     }
  716:     $r->print('</table>');
  717: }
  718: 
  719: # ==================================================== Display Critical Message
  720: 
  721: sub discrit {
  722:     my $r=shift;
  723:     my $header = '<h1><font color=red>'.&mt('Critical Messages').'</font></h1>'.
  724:         '<form action="/adm/email" method="POST">'.
  725:         '<input type="hidden" name="confirm" value="true" />';
  726:     my %what=&Apache::lonnet::dump('critical');
  727:     my $result = '';
  728:     foreach (sort keys %what) {
  729:         my %content=&unpackagemsg($what{$_});
  730:         next if ($content{'senderdomain'} eq '');
  731:         $result.='<hr />'.&mt('From').': <b>'.
  732: &Apache::loncommon::aboutmewrapper(
  733:  &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).'</b> ('.
  734: $content{'sendername'}.'@'.
  735:             $content{'senderdomain'}.') '.$content{'time'}.
  736:             '<br />'.&mt('Subject').': '.$content{'subject'}.
  737:             '<br /><pre>'.
  738:               &Apache::lontexconvert::msgtexconverted($content{'message'}).
  739:             '</pre><small>'.
  740: &mt('You have to confirm that you received this message. After confirmation, this message will be moved to your regular inbox').
  741:             '</small><br />'.
  742:             '<input type="submit" name="rec_'.$_.'" value="'.&mt('Confirm Receipt').'" />'.
  743:             '<input type="submit" name="reprec_'.$_.'" '.
  744:                   'value="'.&mt('Confirm Receipt and Reply').'" />';
  745:     }
  746:     # Check to see if there were any messages.
  747:     if ($result eq '') {
  748:         $result = "<h2>".&mt('You have no critical messages.')."</h2>".
  749: 	    '<a href="/adm/roles">'.&mt('Select a course').'</a><br />'.
  750:             '<a href="/adm/email">'.&mt('Communicate').'</a>';
  751:     } else {
  752:         $r->print($header);
  753:     }
  754:     $r->print($result);
  755:     $r->print('<input type="hidden" name="displayedcrit" value="true" /></form>');
  756: }
  757: 
  758: sub sortedmessages {
  759:     my ($blocked,$startblock,$endblock,$numblocked,$folder) = @_;
  760:     my $suffix=&foldersuffix($folder);
  761:     my @messages = &Apache::lonnet::getkeys('nohist_email'.$suffix);
  762:     #unpack the varibles and repack into temp for sorting
  763:     my @temp;
  764:     foreach (@messages) {
  765: 	my $msgid=&Apache::lonnet::escape($_);
  766: 	my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$fromcid)=
  767: 	    &Apache::lonmsg::unpackmsgid($msgid,$folder);
  768: 	my @temp1 = ($sendtime,$shortsubj,$fromname,$fromdomain,$status,
  769: 		     $msgid);
  770:         # Check whether message was sent during blocking period.
  771:         if ($sendtime >= $startblock && ($sendtime <= $endblock && $endblock > 0) ) {
  772:             my $escid = &Apache::lonnet::unescape($msgid);
  773:             $$blocked{$escid} = 'ON';
  774:             $$numblocked ++;
  775:         } else { 
  776:             push @temp ,\@temp1;
  777:         }
  778:     }
  779:     #default sort
  780:     @temp = sort  {$a->[0] <=> $b->[0]} @temp;    
  781:     if ($env{'form.sortedby'} eq "date"){
  782:         @temp = sort  {$a->[0] <=> $b->[0]} @temp;    
  783:     }
  784:     if ($env{'form.sortedby'} eq "revdate"){
  785:     	@temp = sort  {$b->[0] <=> $a->[0]} @temp; 
  786:     }
  787:     if ($env{'form.sortedby'} eq "user"){
  788: 	@temp = sort  {lc($a->[2]) cmp lc($b->[2])} @temp;
  789:     }
  790:     if ($env{'form.sortedby'} eq "revuser"){
  791: 	@temp = sort  {lc($b->[2]) cmp lc($a->[2])} @temp;
  792:     }
  793:     if ($env{'form.sortedby'} eq "domain"){
  794:         @temp = sort  {$a->[3] cmp $b->[3]} @temp;
  795:     }
  796:     if ($env{'form.sortedby'} eq "revdomain"){
  797:         @temp = sort  {$b->[3] cmp $a->[3]} @temp;
  798:     }
  799:     if ($env{'form.sortedby'} eq "subject"){
  800:         @temp = sort  {lc($a->[1]) cmp lc($b->[1])} @temp;
  801:     }
  802:     if ($env{'form.sortedby'} eq "revsubject"){
  803:         @temp = sort  {lc($b->[1]) cmp lc($a->[1])} @temp;
  804:     }
  805:     if ($env{'form.sortedby'} eq "status"){
  806:         @temp = sort  {$a->[4] cmp $b->[4]} @temp;
  807:     }
  808:     if ($env{'form.sortedby'} eq "revstatus"){
  809:         @temp = sort  {$b->[4] cmp $a->[4]} @temp;
  810:     }
  811:     return @temp;
  812: }
  813: 
  814: # ======================================================== Display new messages
  815: 
  816: 
  817: sub disnew {
  818:     my $r=shift;
  819:     my %lt=&Apache::lonlocal::texthash(
  820: 				       'nm' => 'New Messages',
  821: 				       'su' => 'Subject',
  822: 				       'da' => 'Date',
  823: 				       'us' => 'Username',
  824: 				       'op' => 'Open',
  825: 				       'do' => 'Domain'
  826: 				       );
  827:     my @msgids = sort split(/\&/,&Apache::lonnet::reply
  828:                             ('keys:'.$env{'user.domain'}.':'.
  829:                              $env{'user.name'}.':nohist_email',
  830:                              $env{'user.home'}));
  831:     my @newmsgs;
  832:     my %setters = ();
  833:     my $startblock = 0;
  834:     my $endblock = 0;
  835:     my %blocked = ();
  836:     my $numblocked = 0;
  837:     # Check for blocking of display because of scheduled online exams.
  838:     &blockcheck(\%setters,\$startblock,\$endblock);
  839:     foreach (@msgids) {
  840:         my ($sendtime,$shortsubj,$fromname,$fromdom,$status,$fromcid)=
  841: 	    &Apache::lonmsg::unpackmsgid($_);
  842:         if (defined($sendtime) && $sendtime!~/error/) {
  843:             my $numsendtime = $sendtime;
  844:             $sendtime = &Apache::lonlocal::locallocaltime($sendtime);
  845:             if ($status eq 'new') {
  846:                 if ($numsendtime >= $startblock && ($numsendtime <= $endblock && $endblock > 0) ) {
  847:                     $blocked{$_} = 'ON';
  848:                     $numblocked ++;
  849:                 } else {
  850:                     push @newmsgs, { 
  851:                         msgid    => $_,
  852:                         sendtime => $sendtime,
  853:                         shortsub => &Apache::lonnet::unescape($shortsubj),
  854:                         from     => $fromname,
  855:                         fromdom  => $fromdom 
  856:                         }
  857:                 }
  858:             }
  859:         }
  860:     }
  861:     if ($#newmsgs >= 0) {
  862:         $r->print(<<TABLEHEAD);
  863: <h2>$lt{'nm'}</h2>
  864: <table border=2><tr><th>&nbsp</th>
  865: <th>$lt{'da'}</th><th>$lt{'us'}</th><th>$lt{'do'}</th><th>$lt{'su'}</th></tr>
  866: TABLEHEAD
  867:         foreach my $msg (@newmsgs) {
  868:             $r->print(<<"ENDLINK");
  869: <tr bgcolor="#FFBB77">
  870: <td><a href="/adm/email?dismode=new&display=$msg->{'msgid'}">$lt{'op'}</a></td>
  871: ENDLINK
  872:             foreach ('sendtime','from','fromdom','shortsub') {
  873:                 $r->print("<td>$msg->{$_}</td>");
  874:             }
  875:             $r->print("</td></tr>");
  876:         }
  877:         $r->print('</table>'.&Apache::loncommon::endbodytag().'</html>');
  878:     } elsif ($numblocked == 0) {
  879:         $r->print("<h3>".&mt('You have no unread messages')."</h3>");
  880:     }
  881:     if ($numblocked > 0) {
  882:         my $beginblock = &Apache::lonlocal::locallocaltime($startblock);
  883:         my $finishblock = &Apache::lonlocal::locallocaltime($endblock);
  884:         if ($numblocked == 1) {
  885:             $r->print("<h3>".&mt('You have').' '.$numblocked.' '.&mt('blocked unread message').".</h3>");
  886:             $r->print(&mt('This message is not viewable because').' ');
  887:         } else {
  888:             $r->print("<h3>".&mt('You have').' '.$numblocked.' '.&mt('blocked unread messages').".</h3>");
  889:             $r->print(&mt('These').' '.$numblocked.' '.&mt('messages are not viewable because '));
  890:         }
  891:         $r->print(
  892: &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').'.');
  893:         &build_block_table($r,$startblock,$endblock,\%setters);
  894:     }
  895: }
  896: 
  897: 
  898: # ======================================================== Display all messages
  899: 
  900: sub disall {
  901:     my ($r,$folder)=@_;
  902:     $r->print(&folderlist($folder));
  903:     if ($folder eq 'new') {
  904: 	&disnew($r);
  905:     } elsif ($folder eq 'critical') {
  906: 	&discrit($r);
  907:     } else {
  908: 	&disfolder($r,$folder);
  909:     }
  910: }
  911: 
  912: # ============================================================ Display a folder
  913: 
  914: sub disfolder {
  915:     my ($r,$folder)=@_;
  916:     my %blocked = ();
  917:     my %setters = ();
  918:     my $startblock;
  919:     my $endblock;
  920:     my $numblocked = 0;
  921:     &blockcheck(\%setters,\$startblock,\$endblock);
  922:     $r->print(<<ENDDISHEADER);
  923: <script>
  924:     function checkall() {
  925: 	for (i=0; i<document.forms.disall.elements.length; i++) {
  926:             if 
  927:           (document.forms.disall.elements[i].name.indexOf('delmark_')==0) {
  928: 	      document.forms.disall.elements[i].checked=true;
  929:             }
  930:         }
  931:     }
  932: 
  933:     function uncheckall() {
  934: 	for (i=0; i<document.forms.disall.elements.length; i++) {
  935:             if 
  936:           (document.forms.disall.elements[i].name.indexOf('delmark_')==0) {
  937: 	      document.forms.disall.elements[i].checked=false;
  938:             }
  939:         }
  940:     }
  941: </script>
  942: ENDDISHEADER
  943:     my $fsqs='&folder='.$folder;
  944:     my @temp=sortedmessages(\%blocked,$startblock,$endblock,\$numblocked,$folder);
  945:     my $totalnumber=$#temp+1;
  946:     unless ($totalnumber>0) {
  947: 	$r->print('<h2>'.&mt('Empty Folder').'</h2>');
  948: 	return;
  949:     }
  950:     unless ($interdis) {
  951: 	$interdis=20;
  952:     }
  953:     my $number=int($totalnumber/$interdis);
  954:     if (($startdis<0) || ($startdis>$number)) { $startdis=$number; }
  955:     my $firstdis=$interdis*$startdis;
  956:     if ($firstdis>$#temp) { $firstdis=$#temp-$interdis+1; }
  957:     my $lastdis=$firstdis+$interdis-1;
  958:     if ($lastdis>$#temp) { $lastdis=$#temp; }
  959:     $r->print(&scrollbuttons($startdis,$number,$firstdis,$lastdis,$totalnumber));
  960:     $r->print('<form method="post" name="disall" action="/adm/email">'.
  961: 	      '<table border=2><tr><th colspan="3">&nbsp</th><th>');
  962:     if ($env{'form.sortedby'} eq "revdate") {
  963: 	$r->print('<a href = "?sortedby=date'.$fsqs.'">'.&mt('Date').'</a></th>');
  964:     } else {
  965: 	$r->print('<a href = "?sortedby=revdate'.$fsqs.'">'.&mt('Date').'</a></th>');
  966:     }
  967:     $r->print('<th>');
  968:     if ($env{'form.sortedby'} eq "revuser") {
  969: 	$r->print('<a href = "?sortedby=user'.$fsqs.'">'.&mt('Username').'</a>');
  970:     } else {
  971: 	$r->print('<a href = "?sortedby=revuser'.$fsqs.'">'.&mt('Username').'</a>');
  972:     }
  973:     $r->print('</th><th>');
  974:     if ($env{'form.sortedby'} eq "revdomain") {
  975: 	$r->print('<a href = "?sortedby=domain'.$fsqs.'">'.&mt('Domain').'</a>');
  976:     } else {
  977: 	$r->print('<a href = "?sortedby=revdomain'.$fsqs.'">'.&mt('Domain').'</a>');
  978:     }
  979:     $r->print('</th><th>');
  980:     if ($env{'form.sortedby'} eq "revsubject") {
  981: 	$r->print('<a href = "?sortedby=subject'.$fsqs.'">'.&mt('Subject').'</a>');
  982:     } else {
  983:     	$r->print('<a href = "?sortedby=revsubject'.$fsqs.'">'.&mt('Subject').'</a>');
  984:     }
  985:     $r->print('</th><th>');
  986:     if ($env{'form.sortedby'} eq "revstatus") {
  987: 	$r->print('<a href = "?sortedby=status'.$fsqs.'">'.&mt('Status').'</a></th>');
  988:     } else {
  989:      	$r->print('<a href = "?sortedby=revstatus'.$fsqs.'">'.&mt('Status').'</a></th>');
  990:     }
  991:     $r->print("</tr>\n");
  992:     for (my $n=$firstdis;$n<=$lastdis;$n++) {
  993: 	my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$origID)= @{$temp[$n]};
  994: 	if (($status ne 'deleted') && defined($sendtime) && $sendtime!~/error/) {
  995: 	    if ($status eq 'new') {
  996: 		$r->print('<tr bgcolor="#FFBB77">');
  997: 	    } elsif ($status eq 'read') {
  998: 		$r->print('<tr bgcolor="#BBBB77">');
  999: 	    } elsif ($status eq 'replied') {
 1000: 		$r->print('<tr bgcolor="#AAAA88">'); 
 1001: 	    } else {
 1002: 		$r->print('<tr bgcolor="#99BBBB">');
 1003: 	    }
 1004: 	    $r->print('<td><input type="checkbox" name="delmark_'.$origID.'" /></td><td><a href="/adm/email?display='.$origID.$sqs. 
 1005: 		      '">'.&mt('Open').'</a></td><td>'.
 1006: 		      ($folder ne 'trash'?'<a href="/adm/email?markdel='.$origID.$sqs.
 1007: 		      '">'.&mt('Delete'):'&nbsp').'</a></td>'.
 1008: 		      '<td>'.&Apache::lonlocal::locallocaltime($sendtime).'</td><td>'.
 1009: 		      $fromname.'</td><td>'.$fromdomain.'</td><td>'.
 1010: 		      &Apache::lonnet::unescape($shortsubj).'</td><td>'.
 1011:                       $status."</td></tr>\n");
 1012: 	} elsif ($status eq 'deleted') {
 1013: # purge
 1014: 	    &movemsg(&Apache::lonnet::unescape($origID),$folder,'trash');
 1015: 	}
 1016:     }   
 1017:     $r->print("</table>\n<p>".
 1018:   '<a href="javascript:checkall()">'.&mt('Check All').'</a>&nbsp;'.
 1019:   '<a href="javascript:uncheckall()">'.&mt('Uncheck All').'</a></p>'.
 1020:   '<input type="hidden" name="sortedby" value="'.$env{'form.sortedby'}.'" />');
 1021:     if ($folder ne 'trash') {
 1022: 	$r->print(
 1023: 	      '<p><input type="submit" name="markeddel" value="'.&mt('Delete Checked').'" /></p>');
 1024:     }
 1025:     $r->print('<p><input type="submit" name="markedmove" value="'.&mt('Move Checked to Folder').'" />');
 1026:     my @allfolders=&Apache::lonnet::getkeys('email_folders');
 1027:     if ($allfolders[0]=~/^error:/) { @allfolders=(); }
 1028:     $r->print(
 1029: 	&Apache::loncommon::select_form('','movetofolder',
 1030: 			     ( map { $_ => $_ } @allfolders))
 1031: 	      );
 1032:     my $postedstartdis=$startdis+1;
 1033:     $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>');
 1034:     if ($numblocked > 0) {
 1035:         my $beginblock = &Apache::lonlocal::locallocaltime($startblock);
 1036:         my $finishblock = &Apache::lonlocal::locallocaltime($endblock);
 1037:         $r->print('<br /><br />'.
 1038:                   $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.'));
 1039:         &build_block_table($r,$startblock,$endblock,\%setters);
 1040:     }
 1041: }
 1042: 
 1043: # ============================================================== Compose output
 1044: 
 1045: sub compout {
 1046:     my ($r,$forwarding,$replying,$broadcast,$replycrit,$folder)=@_;
 1047:     my $suffix=&foldersuffix($folder);
 1048: 
 1049:     if ($broadcast eq 'individual') {
 1050: 	&printheader($r,'/adm/email?compose=individual',
 1051: 	     'Send a Message');
 1052:     } elsif ($broadcast) {
 1053: 	&printheader($r,'/adm/email?compose=group',
 1054: 	     'Broadcast Message');
 1055:     } elsif ($forwarding) {
 1056: 	&Apache::lonhtmlcommon::add_breadcrumb
 1057:         ({href=>"/adm/email?display=".&Apache::lonnet::escape($forwarding),
 1058:           text=>"Display Message"});
 1059: 	&printheader($r,'/adm/email?forward='.&Apache::lonnet::escape($forwarding),
 1060: 	     'Forwarding a Message');
 1061:     } elsif ($replying) {
 1062: 	&Apache::lonhtmlcommon::add_breadcrumb
 1063:         ({href=>"/adm/email?display=".&Apache::lonnet::escape($replying),
 1064:           text=>"Display Message"});
 1065: 	&printheader($r,'/adm/email?replyto='.&Apache::lonnet::escape($replying),
 1066: 	     'Replying to a Message');
 1067:     } elsif ($replycrit) {
 1068: 	$r->print('<h3>'.&mt('Replying to a Critical Message').'</h3>');
 1069: 	$replying=$replycrit;
 1070:     } else {
 1071: 	&printheader($r,'/adm/email?compose=upload',
 1072: 	     'Distribute from Uploaded File');
 1073:     }
 1074: 
 1075:     my $dispcrit='';
 1076:     my $dissub='';
 1077:     my $dismsg='';
 1078:     my $disbase='';
 1079:     my $func=&mt('Send New');
 1080:     my %lt=&Apache::lonlocal::texthash('us' => 'Username',
 1081: 				       'do' => 'Domain',
 1082: 				       'ad' => 'Additional Recipients',
 1083: 				       'sb' => 'Subject',
 1084: 				       'ca' => 'Cancel',
 1085: 				       'ma' => 'Mail');
 1086: 
 1087:     if (&Apache::lonnet::allowed('srm',$env{'request.course.id'})) {
 1088: 	 my $crithelp = Apache::loncommon::help_open_topic("Course_Critical_Message");
 1089:          $dispcrit=
 1090:  '<p><label><input type="checkbox" name="critmsg" /> '.&mt('Send as critical message').'</label> ' . $crithelp . 
 1091:  '</p><p>'.
 1092:  '<label><input type="checkbox" name="sendbck" /> '.&mt('Send as critical message').'  ' .
 1093:  &mt('and return receipt') . '</label>' . $crithelp . 
 1094:  '</p><p><label><input type="checkbox" name="permanent" /> '.
 1095: &mt('Send copy to permanent email address (if known)').'</label></p>';
 1096:      }
 1097:     my %message;
 1098:     my %content;
 1099:     my $defdom=$env{'user.domain'};
 1100:     if ($forwarding) {
 1101: 	%message=&Apache::lonnet::get('nohist_email'.$suffix,[$forwarding]);
 1102: 	%content=&unpackagemsg($message{$forwarding},$folder);
 1103: 	$dispcrit.='<input type="hidden" name="forwid" value="'.
 1104: 	    $forwarding.'" />';
 1105: 	$func=&mt('Forward');
 1106: 	
 1107: 	$dissub=&mt('Forwarding').': '.$content{'subject'};
 1108: 	$dismsg=&mt('Forwarded message from').' '.
 1109: 	    $content{'sendername'}.' '.&mt('at').' '.$content{'senderdomain'};
 1110: 	if ($content{'baseurl'}) {
 1111: 	    $disbase='<input type="hidden" name="baseurl" value="'.&Apache::lonnet::escape($content{'baseurl'}).'" />';
 1112: 	}
 1113:     }
 1114:     if ($replying) {
 1115: 	%message=&Apache::lonnet::get('nohist_email'.$suffix,[$replying]);
 1116: 	%content=&unpackagemsg($message{$replying},$folder);
 1117: 	$dispcrit.='<input type="hidden" name="replyid" value="'.
 1118: 	    $replying.'" />';
 1119: 	$func=&mt('Send Reply to');
 1120: 	
 1121: 	$dissub=&mt('Reply').': '.$content{'subject'};       
 1122: 	$dismsg='> '.$content{'message'};
 1123: 	$dismsg=~s/\r/\n/g;
 1124: 	$dismsg=~s/\f/\n/g;
 1125: 	$dismsg=~s/\n+/\n\> /g;
 1126: 	if ($content{'baseurl'}) {
 1127: 	    $disbase='<input type="hidden" name="baseurl" value="'.&Apache::lonnet::escape($content{'baseurl'}).'" />';
 1128: 	    if ($env{'user.adv'}) {
 1129: 		$disbase.='<label><input type="checkbox" name="storebasecomment" />'.&mt('Store message for re-use').
 1130: 		    '</label> <a href="/adm/email?showcommentbaseurl='.
 1131: 		    &Apache::lonnet::escape($content{'baseurl'}).'" target="comments">'.
 1132: 		    &mt('Show re-usable messages').'</a><br />';
 1133: 	    }
 1134: 	}
 1135:     }
 1136:     my $citation=&displayresource(%content);
 1137:     if ($env{'form.recdom'}) { $defdom=$env{'form.recdom'}; }
 1138:       $r->print(
 1139:                 '<form action="/adm/email"  name="compemail" method="post"'.
 1140:                 ' enctype="multipart/form-data">'."\n".
 1141:                 '<input type="hidden" name="sendmail" value="on" />'."\n".
 1142:                 '<table>');
 1143:     unless (($broadcast eq 'group') || ($broadcast eq 'upload')) {
 1144: 	if ($replying) {
 1145: 	    $r->print('<tr><td colspan="2">'.&mt('Replying to').' '.
 1146: 		      &Apache::loncommon::aboutmewrapper(
 1147: 							 &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).' ('.
 1148: 		      $content{'sendername'}.'@'.
 1149: 		      $content{'senderdomain'}.')'.
 1150: 		      '<input type="hidden" name="recuname" value="'.$content{'sendername'}.'" />'.
 1151: 		      '<input type="hidden" name="recdomain" value="'.$content{'senderdomain'}.'" />'.
 1152: 		      '</td></tr>');
 1153: 	} else {
 1154: 	    my $domform = &Apache::loncommon::select_dom_form($defdom,'recdomain');
 1155: 	    my $selectlink=&Apache::loncommon::selectstudent_link
 1156: 	    ('compemail','recuname','recdomain');
 1157: 	    $r->print(<<"ENDREC");
 1158: <tr><td>$lt{'us'}:</td><td><input type="text" size="12" name="recuname" value="$env{'form.recname'}" /></td><td rowspan="2">$selectlink</td></tr>
 1159: <tr><td>$lt{'do'}:</td>
 1160: <td>$domform</td></tr>
 1161: ENDREC
 1162:         }
 1163:     }
 1164:     my $latexHelp = Apache::loncommon::helpLatexCheatsheet();
 1165:     if ($broadcast ne 'upload') {
 1166:        $r->print(<<"ENDCOMP");
 1167: <tr><td>$lt{'ad'}<br /><tt>username\@domain,username\@domain, ...
 1168: </tt></td><td>
 1169: <input type="text" size="50" name="additionalrec" /></td></tr>
 1170: <tr><td>$lt{'sb'}:</td><td><input type="text" size="50" name="subject" value="$dissub" />
 1171: </td></tr></table>
 1172: $latexHelp
 1173: <textarea name="message" cols="80" rows="15" wrap="hard">$dismsg
 1174: </textarea></p><br />
 1175: $dispcrit
 1176: $disbase
 1177: <input type="submit" name="send" value="$func $lt{'ma'}" />
 1178: <input type="submit" name="cancel" value="$lt{'ca'}" /><hr />
 1179: $citation
 1180: ENDCOMP
 1181:     } else { # $broadcast is 'upload'
 1182: 	$r->print(<<ENDUPLOAD);
 1183: <input type="hidden" name="sendmode" value="upload" />
 1184: <input type="hidden" name="send" value="on" />
 1185: <h3>Generate messages from a file</h3>
 1186: <p>
 1187: Subject: <input type="text" size="50" name="subject" />
 1188: </p>
 1189: <p>General message text<br />
 1190: <textarea name="message" cols="60" rows="10" wrap="hard">$dismsg
 1191: </textarea></p>
 1192: <p>
 1193: The file format for the uploaded portion of the message is:
 1194: <pre>
 1195: username1\@domain1: text
 1196: username2\@domain2: text
 1197: username3\@domain1: text
 1198: </pre>
 1199: </p>
 1200: <p>
 1201: The messages will be assembled from all lines with the respective 
 1202: <tt>username\@domain</tt>, and appended to the general message text.</p>
 1203: <p>
 1204: <input type="file" name="upfile" size="40" /></p><p>
 1205: $dispcrit
 1206: <input type="submit" value="Upload and Send" /></p>
 1207: ENDUPLOAD
 1208:     }
 1209:     if ($broadcast eq 'group') {
 1210:        &discourse;
 1211:     }
 1212:     $r->print('</form>');
 1213: }
 1214: 
 1215: # ---------------------------------------------------- Display all face to face
 1216: 
 1217: sub retrieve_instructor_comments {
 1218:     my ($user,$domain)=@_;
 1219:     my $target=$env{'form.grade_target'};
 1220:     if (! $env{'request.course.id'}) { return; }
 1221:     if (! &Apache::lonnet::allowed('srm',$env{'request.course.id'})) {
 1222: 	return;
 1223:     }
 1224:     my %records=&Apache::lonnet::dump('nohist_email',
 1225: 			 $env{'course.'.$env{'request.course.id'}.'.domain'},
 1226: 			 $env{'course.'.$env{'request.course.id'}.'.num'},
 1227:                          '%255b'.$user.'%253a'.$domain.'%255d');
 1228:     my $result='';
 1229:     foreach (sort(keys(%records))) {
 1230:         my %content=&unpackagemsg($records{$_});
 1231:         next if ($content{'senderdomain'} eq '');
 1232:         next if ($content{'subject'} !~ /^Record/);
 1233:         # $content{'message'}=~s/\n/\<br\>/g;
 1234:         $result.='Recorded by '.
 1235:             $content{'sendername'}.'@'.$content{'senderdomain'}."\n";
 1236:         $result.=
 1237:             &Apache::lontexconvert::msgtexconverted($content{'message'})."\n";
 1238:      }
 1239:     return $result;
 1240: }
 1241: 
 1242: sub disfacetoface {
 1243:     my ($r,$user,$domain)=@_;
 1244:     my $target=$env{'form.grade_target'};
 1245:     unless ($env{'request.course.id'}) { return; }
 1246:     unless (&Apache::lonnet::allowed('srm',$env{'request.course.id'})) {
 1247: 	return;
 1248:     }
 1249:     my %records=&Apache::lonnet::dump('nohist_email',
 1250: 			 $env{'course.'.$env{'request.course.id'}.'.domain'},
 1251: 			 $env{'course.'.$env{'request.course.id'}.'.num'},
 1252:                          '%255b'.$user.'%253a'.$domain.'%255d');
 1253:     my $result='';
 1254:     foreach (sort keys %records) {
 1255:         my %content=&unpackagemsg($records{$_});
 1256:         next if ($content{'senderdomain'} eq '');
 1257:         $content{'message'}=~s/\n/\<br\>/g;
 1258:         if ($content{'subject'}=~/^Record/) {
 1259: 	    $result.='<h3>'.&mt('Record').'</h3>';
 1260:         } elsif ($content{'subject'}=~/^Broadcast/) {
 1261:             $result .='<h3>'.&mt('Broadcast Message').'</h3>';
 1262:         } else {
 1263:             $result.='<h3>'.&mt('Critical Message').'</h3>';
 1264:             %content=&unpackagemsg($content{'message'});
 1265:             $content{'message'}=
 1266:                 '<b>'.&mt('Subject').': '.$content{'subject'}.'</b><br />'.
 1267: 		$content{'message'};
 1268:         }
 1269:         $result.=&mt('By').': <b>'.
 1270: &Apache::loncommon::aboutmewrapper(
 1271:  &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).'</b> ('.
 1272: $content{'sendername'}.'@'.
 1273:             $content{'senderdomain'}.') '.$content{'time'}.
 1274:             '<br /><pre>'.
 1275:               &Apache::lontexconvert::msgtexconverted($content{'message'}).
 1276: 	      '</pre>';
 1277:      }
 1278:     # Check to see if there were any messages.
 1279:     if ($result eq '') {
 1280: 	if ($target ne 'tex') { 
 1281: 	    $r->print("<p><b>".&mt("No notes, face-to-face discussion records, critical messages, or broadcast messages in this course.")."</b></p>");
 1282: 	} else {
 1283: 	    $r->print('\textbf{'.&mt("No notes, face-to-face discussion records, critical messages or broadcast messages in this course.").'}\\\\');
 1284: 	}
 1285:     } else {
 1286:        $r->print($result);
 1287:     }
 1288: }
 1289: 
 1290: # ---------------------------------------------------------------- Face to face
 1291: 
 1292: sub facetoface {
 1293:     my ($r,$stage)=@_;
 1294:     unless (&Apache::lonnet::allowed('srm',$env{'request.course.id'})) {
 1295: 	return;
 1296:     }
 1297:     &printheader($r,
 1298: 		 '/adm/email?recordftf=query',
 1299: 		 "User Notes, Face-to-Face, Critical Messages, Broadcast Messages");
 1300: # from query string
 1301: 
 1302:     if ($env{'form.recname'}) { $env{'form.recuname'}=$env{'form.recname'}; }
 1303:     if ($env{'form.recdom'}) { $env{'form.recdomain'}=$env{'form.recdom'}; }
 1304: 
 1305:     my $defdom=$env{'user.domain'};
 1306: # already filled in
 1307:     if ($env{'form.recdomain'}) { $defdom=$env{'form.recdomain'}; }
 1308: # generate output
 1309:     my $domform = &Apache::loncommon::select_dom_form($defdom,'recdomain');
 1310:     my $stdbrws = &Apache::loncommon::selectstudent_link
 1311: 	('stdselect','recuname','recdomain');
 1312:     my %lt=&Apache::lonlocal::texthash('user' => 'Username',
 1313: 				       'dom' => 'Domain',
 1314: 				       'head' => 'User Notes, Records of Face-To-Face Discussions, Critical Messages, and Broadcast Messages in Course',
 1315: 				       'subm' => 'Retrieve discussion and message records',
 1316: 				       'newr' => 'New Record (record is visible to course faculty and staff)',
 1317: 				       'post' => 'Post this Record');
 1318:     $r->print(<<"ENDTREC");
 1319: <h3>$lt{'head'}</h3>
 1320: <form method="post" action="/adm/email" name="stdselect">
 1321: <input type="hidden" name="recordftf" value="retrieve" />
 1322: <table>
 1323: <tr><td>$lt{'user'}:</td><td><input type="text" size="12" name="recuname" value="$env{'form.recuname'}" /></td>
 1324: <td rowspan="2">
 1325: $stdbrws
 1326: <input type="submit" value="$lt{'subm'}" /></td>
 1327: </tr>
 1328: <tr><td>$lt{'dom'}:</td>
 1329: <td>$domform</td></tr>
 1330: </table>
 1331: </form>
 1332: ENDTREC
 1333:     if (($stage ne 'query') &&
 1334:         ($env{'form.recdomain'}) && ($env{'form.recuname'})) {
 1335:         chomp($env{'form.newrecord'});
 1336:         if ($env{'form.newrecord'}) {
 1337:            &user_normal_msg_raw(
 1338:             $env{'course.'.$env{'request.course.id'}.'.num'},
 1339:             $env{'course.'.$env{'request.course.id'}.'.domain'},
 1340:             &mt('Record').
 1341: 	     ' ['.$env{'form.recuname'}.':'.$env{'form.recdomain'}.']',
 1342: 	    $env{'form.newrecord'});
 1343:         }
 1344:         $r->print('<h3>'.&Apache::loncommon::plainname($env{'form.recuname'},
 1345: 				     $env{'form.recdomain'}).'</h3>');
 1346:         &disfacetoface($r,$env{'form.recuname'},$env{'form.recdomain'});
 1347: 	$r->print(<<ENDRHEAD);
 1348: <form method="post" action="/adm/email">
 1349: <input name="recdomain" value="$env{'form.recdomain'}" type="hidden" />
 1350: <input name="recuname" value="$env{'form.recuname'}" type="hidden" />
 1351: ENDRHEAD
 1352:         $r->print(<<ENDBFORM);
 1353: <hr />$lt{'newr'}<br />
 1354: <textarea name="newrecord" cols="80" rows="10" wrap="hard"></textarea>
 1355: <br />
 1356: <input type="hidden" name="recordftf" value="post" />
 1357: <input type="submit" value="$lt{'post'}" />
 1358: </form>
 1359: ENDBFORM
 1360:     }
 1361: }
 1362: 
 1363: # ----------------------------------------------------------- Blocking during exams
 1364: 
 1365: sub examblock {
 1366:     my ($r,$action) = @_;
 1367:     unless ($env{'request.course.id'}) { return;}
 1368:     unless (&Apache::lonnet::allowed('srm',$env{'request.course.id'})) { $r->print('Not allowed'); }
 1369:     my %lt=&Apache::lonlocal::texthash(
 1370:             'comb' => 'Communication Blocking',
 1371:             'cbds' => 'Communication blocking during scheduled exams',
 1372:             '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.',
 1373:              'mecb' => 'Modify existing communication blocking periods',
 1374:              'ncbc' => 'No communication blocks currently stored'
 1375:     );
 1376: 
 1377:     my %ltext = &Apache::lonlocal::texthash(
 1378:             'dura' => 'Duration',
 1379:             'setb' => 'Set by',
 1380:             'even' => 'Event',
 1381:             'actn' => 'Action',
 1382:             'star' => 'Start',
 1383:             'endd' => 'End'
 1384:     );
 1385: 
 1386:     &printheader($r,'/adm/email?block=display',$lt{'comb'});
 1387:     $r->print('<h3>'.$lt{'cbds'}.'</h3>');
 1388: 
 1389:     if ($action eq 'store') {
 1390:         &blockstore($r);
 1391:     }
 1392: 
 1393:     $r->print($lt{'desc'}.'<br /><br />
 1394:                <form name="blockform" method="post" action="/adm/email?block=store">
 1395:              ');
 1396: 
 1397:     $r->print('<h4>'.$lt{'mecb'}.'</h4>');
 1398:     my %records = ();
 1399:     my $blockcount = 0;
 1400:     my $parmcount = 0;
 1401:     &get_blockdates(\%records,\$blockcount);
 1402:     if ($blockcount > 0) {
 1403:         $parmcount = &display_blocker_status($r,\%records,\%ltext);
 1404:     } else {
 1405:         $r->print($lt{'ncbc'}.'<br /><br />');
 1406:     }
 1407:     &display_addblocker_table($r,$parmcount,\%ltext);
 1408:     my $endbody=&Apache::loncommon::endbodytag();
 1409:     $r->print(<<"END");
 1410: <br />
 1411: <input type="hidden" name="blocktotal" value="$blockcount" />
 1412: <input type ="submit" value="Save Changes" />
 1413: </form>
 1414: $endbody
 1415: </html>
 1416: END
 1417:     return;
 1418: }
 1419: 
 1420: sub blockstore {
 1421:     my $r = shift;
 1422:     my %lt=&Apache::lonlocal::texthash(
 1423:             'tfcm' => 'The following changes were made',
 1424:             'cbps' => 'communication blocking period(s)',
 1425:             'werm' => 'was/were removed',
 1426:             'wemo' => 'was/were modified',
 1427:             'wead' => 'was/were added',
 1428:             'ncwm' => 'No changes were made.' 
 1429:     );
 1430:     my %adds = ();
 1431:     my %removals = ();
 1432:     my %cancels = ();
 1433:     my $modtotal = 0;
 1434:     my $canceltotal = 0;
 1435:     my $addtotal = 0;
 1436:     my %blocking = ();
 1437:     $r->print('<h3>'.$lt{'head'}.'</h3>');
 1438:     foreach (keys %env) {
 1439:         if ($_ =~ m/^form\.modify_(\w+)$/) {
 1440:             $adds{$1} = $1;
 1441:             $removals{$1} = $1;
 1442:             $modtotal ++;
 1443:         } elsif ($_ =~ m/^form\.cancel_(\d+)$/) {
 1444:             $cancels{$1} = $1;
 1445:             unless ( defined($removals{$1}) ) {
 1446:                 $removals{$1} = $1;
 1447:                 $canceltotal ++;
 1448:             }
 1449:         } elsif ($_ =~ m/^form\.add_(\d+)$/) {
 1450:             $adds{$1} = $1;
 1451:             $addtotal ++;
 1452:         }
 1453:     }
 1454: 
 1455:     foreach (keys %removals) {
 1456:         my $hashkey = $env{'form.key_'.$_};
 1457:         &Apache::lonnet::del('comm_block',["$hashkey"],
 1458:                          $env{'course.'.$env{'request.course.id'}.'.domain'},
 1459:                          $env{'course.'.$env{'request.course.id'}.'.num'}
 1460:                          );
 1461:     }
 1462:     foreach (keys %adds) {
 1463:         unless ( defined($cancels{$_}) ) {
 1464:             my ($newstart,$newend) = &get_dates_from_form($_);
 1465:             my $newkey = $newstart.'____'.$newend;
 1466:             $blocking{$newkey} = $env{'user.name'}.'@'.$env{'user.domain'}.':'.$env{'form.title_'.$_};
 1467:         }
 1468:     }
 1469:     if ($addtotal + $modtotal > 0) {
 1470:         &Apache::lonnet::put('comm_block',\%blocking,
 1471:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
 1472:                      $env{'course.'.$env{'request.course.id'}.'.num'}
 1473:                      );
 1474:     }
 1475:     my $chgestotal = $canceltotal + $modtotal + $addtotal;
 1476:     if ($chgestotal > 0) {
 1477:         $r->print($lt{'tfcm'}.'<ul>');
 1478:         if ($canceltotal > 0) {
 1479:             $r->print('<li>'.$canceltotal.' '.$lt{'cbps'},' '.$lt{'werm'}.'</li>');
 1480:         }
 1481:         if ($modtotal > 0) {
 1482:             $r->print('<li>'.$modtotal.' '.$lt{'cbps'},' '.$lt{'wemo'}.'</li>');
 1483:         }
 1484:         if ($addtotal > 0) {
 1485:             $r->print('<li>'.$addtotal.' '.$lt{'cbps'},' '.$lt{'wead'}.'</li>');
 1486:         }
 1487:         $r->print('</ul>');
 1488:     } else {
 1489:         $r->print($lt{'ncwm'});
 1490:     }
 1491:     $r->print('<br />');
 1492:     return;
 1493: }
 1494: 
 1495: sub get_dates_from_form {
 1496:     my $item = shift;
 1497:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate_'.$item);
 1498:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate_'.$item);
 1499:     return ($startdate,$enddate);
 1500: }
 1501: 
 1502: sub get_blockdates {
 1503:     my ($records,$blockcount) = @_;
 1504:     $$blockcount = 0;
 1505:     %{$records} = &Apache::lonnet::dump('comm_block',
 1506:                          $env{'course.'.$env{'request.course.id'}.'.domain'},
 1507:                          $env{'course.'.$env{'request.course.id'}.'.num'}
 1508:                          );
 1509:     $$blockcount = keys %{$records};
 1510:                                                                                                              
 1511:     foreach (keys %{$records}) {
 1512:         if ($_ eq 'error: 2 tie(GDBM) Failed while attempting dump') {
 1513:             $$blockcount = 0;
 1514:             last;
 1515:         }
 1516:     }
 1517: }
 1518: 
 1519: sub display_blocker_status {
 1520:     my ($r,$records,$ltext) = @_;
 1521:     my $parmcount = 0;
 1522:     my @bgcols = ("#eeeeee","#dddddd");
 1523:     my $function = &Apache::loncommon::get_users_function();
 1524:     my $color = &Apache::loncommon::designparm($function.'.tabbg',
 1525:                                                     $env{'user.domain'});
 1526:     my %lt = &Apache::lonlocal::texthash(
 1527:         'modi' => 'Modify',
 1528:         'canc' => 'Cancel',
 1529:     );
 1530:     $r->print(<<"END");
 1531: <table border="0" cellpadding="0" cellspacing="0">
 1532:  <tr>
 1533:   <td width="100%" bgcolor="#000000">
 1534:    <table width="100%" border="0" cellpadding="1" cellspacing="0">
 1535:     <tr>
 1536:      <td width="100%" bgcolor="#000000">
 1537:       <table border="0" cellpadding="3" cellspacing="3" bgcolor="#FFFFFF">
 1538:        <tr bgcolor="$color">
 1539:         <td><b>$$ltext{'dura'}</b></td>
 1540:         <td><b>$$ltext{'setb'}</b></td>
 1541:         <td><b>$$ltext{'even'}</b></td>
 1542:         <td><b>$$ltext{'actn'}?</b></td>
 1543:        </tr>
 1544: END
 1545:     foreach (sort keys %{$records}) {
 1546:         my $iter = $parmcount%2;
 1547:         my $onchange = 'onFocus="javascript:window.document.forms['.
 1548:                        "'blockform'].elements['modify_".$parmcount."'].".
 1549:                        'checked=true;"';
 1550:         my ($start,$end) = split/____/,$_;
 1551:         my $startform = &Apache::lonhtmlcommon::date_setter('blockform','startdate_'.$parmcount,$start,$onchange);
 1552:         my $endform = &Apache::lonhtmlcommon::date_setter('blockform','enddate_'.$parmcount,$end,$onchange);
 1553:         my ($setter,$title) = split/:/,$$records{$_};
 1554:         my ($setuname,$setudom) = split/@/,$setter;
 1555:         my $settername = &Apache::loncommon::plainname($setuname,$setudom);
 1556:         $r->print(<<"END");
 1557:        <tr bgcolor="$bgcols[$iter]">
 1558:         <td>$$ltext{'star'}:&nbsp;$startform<br/>$$ltext{'endd'}:&nbsp;&nbsp;$endform</td>
 1559:         <td>$settername</td>
 1560:         <td><input type="text" name="title_$parmcount" size="15" value="$title" /><input type="hidden" name="key_$parmcount" value="$_" /></td>
 1561:         <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>
 1562:        </tr>
 1563: END
 1564:         $parmcount ++;
 1565:     }
 1566:     $r->print(<<"END");
 1567:       </table>
 1568:      </td>
 1569:     </tr>
 1570:    </table>
 1571:   </td>
 1572:  </tr>
 1573: </table>
 1574: <br />
 1575: <br />
 1576: END
 1577:     return $parmcount;
 1578: }
 1579: 
 1580: sub display_addblocker_table {
 1581:     my ($r,$parmcount,$ltext) = @_;
 1582:     my $start = time;
 1583:     my $end = $start + (60 * 60 * 2); #Default is an exam of 2 hours duration.
 1584:     my $onchange = 'onFocus="javascript:window.document.forms['.
 1585:                    "'blockform'].elements['add_".$parmcount."'].".
 1586:                    'checked=true;"';
 1587:     my $startform = &Apache::lonhtmlcommon::date_setter('blockform','startdate_'.$parmcount,$start,$onchange);
 1588:     my $endform = &Apache::lonhtmlcommon::date_setter('blockform','enddate_'.$parmcount,$end,$onchange);
 1589:     my $function = &Apache::loncommon::get_users_function();
 1590:     my $color = &Apache::loncommon::designparm($function.'.tabbg',
 1591:                                                     $env{'user.domain'});
 1592:     my %lt = &Apache::lonlocal::texthash(
 1593:         'addb' => 'Add block',
 1594:         'exam' => 'e.g., Exam 1',
 1595:         'addn' => 'Add new communication blocking periods'
 1596:     );
 1597:     $r->print(<<"END");
 1598: <h4>$lt{'addn'}</h4> 
 1599: <table border="0" cellpadding="0" cellspacing="0">
 1600:  <tr>
 1601:   <td width="100%" bgcolor="#000000">
 1602:    <table width="100%" border="0" cellpadding="1" cellspacing="0">
 1603:     <tr>
 1604:      <td width="100%" bgcolor="#000000">
 1605:       <table border="0" cellpadding="3" cellspacing="3" bgcolor="#FFFFFF">
 1606:        <tr bgcolor="#CCCCFF">
 1607:         <td><b>$$ltext{'dura'}</b></td>
 1608:         <td><b>$$ltext{'even'} $lt{'exam'}</b></td>
 1609:         <td><b>$$ltext{'actn'}?</b></td>
 1610:        </tr>
 1611:        <tr bgcolor="#eeeeee">
 1612:         <td>$$ltext{'star'}:&nbsp;$startform<br />$$ltext{'endd'}:&nbsp;&nbsp;$endform</td>
 1613:         <td><input type="text" name="title_$parmcount" size="15" value="" /></td>
 1614:         <td><label>$lt{'addb'}?&nbsp;<input type="checkbox" name="add_$parmcount" value="1" /></label></td>
 1615:        </tr>
 1616:       </table>
 1617:      </td>
 1618:     </tr>
 1619:    </table>
 1620:   </td>
 1621:  </tr>
 1622: </table>
 1623: END
 1624:     return;
 1625: }
 1626: 
 1627: sub blockcheck {
 1628:     my ($setters,$startblock,$endblock) = @_;
 1629:     # Retrieve active student roles and active course coordinator/instructor roles
 1630:     my @livecses = ();
 1631:     my @staffcses = ();
 1632:     $$startblock = 0;
 1633:     $$endblock = 0;
 1634:     foreach (keys %env) {
 1635:         if ($_ =~ m-^user\.role\.(st|cc|in)\./(.+)$-) {
 1636:             my $role = $1;
 1637:             my $cse = $2;
 1638:             $cse =~ s|/|_|;
 1639:             if ($env{$_} =~ m/^(\d*)\.(\d*)$/) {
 1640:                 unless (($2 > 0 && $2 < time) || ($1 > time)) {
 1641:                     if ($role eq 'st') {
 1642:                         push @livecses, $cse;
 1643:                     } else {
 1644:                         unless (grep/^$cse$/,@staffcses) {
 1645:                             push @staffcses, $cse;
 1646:                         }
 1647:                     }
 1648:                 }
 1649:             }
 1650:         } elsif ($_ =~ m-user\.role\.cr/(\w+)/(\w+)/([^/]+)\./(.+)$- ) { 
 1651:             my $rolepriv = $env{'user.role..rolesdef_'.$3};
 1652:         }
 1653:     }
 1654:     # Retrieve blocking times and identity of blocker for active courses for students.
 1655:     if (@livecses > 0) {
 1656:         foreach my $cse (@livecses) {
 1657:             my ($cdom,$crs) = split/_/,$cse;
 1658:             if ( (grep/^$cse$/,@staffcses) && ($env{'request.role'} !~ m-^st\./$cdom/$crs$-) ) {
 1659:                 next;
 1660:             } else {
 1661:                 %{$$setters{$cse}} = ();
 1662:                 @{$$setters{$cse}{'staff'}} = ();
 1663:                 @{$$setters{$cse}{'times'}} = ();
 1664:                 my %records = &Apache::lonnet::dump('comm_block',$cdom,$crs);
 1665:                 foreach (keys %records) {
 1666:                     if ($_ =~ m/^(\d+)____(\d+)$/) {
 1667:                         if ($1 <= time && $2 >= time) {
 1668:                             my ($staff,$title) = split/:/,$records{$_};
 1669:                             push @{$$setters{$cse}{'staff'}}, $staff;
 1670:                             push @{$$setters{$cse}{'times'}}, $_;
 1671:                             if ( ($$startblock == 0) || ($$startblock > $1) ) {
 1672:                                 $$startblock = $1;
 1673:                             }
 1674:                             if ( ($$endblock == 0) || ($$endblock < $2) ) {
 1675:                                 $$endblock = $2;
 1676:                             }
 1677:                         }
 1678:                     }
 1679:                 }
 1680:             }
 1681:         }
 1682:     }
 1683: }
 1684: 
 1685: sub build_block_table {
 1686:     my ($r,$startblock,$endblock,$setters) = @_;
 1687:     my $function = &Apache::loncommon::get_users_function();
 1688:     my $color = &Apache::loncommon::designparm($function.'.tabbg',
 1689:                                                     $env{'user.domain'});
 1690:     my %lt = &Apache::lonlocal::texthash(
 1691:         'cacb' => 'Currently active communication blocks',
 1692:         'cour' => 'Course',
 1693:         'dura' => 'Duration',
 1694:         'blse' => 'Block set by'
 1695:     ); 
 1696:     $r->print(<<"END");
 1697: <br /<br />$lt{'cacb'}:<br /><br />
 1698: <table border="0" cellpadding="0" cellspacing="0">
 1699:  <tr>
 1700:   <td width="100%" bgcolor="#000000">
 1701:    <table width="100%" border="0" cellpadding="1" cellspacing="0">
 1702:     <tr>
 1703:      <td width="100%" bgcolor="#000000">
 1704:       <table border="0" cellpadding="3" cellspacing="3" bgcolor="#FFFFFF">
 1705:        <tr bgcolor="$color">
 1706:         <td><b>$lt{'cour'}</b></td>
 1707:         <td><b>$lt{'dura'}</b></td>
 1708:         <td><b>$lt{'blse'}</b></td>
 1709:        </tr>
 1710: END
 1711:     foreach (keys %{$setters}) {
 1712:         my %courseinfo=&Apache::lonnet::coursedescription($_);
 1713:         for (my $i=0; $i<@{$$setters{$_}{staff}}; $i++) {
 1714:             my ($uname,$udom) = split/\@/,$$setters{$_}{staff}[$i];
 1715:             my $fullname = &Apache::loncommon::plainname($uname,$udom);
 1716:             my ($openblock,$closeblock) = split/____/,$$setters{$_}{times}[$i];
 1717:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 1718:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 1719:             $r->print('<tr><td>'.$courseinfo{'description'}.'</td>'.
 1720:                       '<td>'.$openblock.' to '.$closeblock.'</td>'.
 1721:                       '<td>'.$fullname.' ('.$uname.'@'.$udom.
 1722:                       ')</td></tr>');
 1723:         }
 1724:     }
 1725:     $r->print('</table></td></tr></table></td></tr></table>');
 1726: }
 1727: 
 1728: # ----------------------------------------------------------- Display a message
 1729: 
 1730: sub displaymessage {
 1731:     my ($r,$msgid,$folder)=@_;
 1732:     my $suffix=&foldersuffix($folder);
 1733:     my %blocked = ();
 1734:     my %setters = ();
 1735:     my $startblock = 0;
 1736:     my $endblock = 0;
 1737:     my $numblocked = 0;
 1738: # info to generate "next" and "previous" buttons and check if message is blocked
 1739:     &blockcheck(\%setters,\$startblock,\$endblock);
 1740:     my @messages=&sortedmessages(\%blocked,$startblock,$endblock,\$numblocked,$folder);
 1741:     if ( $blocked{$msgid} eq 'ON' ) {
 1742:         &printheader($r,'/adm/email',&mt('Display a Message'));
 1743:         $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.'));
 1744:         &build_block_table($r,$startblock,$endblock,\%setters);
 1745:         return;
 1746:     }
 1747:     &statuschange($msgid,'read',$folder);
 1748:     my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
 1749:     my %content=&unpackagemsg($message{$msgid});
 1750: 
 1751:     my $counter=0;
 1752:     $r->print('<pre>');
 1753:     my $escmsgid=&Apache::lonnet::escape($msgid);
 1754:     foreach (@messages) {
 1755: 	if ($_->[5] eq $escmsgid){
 1756: 	    last;
 1757: 	}
 1758: 	$counter++;
 1759:     }
 1760:     $r->print('</pre>');
 1761:     my $number_of_messages = scalar(@messages); #subtract 1 for last index
 1762: # start output
 1763:     &printheader($r,'/adm/email?display='.&Apache::lonnet::escape($msgid),'Display a Message','',$content{'baseurl'});
 1764:     my %courseinfo=&Apache::lonnet::coursedescription($content{'courseid'});
 1765: # Functions
 1766:     $r->print('<table border="2" width="100%"><tr bgcolor="#FFFFAA"><td>'.&mt('Functions').':</td>'.
 1767: 	      '<td><a href="/adm/email?replyto='.&Apache::lonnet::escape($msgid).$sqs.
 1768: 	      '"><b>'.&mt('Reply').'</b></a></td>'.
 1769: 	      '<td><a href="/adm/email?forward='.&Apache::lonnet::escape($msgid).$sqs.
 1770: 	      '"><b>'.&mt('Forward').'</b></a></td>'.
 1771: 	      '<td><a href="/adm/email?markunread='.&Apache::lonnet::escape($msgid).$sqs.
 1772: 	      '"><b>'.&mt('Mark Unread').'</b></a></td>'.
 1773: 	      '<td><a href="/adm/email?markdel='.&Apache::lonnet::escape($msgid).$sqs.
 1774: 	      '"><b>Delete</b></a></td>'.
 1775: 	      '<td><a href="/adm/email?'.$sqs.
 1776: 	      ($env{'form.dismode'} eq 'new'?'&folder=new':'').
 1777: 	      '"><b>'.&mt('Back to Folder Display').'</b></a></td>');
 1778:     if ($counter > 0){
 1779: 	$r->print('<td><a href="/adm/email?display='.$messages[$counter-1]->[5].$sqs.
 1780: 		  '"><b>'.&mt('Previous').'</b></a></td>');
 1781:     }
 1782:     if ($counter < $number_of_messages - 1){
 1783: 	$r->print('<td><a href="/adm/email?display='.$messages[$counter+1]->[5].$sqs.
 1784: 		  '"><b>'.&mt('Next').'</b></a></td>');
 1785:     }
 1786:     $r->print('</tr></table>');
 1787:     $r->print('<br /><b>'.&mt('Subject').':</b> '.$content{'subject'}.
 1788: 	      ($folder ne 'sent'?'<br /><b>'.&mt('From').':</b> '.
 1789: 	      &Apache::loncommon::aboutmewrapper(
 1790: 						 &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),
 1791: 						 $content{'sendername'},$content{'senderdomain'}).' ('.
 1792: 	      $content{'sendername'}.' at '.
 1793: 	      $content{'senderdomain'}.') ':'<br /><b>'.&mt('To').':</b> '.
 1794: 	      &Apache::loncommon::aboutmewrapper(
 1795: 						 &Apache::loncommon::plainname($content{'recuser'},$content{'recdomain'}),
 1796: 						 $content{'recuser'},$content{'recdomain'}).' ('.
 1797: 	      $content{'recuser'}.' at '.
 1798: 	      $content{'recdomain'}.') ').
 1799: 	      ($content{'courseid'}?'<br /><b>'.&mt('Course').':</b> '.$courseinfo{'description'}.
 1800: 	       ($content{'coursesec'}?' ('.&mt('Group/Section').': '.$content{'coursesec'}.')':''):'').
 1801: 	      '<br /><b>'.&mt('Time').':</b> '.$content{'time'}.
 1802: 	      ($content{'baseurl'}?'<br /><b>'.&mt('Refers to').':</b> <a href="'.$content{'baseurl'}.'">'.
 1803: 	       $content{'baseurl'}.' ('.&Apache::lonnet::gettitle($content{'baseurl'}).')</a>':'').
 1804: 	      '<p><pre>'.
 1805: 	      &Apache::lontexconvert::msgtexconverted($content{'message'},1).
 1806: 	      '</pre><hr />'.&displayresource(%content).'</p>');
 1807:     return;   
 1808: }
 1809: 
 1810: # =========================================================== Show the citation
 1811: 
 1812: sub displayresource {
 1813:     my %content=@_;
 1814: #
 1815: # If the recipient is in the same course that the message was sent from and
 1816: # has sufficient privileges, show "all details," else show citation
 1817: #
 1818:     if (($env{'request.course.id'} eq $content{'courseid'})
 1819:      && (&Apache::lonnet::allowed('vgr',$content{'courseid'}))) {
 1820: 	my $symb=&Apache::lonnet::symbread($content{'baseurl'});
 1821: # Could not get a symb, give up
 1822: 	unless ($symb) { return $content{'citation'}; }
 1823: # Have a symb, can render
 1824: 	return '<h2>'.&mt('Current attempts of student (if applicable)').'</h2>'.
 1825: 	    &Apache::loncommon::get_previous_attempt($symb,
 1826: 						     $content{'sendername'},
 1827: 						     $content{'senderdomain'},
 1828: 						     $content{'courseid'}).
 1829: 	    '<hr /><h2>'.&mt('Current screen output (if applicable)').'</h2>'.
 1830: 	    &Apache::loncommon::get_student_view($symb,
 1831: 						 $content{'sendername'},
 1832: 						 $content{'senderdomain'},
 1833: 						 $content{'courseid'}).
 1834: 	    '<h2>'.&mt('Correct Answer(s) (if applicable)').'</h2>'.
 1835: 	    &Apache::loncommon::get_student_answers($symb,
 1836: 						    $content{'sendername'},
 1837: 						    $content{'senderdomain'},
 1838: 						    $content{'courseid'});
 1839:     } else {
 1840: 	return $content{'citation'};
 1841:     }
 1842: }
 1843: 
 1844: # ================================================================== The Header
 1845: 
 1846: sub header {
 1847:     my ($r,$title,$baseurl)=@_;
 1848:     $r->print(&Apache::lonxml::xmlbegin().
 1849: 	      '<head>'.&Apache::lonxml::fontsettings().
 1850: 	      '<title>Communication and Messages</title>');
 1851:     if ($baseurl) {
 1852: 	$r->print("<base href=\"http://$ENV{'SERVER_NAME'}/$baseurl\" />");
 1853:     }
 1854:     $r->print(&Apache::loncommon::studentbrowser_javascript().'</head>'.
 1855: 	      &Apache::loncommon::bodytag('Communication and Messages'));
 1856:         $r->print(&Apache::lonhtmlcommon::breadcrumbs
 1857:                   (undef,($title?$title:'Communication and Messages')));
 1858: 
 1859: }
 1860: 
 1861: # ---------------------------------------------------------------- Print header
 1862: 
 1863: sub printheader {
 1864:     my ($r,$url,$desc,$title,$baseurl)=@_;
 1865:     &Apache::lonhtmlcommon::add_breadcrumb
 1866: 	({href=>$url,
 1867: 	  text=>$desc});
 1868:     &header($r,$title,$baseurl);
 1869: }
 1870: 
 1871: # ------------------------------------------------------------ Store the comment
 1872: 
 1873: sub storecomment {
 1874:     my ($r)=@_;
 1875:     my $msgtxt=&Apache::lonfeedback::clear_out_html($env{'form.message'});
 1876:     my $cleanmsgtxt='';
 1877:     foreach (split(/[\n\r]/,$msgtxt)) {
 1878: 	unless ($_=~/^\s*(\>|\&gt\;)/) {
 1879: 	    $cleanmsgtxt.=$_."\n";
 1880: 	}
 1881:     }
 1882:     my $key=&Apache::lonnet::escape($env{'form.baseurl'}).'___'.time;
 1883:     &Apache::lonnet::put('nohist_stored_comments',{ $key => $cleanmsgtxt });
 1884: }
 1885: 
 1886: sub storedcommentlisting {
 1887:     my ($r)=@_;
 1888:     my %msgs=&Apache::lonnet::dump('nohist_stored_comments',undef,undef,
 1889:        '^'.&Apache::lonnet::escape(&Apache::lonnet::escape($env{'form.showcommentbaseurl'})));
 1890:     $r->print(&Apache::lonxml::xmlbegin().'<head>'.
 1891: 	      &Apache::lonxml::fontsettings().'</head><body>');
 1892:     if ((keys %msgs)[0]=~/^error\:/) {
 1893: 	$r->print(&mt('No stored comments yet.'));
 1894:     } else {
 1895: 	my $found=0;
 1896: 	foreach (sort keys %msgs) {
 1897: 	    $r->print("\n".$msgs{$_}."<hr />");
 1898: 	    $found=1;
 1899: 	}
 1900: 	unless ($found) {
 1901: 	    $r->print(&mt('No stored comments yet for this resource.'));
 1902: 	}
 1903:     }
 1904: }
 1905: 
 1906: # ---------------------------------------------------------------- Send an email
 1907: 
 1908: sub sendoffmail {
 1909:     my ($r,$folder)=@_;
 1910:     my $suffix=&foldersuffix($folder);
 1911:     my $sendstatus='';
 1912:     if ($env{'form.send'}) {
 1913: 	&printheader($r,'','Messages being sent.');
 1914: 	$r->rflush();
 1915: 	my %content=();
 1916: 	undef %content;
 1917: 	if ($env{'form.forwid'}) {
 1918: 	    my $msgid=$env{'form.forwid'};
 1919: 	    my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
 1920: 	    %content=&unpackagemsg($message{$msgid},1);
 1921: 	    &statuschange($msgid,'forwarded',$folder);
 1922: 	    $env{'form.message'}.="\n\n-- Forwarded message --\n\n".
 1923: 		$content{'message'};
 1924: 	}
 1925: 	if ($env{'form.replyid'}) {
 1926: 	    my $msgid=$env{'form.replyid'};
 1927: 	    my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
 1928: 	    %content=&unpackagemsg($message{$msgid},1);
 1929: 	    &statuschange($msgid,'replied',$folder);
 1930: 	}
 1931: 	my %toaddr=();
 1932: 	undef %toaddr;
 1933: 	if ($env{'form.sendmode'} eq 'group') {
 1934: 	    foreach (keys %env) {
 1935: 		if ($_=~/^form\.send\_to\_\&\&\&[^\&]*\&\&\&\_(.+)$/) {
 1936: 		    $toaddr{$1}='';
 1937: 		}
 1938: 	    }
 1939: 	} elsif ($env{'form.sendmode'} eq 'upload') {
 1940: 	    foreach (split(/[\n\r\f]+/,$env{'form.upfile'})) {
 1941: 		my ($rec,$txt)=split(/\s*\:\s*/,$_);
 1942: 		if ($txt) {
 1943: 		    $rec=~s/\@/\:/;
 1944: 		    $toaddr{$rec}.=$txt."\n";
 1945: 		}
 1946: 	    }
 1947: 	} else {
 1948: 	    $toaddr{$env{'form.recuname'}.':'.$env{'form.recdomain'}}='';
 1949: 	}
 1950: 	if ($env{'form.additionalrec'}) {
 1951: 	    foreach (split(/\,/,$env{'form.additionalrec'})) {
 1952: 		my ($auname,$audom)=split(/\@/,$_);
 1953: 		$toaddr{$auname.':'.$audom}='';
 1954: 	    }
 1955: 	}
 1956: 	
 1957: 	foreach (keys %toaddr) {
 1958: 	    my ($recuname,$recdomain)=split(/\:/,$_);
 1959:             my $msgtxt;
 1960:             if ((($env{'form.critmsg'}) || ($env{'form.sendbck'})) &&
 1961:                 (&Apache::lonnet::allowed('srm',$env{'request.course.id'}))) {
 1962:                 $msgtxt=&Apache::lonfeedback::clear_out_html($env{'form.message'},1);
 1963:             } else {  
 1964: 	        $msgtxt=&Apache::lonfeedback::clear_out_html($env{'form.message'});
 1965:             }
 1966: 	    if ($toaddr{$_}) { $msgtxt.='<hr />'.$toaddr{$_}; }
 1967: 	    my $thismsg;    
 1968: 	    if ((($env{'form.critmsg'}) || ($env{'form.sendbck'})) && 
 1969: 		(&Apache::lonnet::allowed('srm',$env{'request.course.id'}))) {
 1970: 		$r->print(&mt('Sending critical message').' '.$recuname.'@'.$recdomain.': ');
 1971: 		$thismsg=&user_crit_msg($recuname,$recdomain,
 1972: 					&Apache::lonfeedback::clear_out_html($env{'form.subject'}),
 1973: 					$msgtxt,
 1974: 					$env{'form.sendbck'},$env{'form.permanent'});
 1975: 	    } else {
 1976: 		$r->print(&mt('Sending').' '.$recuname.'@'.$recdomain.': ');
 1977: 		$thismsg=&user_normal_msg($recuname,$recdomain,
 1978: 					  &Apache::lonfeedback::clear_out_html($env{'form.subject'}),
 1979: 					  $msgtxt,
 1980: 					  $content{'citation'},undef,undef,$env{'form.permanent'});
 1981: 		if (($env{'request.course.id'}) && ($env{'form.sendmode'} eq 'group')) {
 1982: 		    &user_normal_msg_raw(
 1983: 					 $env{'course.'.$env{'request.course.id'}.'.num'},
 1984: 					 $env{'course.'.$env{'request.course.id'}.'.domain'},
 1985: 					 'Broadcast ['.$recuname.':'.$recdomain.']',
 1986: 					 $msgtxt);
 1987: 		}
 1988: 	    }
 1989: 	    $r->print($thismsg.'<br />');
 1990: 	    $sendstatus.=' '.$thismsg;
 1991: 	}
 1992:     } else {
 1993: 	&printheader($r,'','No messages sent.'); 
 1994:     }
 1995:     if ($sendstatus=~/^(\s*(?:ok|con_delayed)\s*)*$/) {
 1996: 	$r->print('<br /><font color="green">'.&mt('Completed.').'</font>');
 1997: 	if ($env{'form.displayedcrit'}) {
 1998: 	    &discrit($r);
 1999: 	} else {
 2000: 	    &Apache::loncommunicate::menu($r);
 2001: 	}
 2002:     } else {
 2003: 	$r->print(
 2004: 		  '<h2><font color="red">'.&mt('Could not deliver message').'</font></h2>'.
 2005: 		  &mt('Please use the browser "Back" button and correct the recipient addresses')
 2006: 		  );
 2007:     }
 2008: }
 2009: 
 2010: # ===================================================================== Handler
 2011: 
 2012: sub handler {
 2013:     my $r=shift;
 2014: 
 2015: # ----------------------------------------------------------- Set document type
 2016:     
 2017:     &Apache::loncommon::content_type($r,'text/html');
 2018:     $r->send_http_header;
 2019:     
 2020:     return OK if $r->header_only;
 2021:     
 2022: # --------------------------- Get query string for limited number of parameters
 2023:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 2024:         ['display','replyto','forward','markread','markdel','markunread',
 2025:          'sendreply','compose','sendmail','critical','recname','recdom',
 2026:          'recordftf','sortedby','block','folder','startdis','interdis',
 2027: 	 'showcommentbaseurl','dismode']);
 2028:     $sqs='&sortedby='.$env{'form.sortedby'};
 2029: 
 2030: # ------------------------------------------------------ They checked for email
 2031:     unless ($env{'form.block'}) {
 2032:         &Apache::lonnet::put('email_status',{'recnewemail'=>0});
 2033:     }
 2034: 
 2035: # ----------------------------------------------------------------- Breadcrumbs
 2036: 
 2037:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 2038:     &Apache::lonhtmlcommon::add_breadcrumb
 2039:         ({href=>"/adm/communicate",
 2040:           text=>"Communication/Messages",
 2041:           faq=>12,bug=>'Communication Tools',});
 2042: 
 2043: # ------------------------------------------------------------------ Get Folder
 2044: 
 2045:     my $folder=$env{'form.folder'};
 2046:     unless ($folder) { 
 2047: 	$folder=''; 
 2048:     } else {
 2049: 	$sqs.='&folder='.&Apache::lonnet::escape($folder);
 2050:     }
 2051: 
 2052: # --------------------------------------------------------------------- Display
 2053: 
 2054:     $startdis=$env{'form.startdis'};
 2055:     $startdis--;
 2056:     unless ($startdis) { $startdis=0; }
 2057: 
 2058:     $interdis=$env{'form.interdis'};
 2059:     unless ($interdis) { $interdis=20; }
 2060:     $sqs.='&interdis='.$interdis;
 2061: 
 2062:     if ($env{'form.firstview'}) {
 2063: 	$startdis=0;
 2064:     }
 2065:     if ($env{'form.lastview'}) {
 2066: 	$startdis=-1;
 2067:     }
 2068:     if ($env{'form.prevview'}) {
 2069: 	$startdis--;
 2070:     }
 2071:     if ($env{'form.nextview'}) {
 2072: 	$startdis++;
 2073:     }
 2074:     my $postedstartdis=$startdis+1;
 2075:     $sqs.='&startdis='.$postedstartdis;
 2076: 
 2077: # --------------------------------------------------------------- Render Output
 2078: 
 2079:     if ($env{'form.display'}) {
 2080: 	&displaymessage($r,$env{'form.display'},$folder);
 2081:     } elsif ($env{'form.replyto'}) {
 2082: 	&compout($r,'',$env{'form.replyto'},undef,undef,$folder);
 2083:     } elsif ($env{'form.confirm'}) {
 2084: 	&printheader($r,'','Confirmed Receipt');
 2085: 	foreach (keys %env) {
 2086: 	    if ($_=~/^form\.rec\_(.*)$/) {
 2087: 		$r->print('<b>'.&mt('Confirming Receipt').':</b> '.
 2088: 			  &user_crit_received($1).'<br>');
 2089: 	    }
 2090: 	    if ($_=~/^form\.reprec\_(.*)$/) {
 2091: 		my $msgid=$1;
 2092: 		$r->print('<b>'.&mt('Confirming Receipt').':</b> '.
 2093: 			  &user_crit_received($msgid).'<br>');
 2094: 		&compout($r,'','','',$msgid);
 2095: 	    }
 2096: 	}
 2097: 	&discrit($r);
 2098:     } elsif ($env{'form.critical'}) {
 2099: 	&printheader($r,'','Displaying Critical Messages');
 2100: 	&discrit($r);
 2101:     } elsif ($env{'form.forward'}) {
 2102: 	&compout($r,$env{'form.forward'},undef,undef,undef,$folder);
 2103:     } elsif ($env{'form.markdel'}) {
 2104: 	&printheader($r,'','Deleted Message');
 2105: 	&statuschange($env{'form.markdel'},'deleted',$folder);
 2106: 	&Apache::loncommunicate::menu($r);
 2107: 	&disall($r,$folder);
 2108:     } elsif ($env{'form.markedmove'}) {
 2109: 	my $total=0;
 2110: 	foreach (keys %env) {
 2111: 	    if ($_=~/^form\.delmark_(.*)$/) {
 2112: 		&movemsg(&Apache::lonnet::unescape($1),$folder,
 2113: 			 $env{'form.movetofolder'});
 2114: 		$total++;
 2115: 	    }
 2116: 	}
 2117: 	&printheader($r,'','Moved Messages');
 2118: 	$r->print('Moved '.$total.' message(s)<p>');
 2119: 	&Apache::loncommunicate::menu($r);
 2120: 	&disall($r,$folder);
 2121:     } elsif ($env{'form.markeddel'}) {
 2122: 	my $total=0;
 2123: 	foreach (keys %env) {
 2124: 	    if ($_=~/^form\.delmark_(.*)$/) {
 2125: 		&statuschange(&Apache::lonnet::unescape($1),'deleted',$folder);
 2126: 		$total++;
 2127: 	    }
 2128: 	}
 2129: 	&printheader($r,'','Deleted Messages');
 2130: 	$r->print('Deleted '.$total.' message(s)<p>');
 2131: 	&Apache::loncommunicate::menu($r);
 2132: 	&disall($r,$folder);
 2133:     } elsif ($env{'form.markunread'}) {
 2134: 	&printheader($r,'','Marked Message as Unread');
 2135: 	&statuschange($env{'form.markunread'},'new');
 2136: 	&Apache::loncommunicate::menu($r);
 2137: 	&disall($r,$folder);
 2138:     } elsif ($env{'form.compose'}) {
 2139: 	&compout($r,'','',$env{'form.compose'});
 2140:     } elsif ($env{'form.recordftf'}) {
 2141: 	&facetoface($r,$env{'form.recordftf'});
 2142:     } elsif ($env{'form.block'}) {
 2143:         &examblock($r,$env{'form.block'});
 2144:     } elsif ($env{'form.sendmail'}) {
 2145: 	&sendoffmail($r,$folder);
 2146: 	if ($env{'form.storebasecomment'}) {
 2147: 	    &storecomment($r);
 2148: 	}
 2149: 	&disall($r,$folder);
 2150:     } elsif ($env{'form.newfolder'}) {
 2151: 	&printheader($r,'','New Folder');
 2152: 	&makefolder($env{'form.newfolder'});
 2153: 	&Apache::loncommunicate::menu($r);
 2154: 	&disall($r,$env{'form.newfolder'});
 2155:     } elsif ($env{'form.showcommentbaseurl'}) {
 2156: 	&storedcommentlisting($r);
 2157:     } else {
 2158: 	&printheader($r,'','Display All Messages');
 2159: 	&Apache::loncommunicate::menu($r);
 2160: 	&disall($r,$folder);
 2161:     }
 2162:     $r->print(&Apache::loncommon::endbodytag().'</html>');
 2163:     return OK;
 2164: }
 2165: # ================================================= Main program, reset counter
 2166: 
 2167: BEGIN {
 2168:     $msgcount=0;
 2169: }
 2170: 
 2171: =pod
 2172: 
 2173: =back
 2174: 
 2175: =cut
 2176: 
 2177: 1; 
 2178: 
 2179: __END__
 2180: 
 2181: 
 2182: 
 2183: 
 2184: 
 2185: 
 2186: 

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