File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.109: download - view: text, annotated - select for diffs
Tue Sep 28 14:12:40 2004 UTC (19 years, 9 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
use loncoursedata::get_classlist instead of doing the classlist dump ourselves.

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

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