File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.161: download - view: text, annotated - select for diffs
Mon Dec 5 22:16:52 2005 UTC (18 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- missed an RSS box

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

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