File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.132: download - view: text, annotated - select for diffs
Mon Jan 31 11:27:14 2005 UTC (19 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Saving my work towards aspects of bugs 1290 and 3442.

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

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