File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.128: download - view: text, annotated - select for diffs
Sat Jan 1 18:36:13 2005 UTC (19 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #3771: not loosing status anymore when moving messages between folders.

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

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