File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.107: download - view: text, annotated - select for diffs
Fri Sep 10 08:42:21 2004 UTC (19 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Saving my work:
* orange on green did not look great for help link (something still fishy
with use of &mt there)
* moving between folders works now, TRASH is still not quite working right

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

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