File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.122: download - view: text, annotated - select for diffs
Sat Dec 11 14:09:46 2004 UTC (19 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Fix bug #3507. Might want make this more general - e.g., just check for &Apache::lonnet::allowed('srm',$ENV{'request.course.id'}), so that all messages (not just crit messages) sent within course context avoid translation of HTML tags to > etc., if user has srm privilege.

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

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