File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.134: download - view: text, annotated - select for diffs
Thu Feb 17 03:36:05 2005 UTC (19 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- showing the list of students in has order doesn't seem like a good idea, how about name order instead

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

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