File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.106: download - view: text, annotated - select for diffs
Fri Sep 10 06:38:24 2004 UTC (19 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Quickly saving my work on folders in COM, Trash.
Also fixed bodytag "emfo" - BTW, bodytag does its own &mt-call.

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

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