File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.152: download - view: text, annotated - select for diffs
Fri Jul 8 10:39:49 2005 UTC (18 years, 10 months ago) by www
Branches: MAIN
CVS tags: version_2_0_X, version_2_0_2, version_2_0_1, version_2_0_0, version_1_99_3, version_1_99_2, HEAD
Back in town.

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

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