Annotation of loncom/interface/lonmsg.pm, revision 1.119

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

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