File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.114: download - view: text, annotated - select for diffs
Thu Nov 11 20:41:53 2004 UTC (19 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
Further work on cleaning up menus

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

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