File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.158: download - view: text, annotated - select for diffs
Mon Nov 28 20:14:43 2005 UTC (18 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Bug 4454. Replies to COM messages that were originally sent in course context now retain the same course context even if replied to in a different context.

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

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