File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.153: download - view: text, annotated - select for diffs
Tue Nov 1 15:59:18 2005 UTC (18 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #3495: preview on mail

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

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