File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.108: download - view: text, annotated - select for diffs
Mon Sep 20 15:01:56 2004 UTC (19 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Just saving work from during the trip

    1: # The LearningOnline Network with CAPA
    2: # Routines for messaging
    3: #
    4: # $Id: lonmsg.pm,v 1.108 2004/09/20 15:01:56 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: 			      'sent' => &mt('Sent Messages'),
  527: 			      map { $_ => $_ } @allfolders)).
  528: 			      ' '.&mt('Show').' '.
  529: 	    &Apache::loncommon::select_form($interdis,'interdis',
  530: (' 10' => '10', ' 20' => '20', ' 50' => '50', '100' => '100', '200' => '200')).	
  531:    '<input type="submit" value="'.&mt('View Folder').'" /><br />'.
  532:    '<input type="submit" name="firstview" value="'.&mt('First').'" />'.
  533:    '<input type="submit" name="prevview" value="'.&mt('Previous').'" />'.
  534:    '<input type="text" size="5" name="startdis" value="'.$startdis.'" />'.
  535:    '<input type="submit" name="nextview" value="'.&mt('Next').'" />'.
  536:    '<input type="submit" name="lastview" value="'.&mt('Last').'" />'.
  537: 	'<a href="/adm/email?critical=display'.$sqs.'">'.
  538: 	    &mt('View Critical Messages').'</a>'.
  539: 	    '</form>';
  540: }
  541: 
  542: # =============================================================== Folder suffix
  543: 
  544: sub foldersuffix {
  545:     my $folder=shift;
  546:     unless ($folder) { return ''; }
  547:     return '_'.&Apache::lonnet::escape($folder);
  548: }
  549: 
  550: # =============================================================== Status Change
  551: 
  552: sub statuschange {
  553:     my ($msgid,$newstatus,$folder)=@_;
  554:     my $suffix=&foldersuffix($folder);
  555:     my %status=&Apache::lonnet::get('email_status'.$suffix,[$msgid]);
  556:     if ($status{$msgid}=~/^error\:/) { $status{$msgid}=''; }
  557:     unless ($status{$msgid}) { $status{$msgid}='new'; }
  558:     unless (($status{$msgid} eq 'replied') || 
  559:             ($status{$msgid} eq 'forwarded')) {
  560: 	&Apache::lonnet::put('email_status'.$suffix,{$msgid => $newstatus});
  561:     }
  562:     if (($newstatus eq 'deleted') || ($newstatus eq 'new')) {
  563: 	&Apache::lonnet::put('email_status'.$suffix,{$msgid => $newstatus});
  564:     }
  565: }
  566: 
  567: # ============================================================= Make new folder
  568: 
  569: sub makefolder {
  570:     my ($newfolder)=@_;
  571:     &Apache::lonnet::put('email_folders',{$newfolder => time});
  572: }
  573: 
  574: # ======================================================== Move between folders
  575: 
  576: sub movemsg {
  577:     my ($msgid,$srcfolder,$trgfolder)=@_;
  578:     my $unmsgid=&Apache::lonnet::unescape($msgid);
  579:     my $srcsuffix=&foldersuffix($srcfolder);
  580:     my $trgsuffix=&foldersuffix($trgfolder);
  581: 
  582: # Copy message
  583:     my %message=&Apache::lonnet::get('nohist_email'.$srcsuffix,[$msgid]);
  584:     &Apache::lonnet::put('nohist_email'.$trgsuffix,{$msgid => $message{$msgid}});
  585: 
  586: # Copy status
  587:     my %status=&Apache::lonnet::get('email_status'.$srcsuffix,[$unmsgid]);
  588:     &Apache::lonnet::put('email_status'.$trgsuffix,{$unmsgid => $status{$unmsgid}});
  589: # See if was deleted -> becomes "read" in trash
  590:     my $currentstatus=(&unpackmsgid($status{$unmsgid}),$srcfolder);
  591:     if ($currentstatus eq 'deleted') {
  592: 	&statuschange($msgid,'read',$trgfolder);
  593:     }
  594: # Delete orginals
  595:     &Apache::lonnet::del('nohist_email'.$srcsuffix,[$msgid]);
  596:     &Apache::lonnet::del('email_status'.$srcsuffix,[$unmsgid]);
  597: }
  598: 
  599: # ======================================================= Display a course list
  600: 
  601: sub discourse {
  602:     my $r=shift;
  603:     my %courselist=&Apache::lonnet::dump(
  604:                    'classlist',
  605: 		   $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
  606: 		   $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
  607:     my $now=time;
  608:     my %lt=&Apache::lonlocal::texthash('cfa' => 'Check for All',
  609:             'cfs' => 'Check for Section/Group',
  610:             'cfn' => 'Check for None');
  611:     $r->print(<<ENDDISHEADER);
  612: <input type="hidden" name="sendmode" value="group" />
  613: <script>
  614:     function checkall() {
  615: 	for (i=0; i<document.forms.compemail.elements.length; i++) {
  616:             if 
  617:           (document.forms.compemail.elements[i].name.indexOf('send_to_')==0) {
  618: 	      document.forms.compemail.elements[i].checked=true;
  619:             }
  620:         }
  621:     }
  622: 
  623:     function checksec() {
  624: 	for (i=0; i<document.forms.compemail.elements.length; i++) {
  625:             if 
  626:           (document.forms.compemail.elements[i].name.indexOf
  627:            ('send_to_&&&'+document.forms.compemail.chksec.value)==0) {
  628: 	      document.forms.compemail.elements[i].checked=true;
  629:             }
  630:         }
  631:     }
  632: 
  633:     function uncheckall() {
  634: 	for (i=0; i<document.forms.compemail.elements.length; i++) {
  635:             if 
  636:           (document.forms.compemail.elements[i].name.indexOf('send_to_')==0) {
  637: 	      document.forms.compemail.elements[i].checked=false;
  638:             }
  639:         }
  640:     }
  641: </script>
  642: <input type="button" onClick="checkall()" value="$lt{'cfa'}" />&nbsp;
  643: <input type="button" onClick="checksec()" value="$lt{'cfs'}" />
  644: <input type="text" size="5" name=chksec />&nbsp;
  645: <input type="button" onClick="uncheckall()" value="$lt{'cfn'}" />
  646: <p>
  647: ENDDISHEADER
  648:     my %coursepersonnel=
  649:        &Apache::lonnet::get_course_adv_roles();
  650:     foreach my $role (sort keys %coursepersonnel) {
  651:        foreach (split(/\,/,$coursepersonnel{$role})) {
  652: 	   my ($puname,$pudom)=split(/\:/,$_);
  653: 	   $r->print(
  654:              '<br /><input type="checkbox" name="send_to_&&&&&&_'.
  655:              $puname.':'.$pudom.'" /> '.
  656: 		     &Apache::loncommon::plainname($puname,
  657:                           $pudom).' ('.$_.'), <i>'.$role.'</i>');
  658: 	}
  659:     }
  660: 
  661:     foreach (sort keys %courselist) {
  662:         my ($end,$start)=split(/\:/,$courselist{$_});
  663:         my $active=1;
  664:         if (($end) && ($now>$end)) { $active=0; }
  665:         if ($active) {
  666:            my ($sname,$sdom)=split(/\:/,$_);
  667:            my %reply=&Apache::lonnet::get('environment',
  668:               ['firstname','middlename','lastname','generation'],
  669:               $sdom,$sname);
  670:            my $section=&Apache::lonnet::usection
  671: 	       ($sdom,$sname,$ENV{'request.course.id'});
  672:            $r->print(
  673:         '<br><input type=checkbox name="send_to_&&&'.$section.'&&&_'.$_.'"> '.
  674: 		      $reply{'firstname'}.' '. 
  675:                       $reply{'middlename'}.' '.
  676:                       $reply{'lastname'}.' '.
  677:                       $reply{'generation'}.
  678:                       ' ('.$_.') '.$section);
  679:         } 
  680:     }
  681: }
  682: 
  683: # ==================================================== Display Critical Message
  684: 
  685: sub discrit {
  686:     my $r=shift;
  687:     my $header = '<h1><font color=red>'.&mt('Critical Messages').'</font></h1>'.
  688:         '<form action=/adm/email method=post>'.
  689:         '<input type=hidden name=confirm value=true>';
  690:     my %what=&Apache::lonnet::dump('critical');
  691:     my $result = '';
  692:     foreach (sort keys %what) {
  693:         my %content=&unpackagemsg($what{$_});
  694:         next if ($content{'senderdomain'} eq '');
  695:         $content{'message'}=~s/\n/\<br\>/g;
  696:         $result.='<hr />'.&mt('From').': <b>'.
  697: &Apache::loncommon::aboutmewrapper(
  698:  &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).'</b> ('.
  699: $content{'sendername'}.'@'.
  700:             $content{'senderdomain'}.') '.$content{'time'}.
  701:             '<br />'.&mt('Subject').': '.$content{'subject'}.
  702:             '<br /><blockquote>'.
  703:               &Apache::lontexconvert::msgtexconverted($content{'message'}).
  704:             '</blockquote><small>'.
  705: &mt('You have to confirm that you received this message. After confirmation, this message will be moved to your regular inbox').
  706:             '</small><br />'.
  707:             '<input type=submit name="rec_'.$_.'" value="'.&mt('Confirm Receipt').'">'.
  708:             '<input type=submit name="reprec_'.$_.'" '.
  709:                   'value="'.&mt('Confirm Receipt and Reply').'">';
  710:     }
  711:     # Check to see if there were any messages.
  712:     if ($result eq '') {
  713:         $result = "<h2>".&mt('You have no critical messages.')."</h2>".
  714: 	    '<a href="/adm/roles">'.&mt('Select a course').'</a><br />'.
  715:             '<a href="/adm/email">'.&mt('Communicate').'</a>';
  716:     } else {
  717:         $r->print($header);
  718:     }
  719:     $r->print($result);
  720:     $r->print('<input type="hidden" name="displayedcrit" value="true" /></form>');
  721: }
  722: 
  723: sub sortedmessages {
  724:     my ($blocked,$startblock,$endblock,$numblocked,$folder) = @_;
  725:     my $suffix=&foldersuffix($folder);
  726:     my @messages = &Apache::lonnet::getkeys('nohist_email'.$suffix);
  727:     #unpack the varibles and repack into temp for sorting
  728:     my @temp;
  729:     foreach (@messages) {
  730: 	my $msgid=&Apache::lonnet::escape($_);
  731: 	my ($sendtime,$shortsubj,$fromname,$fromdomain,$status)=
  732: 	    &Apache::lonmsg::unpackmsgid($msgid,$folder);
  733: 	my @temp1 = ($sendtime,$shortsubj,$fromname,$fromdomain,$status,
  734: 		     $msgid);
  735:         # Check whether message was sent during blocking period.
  736:         if ($sendtime >= $startblock && ($sendtime <= $endblock && $endblock > 0) ) {
  737:             my $escid = &Apache::lonnet::unescape($msgid);
  738:             $$blocked{$escid} = 'ON';
  739:             $$numblocked ++;
  740:         } else { 
  741:             push @temp ,\@temp1;
  742:         }
  743:     }
  744:     #default sort
  745:     @temp = sort  {$a->[0] <=> $b->[0]} @temp;    
  746:     if ($ENV{'form.sortedby'} eq "date"){
  747:         @temp = sort  {$a->[0] <=> $b->[0]} @temp;    
  748:     }
  749:     if ($ENV{'form.sortedby'} eq "revdate"){
  750:     	@temp = sort  {$b->[0] <=> $a->[0]} @temp; 
  751:     }
  752:     if ($ENV{'form.sortedby'} eq "user"){
  753: 	@temp = sort  {lc($a->[2]) cmp lc($b->[2])} @temp;
  754:     }
  755:     if ($ENV{'form.sortedby'} eq "revuser"){
  756: 	@temp = sort  {lc($b->[2]) cmp lc($a->[2])} @temp;
  757:     }
  758:     if ($ENV{'form.sortedby'} eq "domain"){
  759:         @temp = sort  {$a->[3] cmp $b->[3]} @temp;
  760:     }
  761:     if ($ENV{'form.sortedby'} eq "revdomain"){
  762:         @temp = sort  {$b->[3] cmp $a->[3]} @temp;
  763:     }
  764:     if ($ENV{'form.sortedby'} eq "subject"){
  765:         @temp = sort  {lc($a->[1]) cmp lc($b->[1])} @temp;
  766:     }
  767:     if ($ENV{'form.sortedby'} eq "revsubject"){
  768:         @temp = sort  {lc($b->[1]) cmp lc($a->[1])} @temp;
  769:     }
  770:     if ($ENV{'form.sortedby'} eq "status"){
  771:         @temp = sort  {$a->[4] cmp $b->[4]} @temp;
  772:     }
  773:     if ($ENV{'form.sortedby'} eq "revstatus"){
  774:         @temp = sort  {$b->[4] cmp $a->[4]} @temp;
  775:     }
  776:     return @temp;
  777: }
  778: 
  779: # ======================================================== Display all messages
  780: 
  781: sub disall {
  782:     my ($r,$folder)=@_;
  783:     my %blocked = ();
  784:     my %setters = ();
  785:     my $startblock;
  786:     my $endblock;
  787:     my $numblocked = 0;
  788:     &blockcheck(\%setters,\$startblock,\$endblock);
  789:     $r->print(<<ENDDISHEADER);
  790: <script>
  791:     function checkall() {
  792: 	for (i=0; i<document.forms.disall.elements.length; i++) {
  793:             if 
  794:           (document.forms.disall.elements[i].name.indexOf('delmark_')==0) {
  795: 	      document.forms.disall.elements[i].checked=true;
  796:             }
  797:         }
  798:     }
  799: 
  800:     function uncheckall() {
  801: 	for (i=0; i<document.forms.disall.elements.length; i++) {
  802:             if 
  803:           (document.forms.disall.elements[i].name.indexOf('delmark_')==0) {
  804: 	      document.forms.disall.elements[i].checked=false;
  805:             }
  806:         }
  807:     }
  808: </script>
  809: ENDDISHEADER
  810:     my $fsqs='&folder='.$folder;
  811:     my @temp=sortedmessages(\%blocked,$startblock,$endblock,\$numblocked,$folder);
  812:     my $totalnumber=$#temp+1;
  813:     my $number=int($totalnumber/$interdis)+1;
  814:     my $firstdis=$interdis*$startdis;
  815:     if ($firstdis>$#temp) { $firstdis=$#temp-$interdis+1; }
  816:     my $lastdis=$firstdis+$interdis-1;
  817:     if ($lastdis>$#temp) { $lastdis=$#temp; }
  818:     $r->print('<h2>'.&mt('Display All Messages').'</h2>'.
  819: 	      &folderlist($folder).
  820: 	      '<form method="post" name="disall" action="/adm/email">'.
  821: 	      '<table border=2><tr><th colspan="3">&nbsp</th><th>');
  822:     if ($ENV{'form.sortedby'} eq "revdate") {
  823: 	$r->print('<a href = "?sortedby=date'.$fsqs.'">'.&mt('Date').'</a></th>');
  824:     } else {
  825: 	$r->print('<a href = "?sortedby=revdate'.$fsqs.'">'.&mt('Date').'</a></th>');
  826:     }
  827:     $r->print('<th>');
  828:     if ($ENV{'form.sortedby'} eq "revuser") {
  829: 	$r->print('<a href = "?sortedby=user'.$fsqs.'">'.&mt('Username').'</a>');
  830:     } else {
  831: 	$r->print('<a href = "?sortedby=revuser'.$fsqs.'">'.&mt('Username').'</a>');
  832:     }
  833:     $r->print('</th><th>');
  834:     if ($ENV{'form.sortedby'} eq "revdomain") {
  835: 	$r->print('<a href = "?sortedby=domain'.$fsqs.'">'.&mt('Domain').'</a>');
  836:     } else {
  837: 	$r->print('<a href = "?sortedby=revdomain'.$fsqs.'">'.&mt('Domain').'</a>');
  838:     }
  839:     $r->print('</th><th>');
  840:     if ($ENV{'form.sortedby'} eq "revsubject") {
  841: 	$r->print('<a href = "?sortedby=subject'.$fsqs.'">'.&mt('Subject').'</a>');
  842:     } else {
  843:     	$r->print('<a href = "?sortedby=revsubject'.$fsqs.'">'.&mt('Subject').'</a>');
  844:     }
  845:     $r->print('</th><th>');
  846:     if ($ENV{'form.sortedby'} eq "revstatus") {
  847: 	$r->print('<a href = "?sortedby=status'.$fsqs.'">'.&mt('Status').'</th>');
  848:     } else {
  849:      	$r->print('<a href = "?sortedby=revstatus'.$fsqs.'">'.&mt('Status').'</th>');
  850:     }
  851:     $r->print('</tr>');
  852:     for (my $n=$firstdis;$n<=$lastdis;$n++) {
  853: 	my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$origID)= @{$temp[$n]};
  854: 	if (($status ne 'deleted') && defined($sendtime) && $sendtime!~/error/) {
  855: 	    if ($status eq 'new') {
  856: 		$r->print('<tr bgcolor="#FFBB77">');
  857: 	    } elsif ($status eq 'read') {
  858: 		$r->print('<tr bgcolor="#BBBB77">');
  859: 	    } elsif ($status eq 'replied') {
  860: 		$r->print('<tr bgcolor="#AAAA88">'); 
  861: 	    } else {
  862: 		$r->print('<tr bgcolor="#99BBBB">');
  863: 	    }
  864: 	    $r->print('<td></a><input type=checkbox name="delmark_'.$origID.'" /></td><td><a href="/adm/email?display='.$origID.$sqs. 
  865: 		      '">'.&mt('Open').'</a></td><td>'.
  866: 		      ($folder ne 'trash'?'<a href="/adm/email?markdel='.$origID.$sqs.
  867: 		      '">'.&mt('Delete'):'&nbsp').'</td>'.
  868: 		      '<td>'.&Apache::lonlocal::locallocaltime($sendtime).'</td><td>'.
  869: 		      $fromname.'</td><td>'.$fromdomain.'</td><td>'.
  870: 		      &Apache::lonnet::unescape($shortsubj).'</td><td>'.
  871:                       $status.'</td></tr>');
  872: 	} elsif ($status eq 'deleted') {
  873: # purge
  874: 	    &movemsg(&Apache::lonnet::unescape($origID),$folder,'trash');
  875: 	}
  876:     }   
  877:     $r->print('</table><p>'.
  878:   '<a href="javascript:checkall()">'.&mt('Check All').'</a>&nbsp;'.
  879:   '<a href="javascript:uncheckall()">'.&mt('Uncheck All').'</a></p>'.
  880:   '<input type="hidden" name="sortedby" value="'.$ENV{'form.sortedby'}.'" />');
  881:     if ($folder ne 'trash') {
  882: 	$r->print(
  883: 	      '<p><input type="submit" name="markeddel" value="'.&mt('Delete Checked').'" /></p>');
  884:     }
  885: $r->print('<p><input type="submit" name="markedmove" value="'.&mt('Move Checked to Folder').'" />');
  886:     my @allfolders=&Apache::lonnet::getkeys('email_folders');
  887:     if ($allfolders[0]=~/^error:/) { @allfolders=(); }
  888:     $r->print(
  889: 	&Apache::loncommon::select_form('','movetofolder',
  890: 			     ( map { $_ => $_ } @allfolders))
  891: 	      );
  892:     $r->print('<input type="hidden" name="folder" value="'.$folder.'" /></form>');
  893:     if ($numblocked > 0) {
  894:         my $beginblock = &Apache::lonlocal::locallocaltime($startblock);
  895:         my $finishblock = &Apache::lonlocal::locallocaltime($endblock);
  896:         $r->print('<br /><br />'.
  897:                   $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.'));
  898:         &build_block_table($r,$startblock,$endblock,\%setters);
  899:     }
  900: }
  901: 
  902: # ============================================================== Compose output
  903: 
  904: sub compout {
  905:     my ($r,$forwarding,$replying,$broadcast,$replycrit,$folder)=@_;
  906: 
  907:     if ($broadcast eq 'individual') {
  908: 	&printheader($r,'/adm/email?compose=individual',
  909: 	     'Send a Message');
  910:     } elsif ($broadcast) {
  911: 	&printheader($r,'/adm/email?compose=group',
  912: 	     'Broadcast Message');
  913:     } elsif ($forwarding) {
  914: 	&Apache::lonhtmlcommon::add_breadcrumb
  915:         ({href=>"/adm/email?display=".&Apache::lonnet::escape($forwarding),
  916:           text=>"Display Message"});
  917: 	&printheader($r,'/adm/email?forward='.&Apache::lonnet::escape($forwarding),
  918: 	     'Forwarding a Message');
  919:     } elsif ($replying) {
  920: 	&Apache::lonhtmlcommon::add_breadcrumb
  921:         ({href=>"/adm/email?display=".&Apache::lonnet::escape($replying),
  922:           text=>"Display Message"});
  923: 	&printheader($r,'/adm/email?replyto='.&Apache::lonnet::escape($replying),
  924: 	     'Replying to a Message');
  925:     } elsif ($replycrit) {
  926: 	$r->print('<h3>'.&mt('Replying to a Critical Message').'</h3>');
  927: 	$replying=$replycrit;
  928:     } else {
  929: 	&printheader($r,'/adm/email?compose=upload',
  930: 	     'Distribute from Uploaded File');
  931:     }
  932: 
  933:     my $dispcrit='';
  934:     my $dissub='';
  935:     my $dismsg='';
  936:     my $func=&mt('Send New');
  937:     my %lt=&Apache::lonlocal::texthash('us' => 'Username',
  938: 				       'do' => 'Domain',
  939: 				       'ad' => 'Additional Recipients',
  940: 				       'sb' => 'Subject',
  941: 				       'ca' => 'Cancel',
  942: 				       'ma' => 'Mail');
  943: 
  944:     if (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})) {
  945: 	 my $crithelp = Apache::loncommon::help_open_topic("Course_Critical_Message");
  946:          $dispcrit=
  947:  '<input type="checkbox" name="critmsg" /> '.&mt('Send as critical message').' ' . $crithelp . 
  948:  '<br>'.
  949:  '<input type="checkbox" name="sendbck" /> '.&mt('Send as critical message').'  ' .
  950:  &mt('and return receipt') . $crithelp . '<p>';
  951:      }
  952:     my %message;
  953:     my %content;
  954:     my $defdom=$ENV{'user.domain'};
  955:     if ($forwarding) {
  956: 	%message=&Apache::lonnet::get('nohist_email',[$forwarding]);
  957: 	%content=&unpackagemsg($message{$forwarding},$folder);
  958: 	$dispcrit.='<input type="hidden" name="forwid" value="'.
  959: 	    $forwarding.'" />';
  960: 	$func=&mt('Forward');
  961: 	
  962: 	$dissub=&mt('Forwarding').': '.$content{'subject'};
  963: 	$dismsg=&mt('Forwarded message from').' '.
  964: 	    $content{'sendername'}.' '.&mt('at').' '.$content{'senderdomain'};
  965:     }
  966:     if ($replying) {
  967: 	%message=&Apache::lonnet::get('nohist_email',[$replying]);
  968: 	%content=&unpackagemsg($message{$replying},$folder);
  969: 	$dispcrit.='<input type="hidden" name="replyid" value="'.
  970: 	    $replying.'" />';
  971: 	$func=&mt('Send Reply to');
  972: 	
  973: 	$dissub=&mt('Reply').': '.$content{'subject'};       
  974: 	$dismsg='> '.$content{'message'};
  975: 	$dismsg=~s/\r/\n/g;
  976: 	$dismsg=~s/\f/\n/g;
  977: 	$dismsg=~s/\n+/\n\> /g;
  978:     }
  979:     if ($ENV{'form.recdom'}) { $defdom=$ENV{'form.recdom'}; }
  980:       $r->print(
  981:                 '<form action="/adm/email"  name="compemail" method="post"'.
  982:                 ' enctype="multipart/form-data">'."\n".
  983:                 '<input type="hidden" name="sendmail" value="on" />'."\n".
  984:                 '<table>');
  985:     unless (($broadcast eq 'group') || ($broadcast eq 'upload')) {
  986: 	if ($replying) {
  987: 	    $r->print('<tr><td colspan="2">'.&mt('Replying to').' '.
  988: 		      &Apache::loncommon::aboutmewrapper(
  989: 							 &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).' ('.
  990: 		      $content{'sendername'}.'@'.
  991: 		      $content{'senderdomain'}.')'.
  992: 		      '<input type="hidden" name="recuname" value="'.$content{'sendername'}.'" />'.
  993: 		      '<input type="hidden" name="recdomain" value="'.$content{'senderdomain'}.'" />'.
  994: 		      '</td></tr>');
  995: 	} else {
  996: 	    my $domform = &Apache::loncommon::select_dom_form($defdom,'recdomain');
  997: 	    my $selectlink=&Apache::loncommon::selectstudent_link
  998: 	    ('compemail','recuname','recdomain');
  999: 	    $r->print(<<"ENDREC");
 1000: <tr><td>$lt{'us'}:</td><td><input type="text" size="12" name="recuname" value="$ENV{'form.recname'}"></td><td rowspan="2">$selectlink</td></tr>
 1001: <tr><td>$lt{'do'}:</td>
 1002: <td>$domform</td></tr>
 1003: ENDREC
 1004:         }
 1005:     }
 1006:     my $latexHelp = Apache::loncommon::helpLatexCheatsheet();
 1007:     if ($broadcast ne 'upload') {
 1008:        $r->print(<<"ENDCOMP");
 1009: <tr><td>$lt{'ad'}<br /><tt>username\@domain,username\@domain, ...
 1010: </tt></td><td>
 1011: <input type="text" size="50" name="additionalrec" /></td></tr>
 1012: <tr><td>$lt{'sb'}:</td><td><input type="text" size="50" name="subject" value="$dissub" />
 1013: </td></tr></table>
 1014: $latexHelp
 1015: <textarea name="message" cols="80" rows="15" wrap="hard">$dismsg
 1016: </textarea></p><br />
 1017: $dispcrit
 1018: <input type="submit" name="send" value="$func $lt{'ma'}" />
 1019: <input type="submit" name="cancel" value="$lt{'ca'}" />
 1020: ENDCOMP
 1021:     } else { # $broadcast is 'upload'
 1022: 	$r->print(<<ENDUPLOAD);
 1023: <input type="hidden" name="sendmode" value="upload" />
 1024: <input type="hidden" name="send" value="on" />
 1025: <h3>Generate messages from a file</h3>
 1026: <p>
 1027: Subject: <input type="text" size="50" name="subject" />
 1028: </p>
 1029: <p>General message text<br />
 1030: <textarea name="message" cols="60" rows="10" wrap="hard">$dismsg
 1031: </textarea></p>
 1032: <p>
 1033: The file format for the uploaded portion of the message is:
 1034: <pre>
 1035: username1\@domain1: text
 1036: username2\@domain2: text
 1037: username3\@domain1: text
 1038: </pre>
 1039: </p>
 1040: <p>
 1041: The messages will be assembled from all lines with the respective 
 1042: <tt>username\@domain</tt>, and appended to the general message text.</p>
 1043: <p>
 1044: <input type="file" name="upfile" size="40" /></p><p>
 1045: $dispcrit
 1046: <input type="submit" value="Upload and Send" /></p>
 1047: ENDUPLOAD
 1048:     }
 1049:     if ($broadcast eq 'group') {
 1050:        &discourse;
 1051:     }
 1052:     $r->print('</form>');
 1053: }
 1054: 
 1055: # ---------------------------------------------------- Display all face to face
 1056: 
 1057: sub retrieve_instructor_comments {
 1058:     my ($user,$domain)=@_;
 1059:     my $target=$ENV{'form.grade_target'};
 1060:     if (! $ENV{'request.course.id'}) { return; }
 1061:     if (! &Apache::lonnet::allowed('srm',$ENV{'request.course.id'})) {
 1062: 	return;
 1063:     }
 1064:     my %records=&Apache::lonnet::dump('nohist_email',
 1065: 			 $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
 1066: 			 $ENV{'course.'.$ENV{'request.course.id'}.'.num'},
 1067:                          '%255b'.$user.'%253a'.$domain.'%255d');
 1068:     my $result='';
 1069:     foreach (sort(keys(%records))) {
 1070:         my %content=&unpackagemsg($records{$_});
 1071:         next if ($content{'senderdomain'} eq '');
 1072:         next if ($content{'subject'} !~ /^Record/);
 1073:         # $content{'message'}=~s/\n/\<br\>/g;
 1074:         $result.='Recorded by '.
 1075:             $content{'sendername'}.'@'.$content{'senderdomain'}."\n";
 1076:         $result.=
 1077:             &Apache::lontexconvert::msgtexconverted($content{'message'})."\n";
 1078:      }
 1079:     return $result;
 1080: }
 1081: 
 1082: sub disfacetoface {
 1083:     my ($r,$user,$domain)=@_;
 1084:     my $target=$ENV{'form.grade_target'};
 1085:     unless ($ENV{'request.course.id'}) { return; }
 1086:     unless (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})) {
 1087: 	return;
 1088:     }
 1089:     my %records=&Apache::lonnet::dump('nohist_email',
 1090: 			 $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
 1091: 			 $ENV{'course.'.$ENV{'request.course.id'}.'.num'},
 1092:                          '%255b'.$user.'%253a'.$domain.'%255d');
 1093:     my $result='';
 1094:     foreach (sort keys %records) {
 1095:         my %content=&unpackagemsg($records{$_});
 1096:         next if ($content{'senderdomain'} eq '');
 1097:         $content{'message'}=~s/\n/\<br\>/g;
 1098:         if ($content{'subject'}=~/^Record/) {
 1099: 	    $result.='<h3>'.&mt('Record').'</h3>';
 1100:         } elsif ($content{'subject'}=~/^Broadcast/) {
 1101:             $result .='<h3>'.&mt('Broadcast Message').'</h3>';
 1102:         } else {
 1103:             $result.='<h3>'.&mt('Critical Message').'</h3>';
 1104:             %content=&unpackagemsg($content{'message'});
 1105:             $content{'message'}=
 1106:                 '<b>'.&mt('Subject').': '.$content{'subject'}.'</b><br />'.
 1107: 		$content{'message'};
 1108:         }
 1109:         $result.=&mt('By').': <b>'.
 1110: &Apache::loncommon::aboutmewrapper(
 1111:  &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).'</b> ('.
 1112: $content{'sendername'}.'@'.
 1113:             $content{'senderdomain'}.') '.$content{'time'}.
 1114:             '<br /><blockquote>'.
 1115:               &Apache::lontexconvert::msgtexconverted($content{'message'}).
 1116: 	      '</blockquote>';
 1117:      }
 1118:     # Check to see if there were any messages.
 1119:     if ($result eq '') {
 1120: 	if ($target ne 'tex') { 
 1121: 	    $r->print("<p><b>".&mt("No notes, face-to-face discussion records, critical messages, or broadcast messages in this course.")."</b></p>");
 1122: 	} else {
 1123: 	    $r->print('\textbf{'.&mt("No notes, face-to-face discussion records, critical messages or broadcast messages in this course.").'}\\\\');
 1124: 	}
 1125:     } else {
 1126:        $r->print($result);
 1127:     }
 1128: }
 1129: 
 1130: # ---------------------------------------------------------------- Face to face
 1131: 
 1132: sub facetoface {
 1133:     my ($r,$stage)=@_;
 1134:     unless (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})) {
 1135: 	return;
 1136:     }
 1137:     &printheader($r,
 1138: 		 '/adm/email?recordftf=query',
 1139: 		 "User Notes, Face-to-Face, Critical Messages, Broadcast Messages");
 1140: # from query string
 1141: 
 1142:     if ($ENV{'form.recname'}) { $ENV{'form.recuname'}=$ENV{'form.recname'}; }
 1143:     if ($ENV{'form.recdom'}) { $ENV{'form.recdomain'}=$ENV{'form.recdom'}; }
 1144: 
 1145:     my $defdom=$ENV{'user.domain'};
 1146: # already filled in
 1147:     if ($ENV{'form.recdomain'}) { $defdom=$ENV{'form.recdomain'}; }
 1148: # generate output
 1149:     my $domform = &Apache::loncommon::select_dom_form($defdom,'recdomain');
 1150:     my $stdbrws = &Apache::loncommon::selectstudent_link
 1151: 	('stdselect','recuname','recdomain');
 1152:     my %lt=&Apache::lonlocal::texthash('user' => 'Username',
 1153: 				       'dom' => 'Domain',
 1154: 				       'head' => 'User Notes, Records of Face-To-Face Discussions, Critical Messages, and Broadcast Messages in Course',
 1155: 				       'subm' => 'Retrieve discussion and message records',
 1156: 				       'newr' => 'New Record (record is visible to course faculty and staff)',
 1157: 				       'post' => 'Post this Record');
 1158:     $r->print(<<"ENDTREC");
 1159: <h3>$lt{'head'}</h3>
 1160: <form method="post" action="/adm/email" name="stdselect">
 1161: <input type="hidden" name="recordftf" value="retrieve" />
 1162: <table>
 1163: <tr><td>$lt{'user'}:</td><td><input type="text" size="12" name="recuname" value="$ENV{'form.recuname'}" /></td>
 1164: <td rowspan="2">
 1165: $stdbrws
 1166: <input type="submit" value="$lt{'subm'}" /></td>
 1167: </tr>
 1168: <tr><td>$lt{'dom'}:</td>
 1169: <td>$domform</td></tr>
 1170: </table>
 1171: </form>
 1172: ENDTREC
 1173:     if (($stage ne 'query') &&
 1174:         ($ENV{'form.recdomain'}) && ($ENV{'form.recuname'})) {
 1175:         chomp($ENV{'form.newrecord'});
 1176:         if ($ENV{'form.newrecord'}) {
 1177:            &user_normal_msg_raw(
 1178:             $ENV{'course.'.$ENV{'request.course.id'}.'.num'},
 1179:             $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
 1180:             &mt('Record').
 1181: 	     ' ['.$ENV{'form.recuname'}.':'.$ENV{'form.recdomain'}.']',
 1182: 	    $ENV{'form.newrecord'});
 1183:         }
 1184:         $r->print('<h3>'.&Apache::loncommon::plainname($ENV{'form.recuname'},
 1185: 				     $ENV{'form.recdomain'}).'</h3>');
 1186:         &disfacetoface($r,$ENV{'form.recuname'},$ENV{'form.recdomain'});
 1187: 	$r->print(<<ENDRHEAD);
 1188: <form method="post" action="/adm/email">
 1189: <input name="recdomain" value="$ENV{'form.recdomain'}" type="hidden" />
 1190: <input name="recuname" value="$ENV{'form.recuname'}" type="hidden" />
 1191: ENDRHEAD
 1192:         $r->print(<<ENDBFORM);
 1193: <hr />$lt{'newr'}<br />
 1194: <textarea name="newrecord" cols="80" rows="10" wrap="hard"></textarea>
 1195: <br />
 1196: <input type="hidden" name="recordftf" value="post" />
 1197: <input type="submit" value="$lt{'post'}" />
 1198: </form>
 1199: ENDBFORM
 1200:     }
 1201: }
 1202: 
 1203: # ----------------------------------------------------------- Blocking during exams
 1204: 
 1205: sub examblock {
 1206:     my ($r,$action) = @_;
 1207:     unless ($ENV{'request.course.id'}) { return;}
 1208:     unless (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})) { $r->print('Not allowed'); }
 1209:     my %lt=&Apache::lonlocal::texthash(
 1210:             'comb' => 'Communication Blocking',
 1211:             'cbds' => 'Communication blocking during scheduled exams',
 1212:             '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.',
 1213:              'mecb' => 'Modify existing communication blocking periods',
 1214:              'ncbc' => 'No communication blocks currently stored'
 1215:     );
 1216: 
 1217:     my %ltext = &Apache::lonlocal::texthash(
 1218:             'dura' => 'Duration',
 1219:             'setb' => 'Set by',
 1220:             'even' => 'Event',
 1221:             'actn' => 'Action',
 1222:             'star' => 'Start',
 1223:             'endd' => 'End'
 1224:     );
 1225: 
 1226:     &printheader($r,'/adm/email?block=display',$lt{'comb'});
 1227:     $r->print('<h3>'.$lt{'cbds'}.'</h3>');
 1228: 
 1229:     if ($action eq 'store') {
 1230:         &blockstore($r);
 1231:     }
 1232: 
 1233:     $r->print($lt{'desc'}.'<br /><br />
 1234:                <form name="blockform" method="post" action="/adm/email?block=store">
 1235:              ');
 1236: 
 1237:     $r->print('<h4>'.$lt{'mecb'}.'</h4>');
 1238:     my %records = ();
 1239:     my $blockcount = 0;
 1240:     my $parmcount = 0;
 1241:     &get_blockdates(\%records,\$blockcount);
 1242:     if ($blockcount > 0) {
 1243:         $parmcount = &display_blocker_status($r,\%records,\%ltext);
 1244:     } else {
 1245:         $r->print($lt{'ncbc'}.'<br /><br />');
 1246:     }
 1247:     &display_addblocker_table($r,$parmcount,\%ltext);
 1248:     $r->print(<<"END");
 1249: <br />
 1250: <input type="hidden" name="blocktotal" value="$blockcount" />
 1251: <input type ="submit" value="Save Changes" />
 1252: </form>
 1253: </body>
 1254: </html>
 1255: END
 1256:     return;
 1257: }
 1258: 
 1259: sub blockstore {
 1260:     my $r = shift;
 1261:     my %lt=&Apache::lonlocal::texthash(
 1262:             'tfcm' => 'The following changes were made',
 1263:             'cbps' => 'communication blocking period(s)',
 1264:             'werm' => 'was/were removed',
 1265:             'wemo' => 'was/were modified',
 1266:             'wead' => 'was/were added',
 1267:             'ncwm' => 'No changes were made.' 
 1268:     );
 1269:     my %adds = ();
 1270:     my %removals = ();
 1271:     my %cancels = ();
 1272:     my $modtotal = 0;
 1273:     my $canceltotal = 0;
 1274:     my $addtotal = 0;
 1275:     my %blocking = ();
 1276:     $r->print('<h3>'.$lt{'head'}.'</h3>');
 1277:     foreach (keys %ENV) {
 1278:         if ($_ =~ m/^form\.modify_(\w+)$/) {
 1279:             $adds{$1} = $1;
 1280:             $removals{$1} = $1;
 1281:             $modtotal ++;
 1282:         } elsif ($_ =~ m/^form\.cancel_(\d+)$/) {
 1283:             $cancels{$1} = $1;
 1284:             unless ( defined($removals{$1}) ) {
 1285:                 $removals{$1} = $1;
 1286:                 $canceltotal ++;
 1287:             }
 1288:         } elsif ($_ =~ m/^form\.add_(\d+)$/) {
 1289:             $adds{$1} = $1;
 1290:             $addtotal ++;
 1291:         }
 1292:     }
 1293: 
 1294:     foreach (keys %removals) {
 1295:         my $hashkey = $ENV{'form.key_'.$_};
 1296:         &Apache::lonnet::del('comm_block',["$hashkey"],
 1297:                          $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
 1298:                          $ENV{'course.'.$ENV{'request.course.id'}.'.num'}
 1299:                          );
 1300:     }
 1301:     foreach (keys %adds) {
 1302:         unless ( defined($cancels{$_}) ) {
 1303:             my ($newstart,$newend) = &get_dates_from_form($_);
 1304:             my $newkey = $newstart.'____'.$newend;
 1305:             $blocking{$newkey} = $ENV{'user.name'}.'@'.$ENV{'user.domain'}.':'.$ENV{'form.title_'.$_};
 1306:         }
 1307:     }
 1308:     if ($addtotal + $modtotal > 0) {
 1309:         &Apache::lonnet::put('comm_block',\%blocking,
 1310:                      $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
 1311:                      $ENV{'course.'.$ENV{'request.course.id'}.'.num'}
 1312:                      );
 1313:     }
 1314:     my $chgestotal = $canceltotal + $modtotal + $addtotal;
 1315:     if ($chgestotal > 0) {
 1316:         $r->print($lt{'tfcm'}.'<ul>');
 1317:         if ($canceltotal > 0) {
 1318:             $r->print('<li>'.$canceltotal.' '.$lt{'cbps'},' '.$lt{'werm'}.'</li>');
 1319:         }
 1320:         if ($modtotal > 0) {
 1321:             $r->print('<li>'.$modtotal.' '.$lt{'cbps'},' '.$lt{'wemo'}.'</li>');
 1322:         }
 1323:         if ($addtotal > 0) {
 1324:             $r->print('<li>'.$addtotal.' '.$lt{'cbps'},' '.$lt{'wead'}.'</li>');
 1325:         }
 1326:         $r->print('</ul>');
 1327:     } else {
 1328:         $r->print($lt{'ncwm'});
 1329:     }
 1330:     $r->print('<br />');
 1331:     return;
 1332: }
 1333: 
 1334: sub get_dates_from_form {
 1335:     my $item = shift;
 1336:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate_'.$item);
 1337:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate_'.$item);
 1338:     return ($startdate,$enddate);
 1339: }
 1340: 
 1341: sub get_blockdates {
 1342:     my ($records,$blockcount) = @_;
 1343:     $$blockcount = 0;
 1344:     %{$records} = &Apache::lonnet::dump('comm_block',
 1345:                          $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
 1346:                          $ENV{'course.'.$ENV{'request.course.id'}.'.num'}
 1347:                          );
 1348:     $$blockcount = keys %{$records};
 1349:                                                                                                              
 1350:     foreach (keys %{$records}) {
 1351:         if ($_ eq 'error: 2 tie(GDBM) Failed while attempting dump') {
 1352:             $$blockcount = 0;
 1353:             last;
 1354:         }
 1355:     }
 1356: }
 1357: 
 1358: sub display_blocker_status {
 1359:     my ($r,$records,$ltext) = @_;
 1360:     my $parmcount = 0;
 1361:     my @bgcols = ("#eeeeee","#dddddd");
 1362:     my $function = &Apache::loncommon::get_users_function();
 1363:     my $color = &Apache::loncommon::designparm($function.'.tabbg',
 1364:                                                     $ENV{'user.domain'});
 1365:     my %lt = &Apache::lonlocal::texthash(
 1366:         'modi' => 'Modify',
 1367:         'canc' => 'Cancel',
 1368:     );
 1369:     $r->print(<<"END");
 1370: <table border="0" cellpadding="0" cellspacing="0">
 1371:  <tr>
 1372:   <td width="100%" bgcolor="#000000">
 1373:    <table width="100%" border="0" cellpadding="1" cellspacing="0">
 1374:     <tr>
 1375:      <td width="100%" bgcolor="#000000">
 1376:       <table border="0" cellpadding="3" cellspacing="3" bgcolor="#FFFFFF">
 1377:        <tr bgcolor="$color">
 1378:         <td><b>$$ltext{'dura'}</b></td>
 1379:         <td><b>$$ltext{'setb'}</b></td>
 1380:         <td><b>$$ltext{'even'}</b></td>
 1381:         <td><b>$$ltext{'actn'}?</b></td>
 1382:        </tr>
 1383: END
 1384:     foreach (sort keys %{$records}) {
 1385:         my $iter = $parmcount%2;
 1386:         my $onchange = 'onFocus="javascript:window.document.forms['.
 1387:                        "'blockform'].elements['modify_".$parmcount."'].".
 1388:                        'checked=true;"';
 1389:         my ($start,$end) = split/____/,$_;
 1390:         my $startform = &Apache::lonhtmlcommon::date_setter('blockform','startdate_'.$parmcount,$start,$onchange);
 1391:         my $endform = &Apache::lonhtmlcommon::date_setter('blockform','enddate_'.$parmcount,$end,$onchange);
 1392:         my ($setter,$title) = split/:/,$$records{$_};
 1393:         my ($setuname,$setudom) = split/@/,$setter;
 1394:         my $settername = &Apache::loncommon::plainname($setuname,$setudom);
 1395:         $r->print(<<"END");
 1396:        <tr bgcolor="$bgcols[$iter]">
 1397:         <td>$$ltext{'star'}:&nbsp;$startform<br/>$$ltext{'endd'}:&nbsp;&nbsp;$endform</td>
 1398:         <td>$settername</td>
 1399:         <td><input type="text" name="title_$parmcount" size="15" value="$title"/><input type="hidden" name="key_$parmcount" value="$_"></td>
 1400:         <td>$lt{'modi'}?&nbsp;<input type="checkbox" name="modify_$parmcount"/><br />$lt{'canc'}?&nbsp;&nbsp;<input type="checkbox" name="cancel_$parmcount"/>
 1401:        </tr>
 1402: END
 1403:         $parmcount ++;
 1404:     }
 1405:     $r->print(<<"END");
 1406:       </table>
 1407:      </td>
 1408:     </tr>
 1409:    </table>
 1410:   </td>
 1411:  </tr>
 1412: </table>
 1413: <br />
 1414: <br />
 1415: END
 1416:     return $parmcount;
 1417: }
 1418: 
 1419: sub display_addblocker_table {
 1420:     my ($r,$parmcount,$ltext) = @_;
 1421:     my $start = time;
 1422:     my $end = $start + (60 * 60 * 2); #Default is an exam of 2 hours duration.
 1423:     my $onchange = 'onFocus="javascript:window.document.forms['.
 1424:                    "'blockform'].elements['add_".$parmcount."'].".
 1425:                    'checked=true;"';
 1426:     my $startform = &Apache::lonhtmlcommon::date_setter('blockform','startdate_'.$parmcount,$start,$onchange);
 1427:     my $endform = &Apache::lonhtmlcommon::date_setter('blockform','enddate_'.$parmcount,$end,$onchange);
 1428:     my $function = &Apache::loncommon::get_users_function();
 1429:     my $color = &Apache::loncommon::designparm($function.'.tabbg',
 1430:                                                     $ENV{'user.domain'});
 1431:     my %lt = &Apache::lonlocal::texthash(
 1432:         'addb' => 'Add block',
 1433:         'exam' => 'e.g., Exam 1',
 1434:         'addn' => 'Add new communication blocking periods'
 1435:     );
 1436:     $r->print(<<"END");
 1437: <h4>$lt{'addn'}</h4> 
 1438: <table border="0" cellpadding="0" cellspacing="0">
 1439:  <tr>
 1440:   <td width="100%" bgcolor="#000000">
 1441:    <table width="100%" border="0" cellpadding="1" cellspacing="0">
 1442:     <tr>
 1443:      <td width="100%" bgcolor="#000000">
 1444:       <table border="0" cellpadding="3" cellspacing="3" bgcolor="#FFFFFF">
 1445:        <tr bgcolor="#CCCCFF">
 1446:         <td><b>$$ltext{'dura'}</b></td>
 1447:         <td><b>$$ltext{'even'} $lt{'exam'}</b></td>
 1448:         <td><b>$$ltext{'actn'}?</b></td>
 1449:        </tr>
 1450:        <tr bgcolor="#eeeeee">
 1451:         <td>$$ltext{'star'}:&nbsp;$startform<br />$$ltext{'endd'}:&nbsp;&nbsp;$endform</td>
 1452:         <td><input type="text" name="title_$parmcount" size="15" value=""/></td>
 1453:         <td>$lt{'addb'}?&nbsp;<input type="checkbox" name="add_$parmcount" value="1"/></td>
 1454:        </tr>
 1455:       </table>
 1456:      </td>
 1457:     </tr>
 1458:    </table>
 1459:   </td>
 1460:  </tr>
 1461: </table>
 1462: END
 1463:     return;
 1464: }
 1465: 
 1466: sub blockcheck {
 1467:     my ($setters,$startblock,$endblock) = @_;
 1468:     # Retrieve active student roles and active course coordinator/instructor roles
 1469:     my @livecses = ();
 1470:     my @staffcses = ();
 1471:     $$startblock = 0;
 1472:     $$endblock = 0;
 1473:     foreach (keys %ENV) {
 1474:         if ($_ =~ m-^user\.role\.(st|cc|in)\./(.+)$-) {
 1475:             my $role = $1;
 1476:             my $cse = $2;
 1477:             $cse =~ s|/|_|;
 1478:             if ($ENV{$_} =~ m/^(\d*)\.(\d*)$/) {
 1479:                 unless (($2 > 0 && $2 < time) || ($1 > time)) {
 1480:                     if ($role eq 'st') {
 1481:                         push @livecses, $cse;
 1482:                     } else {
 1483:                         unless (grep/^$cse$/,@staffcses) {
 1484:                             push @staffcses, $cse;
 1485:                         }
 1486:                     }
 1487:                 }
 1488:             }
 1489:         } elsif ($_ =~ m-user\.role\.cr/(\w+)/(\w+)/([^/]+)\./(.+)$- ) { 
 1490:             my $rolepriv = $ENV{'user.role..rolesdef_'.$3};
 1491:         }
 1492:     }
 1493:     # Retrieve blocking times and identity of blocker for active courses for students.
 1494:     if (@livecses > 0) {
 1495:         foreach my $cse (@livecses) {
 1496:             my ($cdom,$crs) = split/_/,$cse;
 1497:             if ( (grep/^$cse$/,@staffcses) && ($ENV{'request.role'} !~ m-^st\./$cdom/$crs$-) ) {
 1498:                 next;
 1499:             } else {
 1500:                 %{$$setters{$cse}} = ();
 1501:                 @{$$setters{$cse}{'staff'}} = ();
 1502:                 @{$$setters{$cse}{'times'}} = ();
 1503:                 my %records = &Apache::lonnet::dump('comm_block',$cdom,$crs);
 1504:                 foreach (keys %records) {
 1505:                     if ($_ =~ m/^(\d+)____(\d+)$/) {
 1506:                         if ($1 <= time && $2 >= time) {
 1507:                             my ($staff,$title) = split/:/,$records{$_};
 1508:                             push @{$$setters{$cse}{'staff'}}, $staff;
 1509:                             push @{$$setters{$cse}{'times'}}, $_;
 1510:                             if ( ($$startblock == 0) || ($$startblock > $1) ) {
 1511:                                 $$startblock = $1;
 1512:                             }
 1513:                             if ( ($$endblock == 0) || ($$endblock < $2) ) {
 1514:                                 $$endblock = $2;
 1515:                             }
 1516:                         }
 1517:                     }
 1518:                 }
 1519:             }
 1520:         }
 1521:     }
 1522: }
 1523: 
 1524: sub build_block_table {
 1525:     my ($r,$startblock,$endblock,$setters) = @_;
 1526:     my $function = &Apache::loncommon::get_users_function();
 1527:     my $color = &Apache::loncommon::designparm($function.'.tabbg',
 1528:                                                     $ENV{'user.domain'});
 1529:     my %lt = &Apache::lonlocal::texthash(
 1530:         'cacb' => 'Currently active communication blocks',
 1531:         'cour' => 'Course',
 1532:         'dura' => 'Duration',
 1533:         'blse' => 'Block set by'
 1534:     ); 
 1535:     $r->print(<<"END");
 1536: <br /<br />$lt{'cacb'}:<br /><br />
 1537: <table border="0" cellpadding="0" cellspacing="0">
 1538:  <tr>
 1539:   <td width="100%" bgcolor="#000000">
 1540:    <table width="100%" border="0" cellpadding="1" cellspacing="0">
 1541:     <tr>
 1542:      <td width="100%" bgcolor="#000000">
 1543:       <table border="0" cellpadding="3" cellspacing="3" bgcolor="#FFFFFF">
 1544:        <tr bgcolor="$color">
 1545:         <td><b>$lt{'cour'}</b></td>
 1546:         <td><b>$lt{'dura'}</b></td>
 1547:         <td><b>$lt{'blse'}</b></td>
 1548:        </tr>
 1549: END
 1550:     foreach (keys %{$setters}) {
 1551:         my %courseinfo=&Apache::lonnet::coursedescription($_);
 1552:         for (my $i=0; $i<@{$$setters{$_}{staff}}; $i++) {
 1553:             my ($uname,$udom) = split/\@/,$$setters{$_}{staff}[$i];
 1554:             my $fullname = &Apache::loncommon::plainname($uname,$udom);
 1555:             my ($openblock,$closeblock) = split/____/,$$setters{$_}{times}[$i];
 1556:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 1557:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 1558:             $r->print('<tr><td>'.$courseinfo{'description'}.'</td>'.
 1559:                       '<td>'.$openblock.' to '.$closeblock.'</td>'.
 1560:                       '<td>'.$fullname.' ('.$uname.'@'.$udom.
 1561:                       ')</td></tr>');
 1562:         }
 1563:     }
 1564:     $r->print('</table></td></tr></table></td></tr></table>');
 1565: }
 1566: 
 1567: # ----------------------------------------------------------- Display a message
 1568: 
 1569: sub displaymessage {
 1570:     my ($r,$msgid,$folder)=@_;
 1571:     my $suffix=&foldersuffix($folder);
 1572:     my %blocked = ();
 1573:     my %setters = ();
 1574:     my $startblock = 0;
 1575:     my $endblock = 0;
 1576:     my $numblocked = 0;
 1577: # info to generate "next" and "previous" buttons and check if message is blocked
 1578:     &blockcheck(\%setters,\$startblock,\$endblock);
 1579:     my @messages=&sortedmessages(\%blocked,$startblock,$endblock,\$numblocked,$folder);
 1580:     if ( $blocked{$msgid} eq 'ON' ) {
 1581:         &printheader($r,'/adm/email',&mt('Display a Message'));
 1582:         $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.'));
 1583:         &build_block_table($r,$startblock,$endblock,\%setters);
 1584:         return;
 1585:     }
 1586:     &statuschange($msgid,'read',$folder);
 1587:     my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
 1588:     my %content=&unpackagemsg($message{$msgid});
 1589: 
 1590:     my $counter=0;
 1591:     $r->print('<pre>');
 1592:     my $escmsgid=&Apache::lonnet::escape($msgid);
 1593:     foreach (@messages) {
 1594: 	if ($_->[5] eq $escmsgid){
 1595: 	    last;
 1596: 	}
 1597: 	$counter++;
 1598:     }
 1599:     $r->print('</pre>');
 1600:     my $number_of_messages = scalar(@messages); #subtract 1 for last index
 1601: # start output
 1602:     &printheader($r,'/adm/email?display='.&Apache::lonnet::escape($msgid),'Display a Message','',$content{'baseurl'});
 1603:     my %courseinfo=&Apache::lonnet::coursedescription($content{'courseid'});
 1604: # Functions
 1605:     $r->print('<table border="2" width="100%"><tr bgcolor="#FFFFAA"><td>'.&mt('Functions').':</td>'.
 1606: 	      '<td><a href="/adm/email?replyto='.&Apache::lonnet::escape($msgid).$sqs.
 1607: 	      '"><b>'.&mt('Reply').'</b></a></td>'.
 1608: 	      '<td><a href="/adm/email?forward='.&Apache::lonnet::escape($msgid).$sqs.
 1609: 	      '"><b>'.&mt('Forward').'</b></a></td>'.
 1610: 	      '<td><a href="/adm/email?markunread='.&Apache::lonnet::escape($msgid).$sqs.
 1611: 	      '"><b>'.&mt('Mark Unread').'</b></a></td>'.
 1612: 	      '<td><a href="/adm/email?markdel='.&Apache::lonnet::escape($msgid).$sqs.
 1613: 	      '"><b>Delete</b></a></td>'.
 1614: 	      '<td><a href="/adm/email?sortedby='.$ENV{'form.sortedby'}.
 1615: 	      '&folder='.&Apache::lonnet::escape($folder).
 1616: 	      '"><b>'.&mt('Display all Messages').'</b></a></td>');
 1617:     if ($counter > 0){
 1618: 	$r->print('<td><a href="/adm/email?display='.$messages[$counter-1]->[5].$sqs.
 1619: 		  '"><b>'.&mt('Previous').'</b></a></td>');
 1620:     }
 1621:     if ($counter < $number_of_messages - 1){
 1622: 	$r->print('<td><a href="/adm/email?display='.$messages[$counter+1]->[5].$sqs.
 1623: 		  '"><b>'.&mt('Next').'</b></a></td>');
 1624:     }
 1625:     $r->print('</tr></table>');
 1626:     $r->print('<br /><b>'.&mt('Subject').':</b> '.$content{'subject'}.
 1627: 	      ($folder ne 'sent'?'<br /><b>'.&mt('From').':</b> '.
 1628: 	      &Apache::loncommon::aboutmewrapper(
 1629: 						 &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),
 1630: 						 $content{'sendername'},$content{'senderdomain'}).' ('.
 1631: 	      $content{'sendername'}.' at '.
 1632: 	      $content{'senderdomain'}.') ':'<br /><b>'.&mt('To').':</b> '.
 1633: 	      &Apache::loncommon::aboutmewrapper(
 1634: 						 &Apache::loncommon::plainname($content{'recuser'},$content{'recdomain'}),
 1635: 						 $content{'recuser'},$content{'recdomain'}).' ('.
 1636: 	      $content{'recuser'}.' at '.
 1637: 	      $content{'recdomain'}.') ').
 1638: 	      ($content{'courseid'}?'<br /><b>'.&mt('Course').':</b> '.$courseinfo{'description'}.
 1639: 	       ($content{'coursesec'}?' ('.&mt('Group/Section').': '.$content{'coursesec'}.')':''):'').
 1640: 	      '<br /><b>'.&mt('Time').':</b> '.$content{'time'}.
 1641: 	      '<p><pre>'.
 1642: 	      &Apache::lontexconvert::msgtexconverted($content{'message'},1).
 1643: 	      '</pre><hr />'.$content{'citation'}.'</p>');
 1644:     return;   
 1645: }
 1646: 
 1647: # ================================================================== The Header
 1648: 
 1649: sub header {
 1650:     my ($r,$title,$baseurl)=@_;
 1651:     $r->print('<html><head><title>Communication and Messages</title>');
 1652:     if ($baseurl) {
 1653: 	$r->print("<base href=\"http://$ENV{'SERVER_NAME'}/$baseurl\" />");
 1654:     }
 1655:     $r->print(&Apache::loncommon::studentbrowser_javascript().'</head>'.
 1656: 	      &Apache::loncommon::bodytag('Communication and Messages'));
 1657:         $r->print(&Apache::lonhtmlcommon::breadcrumbs
 1658:                   (undef,($title?$title:'Communication and Messages')));
 1659: 
 1660: }
 1661: 
 1662: # ---------------------------------------------------------------- Print header
 1663: 
 1664: sub printheader {
 1665:     my ($r,$url,$desc,$title,$baseurl)=@_;
 1666:     &Apache::lonhtmlcommon::add_breadcrumb
 1667: 	({href=>$url,
 1668: 	  text=>$desc});
 1669:     &header($r,$title,$baseurl);
 1670: }
 1671: 
 1672: 
 1673: # ===================================================================== Handler
 1674: 
 1675: sub handler {
 1676:     my $r=shift;
 1677: 
 1678: # ----------------------------------------------------------- Set document type
 1679:     
 1680:     &Apache::loncommon::content_type($r,'text/html');
 1681:     $r->send_http_header;
 1682:     
 1683:     return OK if $r->header_only;
 1684:     
 1685: # --------------------------- Get query string for limited number of parameters
 1686:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1687:         ['display','replyto','forward','markread','markdel','markunread',
 1688:          'sendreply','compose','sendmail','critical','recname','recdom',
 1689:          'recordftf','sortedby','block','folder','startdis','interdis']);
 1690:     $sqs='&sortedby='.$ENV{'form.sortedby'}.
 1691: 	 '&startdis='.$ENV{'form.startdis'}.
 1692: 	 '&interdis='.$ENV{'form.interdis'};
 1693: 
 1694: # ------------------------------------------------------ They checked for email
 1695:     unless ($ENV{'form.block'}) {
 1696:         &Apache::lonnet::put('email_status',{'recnewemail'=>0});
 1697:     }
 1698: 
 1699: # ----------------------------------------------------------------- Breadcrumbs
 1700: 
 1701:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 1702:     &Apache::lonhtmlcommon::add_breadcrumb
 1703:         ({href=>"/adm/communicate",
 1704:           text=>"Communication/Messages",
 1705:           faq=>12,bug=>'Communication Tools',});
 1706: 
 1707: # ------------------------------------------------------------------ Get Folder
 1708: 
 1709:     my $folder=$ENV{'form.folder'};
 1710:     unless ($folder) { 
 1711: 	$folder=''; 
 1712:     } else {
 1713: 	$sqs='&folder='.&Apache::lonnet::escape($folder);
 1714:     }
 1715: 
 1716: # --------------------------------------------------------------------- Display
 1717: 
 1718:     $startdis=$ENV{'form.startdis'};
 1719:     unless ($startdis) { $startdis=0; }
 1720:     $interdis=$ENV{'form.interdis'};
 1721:     unless ($interdis) { $interdis=20; }
 1722: 
 1723: # --------------------------------------------------------------- Render Output
 1724: 
 1725:     if ($ENV{'form.display'}) {
 1726: 	&displaymessage($r,$ENV{'form.display'},$folder);
 1727:     } elsif ($ENV{'form.replyto'}) {
 1728: 	&compout($r,'',$ENV{'form.replyto'},undef,undef,$folder);
 1729:     } elsif ($ENV{'form.confirm'}) {
 1730: 	&printheader($r,'','Confirmed Receipt');
 1731: 	foreach (keys %ENV) {
 1732: 	    if ($_=~/^form\.rec\_(.*)$/) {
 1733: 		$r->print('<b>'.&mt('Confirming Receipt').':</b> '.
 1734: 			  &user_crit_received($1).'<br>');
 1735: 	    }
 1736: 	    if ($_=~/^form\.reprec\_(.*)$/) {
 1737: 		my $msgid=$1;
 1738: 		$r->print('<b>'.&mt('Confirming Receipt').':</b> '.
 1739: 			  &user_crit_received($msgid).'<br>');
 1740: 		&compout($r,'','','',$msgid);
 1741: 	    }
 1742: 	}
 1743: 	&discrit($r);
 1744:     } elsif ($ENV{'form.critical'}) {
 1745: 	&printheader($r,'','Displaying Critical Messages');
 1746: 	&discrit($r);
 1747:     } elsif ($ENV{'form.forward'}) {
 1748: 	&compout($r,$ENV{'form.forward'});
 1749:     } elsif ($ENV{'form.markdel'}) {
 1750: 	&printheader($r,'','Deleted Message');
 1751: 	&statuschange($ENV{'form.markdel'},'deleted',$folder);
 1752: 	&disall($r,$folder);
 1753:     } elsif ($ENV{'form.markedmove'}) {
 1754: 	my $total=0;
 1755: 	foreach (keys %ENV) {
 1756: 	    if ($_=~/^form\.delmark_(.*)$/) {
 1757: 		&movemsg(&Apache::lonnet::unescape($1),$folder,
 1758: 			 $ENV{'form.movetofolder'});
 1759: 		$total++;
 1760: 	    }
 1761: 	}
 1762: 	&printheader($r,'','Moved Messages');
 1763: 	$r->print('Moved '.$total.' message(s)<p>');
 1764: 	&disall($r,$folder);
 1765:     } elsif ($ENV{'form.markeddel'}) {
 1766: 	my $total=0;
 1767: 	foreach (keys %ENV) {
 1768: 	    if ($_=~/^form\.delmark_(.*)$/) {
 1769: 		&statuschange(&Apache::lonnet::unescape($1),'deleted',$folder);
 1770: 		$total++;
 1771: 	    }
 1772: 	}
 1773: 	&printheader($r,'','Deleted Messages');
 1774: 	$r->print('Deleted '.$total.' message(s)<p>');
 1775: 	&disall($r,$folder);
 1776:     } elsif ($ENV{'form.markunread'}) {
 1777: 	&printheader($r,'','Marked Message as Unread');
 1778: 	&statuschange($ENV{'form.markunread'},'new');
 1779: 	&disall($r,$folder);
 1780:     } elsif ($ENV{'form.compose'}) {
 1781: 	&compout($r,'','',$ENV{'form.compose'});
 1782:     } elsif ($ENV{'form.recordftf'}) {
 1783: 	&facetoface($r,$ENV{'form.recordftf'});
 1784:     } elsif ($ENV{'form.block'}) {
 1785:         &examblock($r,$ENV{'form.block'});
 1786:     } elsif ($ENV{'form.sendmail'}) {
 1787: 	my $sendstatus='';
 1788: 	if ($ENV{'form.send'}) {
 1789: 	    &printheader($r,'','Messages being sent.');
 1790: 	    $r->rflush();
 1791: 	    my %content=();
 1792: 	    undef %content;
 1793: 	    if ($ENV{'form.forwid'}) {
 1794: 		my $msgid=$ENV{'form.forwid'};
 1795: 		my %message=&Apache::lonnet::get('nohist_email',[$msgid]);
 1796: 		%content=&unpackagemsg($message{$msgid},1);
 1797: 		&statuschange($msgid,'forwarded');
 1798: 		$ENV{'form.message'}.="\n\n-- Forwarded message --\n\n".
 1799: 		    $content{'message'};
 1800: 	    }
 1801: 	    if ($ENV{'form.replyid'}) {
 1802: 		my $msgid=$ENV{'form.replyid'};
 1803: 		my %message=&Apache::lonnet::get('nohist_email',[$msgid]);
 1804: 		%content=&unpackagemsg($message{$msgid},1);
 1805: 		&statuschange($msgid,'replied');
 1806: 	    }
 1807: 	    my %toaddr=();
 1808: 	    undef %toaddr;
 1809: 	    if ($ENV{'form.sendmode'} eq 'group') {
 1810: 		foreach (keys %ENV) {
 1811: 		    if ($_=~/^form\.send\_to\_\&\&\&[^\&]*\&\&\&\_(.+)$/) {
 1812: 			$toaddr{$1}='';
 1813: 		    }
 1814: 		}
 1815: 	    } elsif ($ENV{'form.sendmode'} eq 'upload') {
 1816: 		foreach (split(/[\n\r\f]+/,$ENV{'form.upfile'})) {
 1817: 		    my ($rec,$txt)=split(/\s*\:\s*/,$_);
 1818: 		    if ($txt) {
 1819: 			$rec=~s/\@/\:/;
 1820: 			$toaddr{$rec}.=$txt."\n";
 1821: 		    }
 1822: 		}
 1823: 	    } else {
 1824: 		$toaddr{$ENV{'form.recuname'}.':'.$ENV{'form.recdomain'}}='';
 1825: 	    }
 1826: 	    if ($ENV{'form.additionalrec'}) {
 1827: 		foreach (split(/\,/,$ENV{'form.additionalrec'})) {
 1828: 		    my ($auname,$audom)=split(/\@/,$_);
 1829: 		    $toaddr{$auname.':'.$audom}='';
 1830: 		}
 1831: 	    }
 1832: 
 1833: 	    foreach (keys %toaddr) {
 1834: 		my ($recuname,$recdomain)=split(/\:/,$_);
 1835: 		my $msgtxt=&Apache::lonfeedback::clear_out_html($ENV{'form.message'});
 1836: 		if ($toaddr{$_}) { $msgtxt.='<hr />'.$toaddr{$_}; }
 1837: 		my $thismsg;    
 1838: 		if ((($ENV{'form.critmsg'}) || ($ENV{'form.sendbck'})) && 
 1839: 		    (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'}))) {
 1840: 		    $r->print(&mt('Sending critical message').' '.$recuname.'@'.$recdomain.': ');
 1841: 		    $thismsg=&user_crit_msg($recuname,$recdomain,
 1842: 						    &Apache::lonfeedback::clear_out_html($ENV{'form.subject'}),
 1843: 						    $msgtxt,
 1844: 						    $ENV{'form.sendbck'});
 1845: 		} else {
 1846: 		    $r->print(&mt('Sending').' '.$recuname.'@'.$recdomain.': ');
 1847: 		    $thismsg=&user_normal_msg($recuname,$recdomain,
 1848: 						      &Apache::lonfeedback::clear_out_html($ENV{'form.subject'}),
 1849: 						      $msgtxt,
 1850: 						      $content{'citation'});
 1851:                     if (($ENV{'request.course.id'}) && ($ENV{'form.sendmode'} eq 'group')) {
 1852:                         &user_normal_msg_raw(
 1853:                         $ENV{'course.'.$ENV{'request.course.id'}.'.num'},
 1854:                         $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
 1855:                         'Broadcast ['.$recuname.':'.$recdomain.']',
 1856:                         $msgtxt);
 1857:                     }
 1858: 		}
 1859: 		$r->print($thismsg.'<br />');
 1860: 		$sendstatus.=' '.$thismsg;
 1861: 	    }
 1862: 	} else {
 1863: 	    &printheader($r,'','No messages sent.'); 
 1864: 	}
 1865: 	if ($sendstatus=~/^(\s*(?:ok|con_delayed)\s*)*$/) {
 1866: 	    $r->print('<br /><font color="green">'.&mt('Completed.').'</font>');
 1867: 	    if ($ENV{'form.displayedcrit'}) {
 1868: 		&discrit($r);
 1869: 	    } else {
 1870: 		&Apache::loncommunicate::menu($r);
 1871: 	    }
 1872: 	} else {
 1873: 	    $r->print(
 1874: 		      '<h2><font color="red">'.&mt('Could not deliver message').'</font></h2>'.
 1875: 		      &mt('Please use the browser "Back" button and correct the recipient addresses')
 1876: 		      );
 1877: 	}
 1878:     } elsif ($ENV{'form.newfolder'}) {
 1879: 	&printheader($r,'','New Folder');
 1880: 	&makefolder($ENV{'form.newfolder'});
 1881: 	&disall($r,$ENV{'form.newfolder'});
 1882:     } else {
 1883: 	&printheader($r,'','Display All Messages');
 1884: 	&disall($r,$folder);
 1885:     }
 1886:     $r->print('</body></html>');
 1887:     return OK;
 1888: }
 1889: # ================================================= Main program, reset counter
 1890: 
 1891: BEGIN {
 1892:     $msgcount=0;
 1893: }
 1894: 
 1895: =pod
 1896: 
 1897: =back
 1898: 
 1899: =cut
 1900: 
 1901: 1; 
 1902: 
 1903: __END__
 1904: 
 1905: 
 1906: 
 1907: 
 1908: 
 1909: 
 1910: 

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