File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.144: download - view: text, annotated - select for diffs
Sat Jun 4 21:11:30 2005 UTC (19 years ago) by albertel
Branches: MAIN
CVS tags: HEAD
- bug #3715 html editor for COM style messages

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

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