File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.140: download - view: text, annotated - select for diffs
Thu Apr 7 06:56:23 2005 UTC (19 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- ENV -> env

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

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