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

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

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