File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.154: download - view: text, annotated - select for diffs
Thu Nov 17 21:33:40 2005 UTC (18 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Having fun with RSS. Option when doing Broadcasts and Calendar Announcements

Next steps:
* dynamically generated, showing due dates, etc

Long term:
* podcasts
* blogs

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

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