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

1.1       www         1: # The LearningOnline Network with CAPA
1.26      albertel    2: # Routines for messaging
                      3: #
1.168     albertel    4: # $Id: lonmsg.pm,v 1.167 2006/01/03 04:17:02 raeburn 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.68      www       299: 	print $fh $body;
                    300: 	$fh->close;
                    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.140     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
                    541:     my $status='';
                    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.51      www       547:        ($msgid,$message)=&packagemsg($subject,$message,$citation,$baseurl,
1.159     raeburn   548:                                      $attachmenturl,$user,$domain,$currid);
1.108     www       549: # Store in user folder
1.4       www       550:        $status=&Apache::lonnet::critical(
                    551:            'put:'.$domain.':'.$user.':nohist_email:'.
                    552:            &Apache::lonnet::escape($msgid).'='.
                    553:            &Apache::lonnet::escape($message),$homeserver);
1.108     www       554: # Save new message received time
1.40      www       555:        &Apache::lonnet::put
                    556:                          ('email_status',{'recnewemail'=>time},$domain,$user);
1.159     raeburn   557: # Into sent-mail folder unless a broadcast message or critical message
                    558:        unless (($env{'request.course.id'}) && 
                    559:                (($env{'form.sendmode'} eq 'group')  || 
                    560:                (($env{'form.critmsg'}) || ($env{'form.sendbck'})) &&
                    561:                (&Apache::lonnet::allowed('srm',$env{'request.course.id'})))) {
1.156     raeburn   562:            $status .= &store_sent_mail($msgid,$message);
                    563:        }
1.2       www       564:     } else {
                    565:        $status='no_host';
1.53      www       566:     }
1.156     raeburn   567:     if (defined($newid)) {
                    568:         $$newid = $msgid;
                    569:     }
1.159     raeburn   570:     if (defined($sentmessage)) {
                    571:         $$sentmessage = $message;
                    572:     }
                    573: 
1.53      www       574: # Notifications
1.132     www       575:     my %userenv = &Apache::lonnet::get('environment',['notification',
                    576:                                                       'permanentemail'],
1.53      www       577:                                        $domain,$user);
                    578:     if ($userenv{'notification'}) {
1.131     www       579: 	&sendnotification($userenv{'notification'},$user,$domain,$subject,0,
                    580: 			  $text);
1.2       www       581:     }
1.132     www       582:     if ($toperm && $userenv{'permanentemail'}) {
                    583:       &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,0,
                    584: 			$text);
                    585:     }
1.140     albertel  586:     &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
                    587:                          $env{'user.home'},
1.2       www       588:       'Sending '.$msgid.' to '.$user.' at '.$domain.' with status: '.$status);
                    589:     return $status;
                    590: }
1.38      www       591: 
                    592: # New routine that respects "forward" and calls old routine
                    593: 
1.58      bowersj2  594: =pod
                    595: 
                    596: =item * B<user_normal_msg($user, $domain, $subject, $message,
                    597:     $citation, $baseurl, $attachmenturl)>: Sends a message to the
                    598:     $user at $domain, with subject $subject and message $message.
                    599: 
                    600: =cut
                    601: 
1.38      www       602: sub user_normal_msg {
1.132     www       603:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
1.159     raeburn   604: 	$toperm,$sentmessage)=@_;
1.38      www       605:     my $status='';
                    606:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
                    607:                                        $domain,$user);
                    608:     my $msgforward=$userenv{'msgforward'};
                    609:     if ($msgforward) {
                    610:        foreach (split(/\,/,$msgforward)) {
                    611: 	 my ($forwuser,$forwdomain)=split(/\:/,$_);
                    612:          $status.=
                    613: 	  &user_normal_msg_raw($forwuser,$forwdomain,$subject,$message,
1.159     raeburn   614: 	$citation,$baseurl,$attachmenturl,$toperm,undef,undef,$sentmessage).' ';
1.38      www       615:        }
                    616:     } else { 
1.49      albertel  617: 	$status=&user_normal_msg_raw($user,$domain,$subject,$message,
1.159     raeburn   618: 	    $citation,$baseurl,$attachmenturl,$toperm,undef,undef,$sentmessage);
1.38      www       619:     }
                    620:     return $status;
                    621: }
                    622: 
1.156     raeburn   623: sub store_sent_mail {
                    624:     my ($msgid,$message) = @_;
                    625:         my $status =' '.&Apache::lonnet::critical(
                    626:                    'put:'.$env{'user.domain'}.':'.$env{'user.name'}.
                    627:                                               ':nohist_email_sent:'.
                    628:                    &Apache::lonnet::escape($msgid).'='.
                    629:                    &Apache::lonnet::escape($message),$env{'user.home'});
                    630:     return $status;
                    631: }
1.2       www       632: 
1.106     www       633: # ============================================================ List all folders
                    634: 
                    635: sub folderlist {
                    636:     my $folder=shift;
                    637:     my @allfolders=&Apache::lonnet::getkeys('email_folders');
                    638:     if ($allfolders[0]=~/^error:/) { @allfolders=(); }
                    639:     return '<form method="post" action="/adm/email">'.
1.108     www       640: 	&mt('Folder').': '.
1.106     www       641: 	&Apache::loncommon::select_form($folder,'folder',
                    642: 			     ('' => &mt('INBOX'),'trash' => &mt('TRASH'),
1.114     www       643: 			      'new' => &mt('New Messages Only'),
1.113     www       644:                               'critical' => &mt('Critical'),
1.106     www       645: 			      'sent' => &mt('Sent Messages'),
                    646: 			      map { $_ => $_ } @allfolders)).
1.125     www       647: 			      ' '.&mt('Show').
                    648: 			      '<select name="interdis">'.
                    649: 			      join("\n",map { '<option value="'.$_.'"'.
                    650: 	 ($_==$interdis?' selected="selected"':'').'>'.$_.'</option>' }
                    651: 				   (10,20,50,100,200)).'</select>'.	
1.108     www       652:    '<input type="submit" value="'.&mt('View Folder').'" /><br />'.
1.140     albertel  653:     '<input type="hidden" name="sortedby" value="'.$env{'form.sortedby'}.'" />'.
1.118     www       654: 			      ($folder=~/^(new|critical)/?'</form>':'');
                    655: }
                    656: 
                    657: sub scrollbuttons {
                    658:     my ($start,$maxdis,$first,$finish,$total)=@_;
1.124     www       659:     unless ($total>0) { return ''; }
1.118     www       660:     $start++; $maxdis++;$first++;$finish++;
1.152     www       661:     return
                    662:    &mt('Page').': '. 
1.108     www       663:    '<input type="submit" name="firstview" value="'.&mt('First').'" />'.
                    664:    '<input type="submit" name="prevview" value="'.&mt('Previous').'" />'.
1.118     www       665:    '<input type="text" size="5" name="startdis" value="'.$start.'" onChange="this.form.submit()" /> of '.$maxdis.
1.108     www       666:    '<input type="submit" name="nextview" value="'.&mt('Next').'" />'.
1.118     www       667:    '<input type="submit" name="lastview" value="'.&mt('Last').'" /><br />'.
1.152     www       668:    &mt('Showing messages [_1] through [_2] of [_3]',$first,$finish,$total).'</form>';
1.106     www       669: }
1.108     www       670: 
1.106     www       671: # =============================================================== Folder suffix
                    672: 
                    673: sub foldersuffix {
                    674:     my $folder=shift;
                    675:     unless ($folder) { return ''; }
                    676:     return '_'.&Apache::lonnet::escape($folder);
                    677: }
                    678: 
1.7       www       679: # =============================================================== Status Change
                    680: 
                    681: sub statuschange {
1.106     www       682:     my ($msgid,$newstatus,$folder)=@_;
                    683:     my $suffix=&foldersuffix($folder);
                    684:     my %status=&Apache::lonnet::get('email_status'.$suffix,[$msgid]);
1.7       www       685:     if ($status{$msgid}=~/^error\:/) { $status{$msgid}=''; }
                    686:     unless ($status{$msgid}) { $status{$msgid}='new'; }
                    687:     unless (($status{$msgid} eq 'replied') || 
                    688:             ($status{$msgid} eq 'forwarded')) {
1.106     www       689: 	&Apache::lonnet::put('email_status'.$suffix,{$msgid => $newstatus});
1.7       www       690:     }
1.14      www       691:     if (($newstatus eq 'deleted') || ($newstatus eq 'new')) {
1.106     www       692: 	&Apache::lonnet::put('email_status'.$suffix,{$msgid => $newstatus});
1.14      www       693:     }
1.148     www       694:     if ($newstatus eq 'deleted') {
                    695:        &movemsg(&Apache::lonnet::unescape($msgid),$folder,'trash');
                    696:    }
1.7       www       697: }
1.14      www       698: 
1.106     www       699: # ============================================================= Make new folder
                    700: 
                    701: sub makefolder {
                    702:     my ($newfolder)=@_;
1.113     www       703:     if (($newfolder eq 'sent')
                    704:      || ($newfolder eq 'critical')
1.114     www       705:      || ($newfolder eq 'trash')
                    706:      || ($newfolder eq 'new')) { return; }
1.106     www       707:     &Apache::lonnet::put('email_folders',{$newfolder => time});
                    708: }
                    709: 
                    710: # ======================================================== Move between folders
                    711: 
                    712: sub movemsg {
                    713:     my ($msgid,$srcfolder,$trgfolder)=@_;
1.142     www       714:     if ($srcfolder eq 'new') { $srcfolder=''; }
1.106     www       715:     my $srcsuffix=&foldersuffix($srcfolder);
                    716:     my $trgsuffix=&foldersuffix($trgfolder);
1.107     www       717: 
                    718: # Copy message
                    719:     my %message=&Apache::lonnet::get('nohist_email'.$srcsuffix,[$msgid]);
                    720:     &Apache::lonnet::put('nohist_email'.$trgsuffix,{$msgid => $message{$msgid}});
                    721: 
                    722: # Copy status
1.128     www       723:     unless ($trgfolder eq 'trash') {
                    724: 	my %status=&Apache::lonnet::get('email_status'.$srcsuffix,[$msgid]);
                    725: 	&Apache::lonnet::put('email_status'.$trgsuffix,{$msgid => $status{$msgid}});
1.107     www       726:     }
                    727: # Delete orginals
1.106     www       728:     &Apache::lonnet::del('nohist_email'.$srcsuffix,[$msgid]);
1.127     www       729:     &Apache::lonnet::del('email_status'.$srcsuffix,[$msgid]);
1.106     www       730: }
                    731: 
1.17      www       732: # ======================================================= Display a course list
                    733: 
                    734: sub discourse {
                    735:     my $r=shift;
1.109     matthew   736:     my $classlist = &Apache::loncoursedata::get_classlist();
1.17      www       737:     my $now=time;
1.138     albertel  738:     my %lt=&Apache::lonlocal::texthash('cfa' => 'Check All',
                    739:             'cfs' => 'Check Section/Group',
                    740:             'cfn' => 'Uncheck All');
1.17      www       741:     $r->print(<<ENDDISHEADER);
1.92      www       742: <input type="hidden" name="sendmode" value="group" />
1.17      www       743: <script>
                    744:     function checkall() {
                    745: 	for (i=0; i<document.forms.compemail.elements.length; i++) {
                    746:             if 
                    747:           (document.forms.compemail.elements[i].name.indexOf('send_to_')==0) {
                    748: 	      document.forms.compemail.elements[i].checked=true;
                    749:             }
                    750:         }
                    751:     }
                    752: 
1.19      www       753:     function checksec() {
                    754: 	for (i=0; i<document.forms.compemail.elements.length; i++) {
                    755:             if 
                    756:           (document.forms.compemail.elements[i].name.indexOf
                    757:            ('send_to_&&&'+document.forms.compemail.chksec.value)==0) {
                    758: 	      document.forms.compemail.elements[i].checked=true;
                    759:             }
                    760:         }
                    761:     }
                    762: 
1.17      www       763:     function uncheckall() {
                    764: 	for (i=0; i<document.forms.compemail.elements.length; i++) {
                    765:             if 
                    766:           (document.forms.compemail.elements[i].name.indexOf('send_to_')==0) {
                    767: 	      document.forms.compemail.elements[i].checked=false;
                    768:             }
                    769:         }
                    770:     }
                    771: </script>
1.92      www       772: <input type="button" onClick="checkall()" value="$lt{'cfa'}" />&nbsp;
                    773: <input type="button" onClick="checksec()" value="$lt{'cfs'}" />
1.136     albertel  774: <input type="text" size="5" name="chksec" />&nbsp;
1.92      www       775: <input type="button" onClick="uncheckall()" value="$lt{'cfn'}" />
1.17      www       776: <p>
                    777: ENDDISHEADER
1.109     matthew   778:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
                    779:     $r->print('<table>');
1.61      www       780:     foreach my $role (sort keys %coursepersonnel) {
1.109     matthew   781:         foreach (split(/\,/,$coursepersonnel{$role})) {
                    782:             my ($puname,$pudom)=split(/\:/,$_);
                    783:             $r->print('<tr><td><label>'.
                    784:                       '<input type="checkbox" name="send_to_&&&&&&_'.
                    785:                       $puname.':'.$pudom.'" /> '.
                    786:                       &Apache::loncommon::plainname($puname,$pudom).
                    787:                       '</label></td>'.
                    788:                       '<td>('.$_.'),</td><td><i>'.$role.'</i></td></tr>');
                    789:         }
1.61      www       790:     }
1.110     matthew   791:     $r->print('</table><table>');
1.134     albertel  792:     my $sort = sub {
                    793: 	my $aname=lc($classlist->{$a}[&Apache::loncoursedata::CL_FULLNAME()]);
                    794: 	if (!$aname) { $aname=$a; }
                    795: 	my $bname=lc($classlist->{$b}[&Apache::loncoursedata::CL_FULLNAME()]);
                    796: 	if (!$bname) { $bname=$b; }
                    797: 	return $aname cmp $bname;
                    798:     };
                    799:     foreach my $student (sort $sort (keys(%{$classlist}))) {
                    800: 	my $info=$classlist->{$student};
1.109     matthew   801:         my ($sname,$sdom,$status,$fullname,$section) =
                    802:             (@{$info}[&Apache::loncoursedata::CL_SNAME(),
                    803:                       &Apache::loncoursedata::CL_SDOM(),
                    804:                       &Apache::loncoursedata::CL_STATUS(),
                    805:                       &Apache::loncoursedata::CL_FULLNAME(),
                    806:                       &Apache::loncoursedata::CL_SECTION()]);
1.110     matthew   807:         next if ($status ne 'Active');
1.143     albertel  808: 	next if ($env{'request.course.sec'} &&
                    809: 		 $section ne $env{'request.course.sec'});
1.129     matthew   810:         my $key = 'send_to_&&&'.$section.'&&&_'.$student;
1.109     matthew   811:         if (! defined($fullname) || $fullname eq '') { $fullname = $sname; }
                    812:         $r->print('<tr><td><label>'.
1.136     albertel  813:                   qq{<input type="checkbox" name="$key" />}.('&nbsp;'x2).
                    814:                   $fullname.'</label></td><td>'.$sname.'@'.$sdom.'</td><td>'.$section.
1.109     matthew   815:                   '</td></tr>');
1.28      harris41  816:     }
1.110     matthew   817:     $r->print('</table>');
1.17      www       818: }
                    819: 
1.13      www       820: # ==================================================== Display Critical Message
1.5       www       821: 
1.12      www       822: sub discrit {
                    823:     my $r=shift;
1.67      www       824:     my $header = '<h1><font color=red>'.&mt('Critical Messages').'</font></h1>'.
1.136     albertel  825:         '<form action="/adm/email" method="POST">'.
                    826:         '<input type="hidden" name="confirm" value="true" />';
1.30      matthew   827:     my %what=&Apache::lonnet::dump('critical');
                    828:     my $result = '';
                    829:     foreach (sort keys %what) {
                    830:         my %content=&unpackagemsg($what{$_});
                    831:         next if ($content{'senderdomain'} eq '');
1.106     www       832:         $result.='<hr />'.&mt('From').': <b>'.
1.37      www       833: &Apache::loncommon::aboutmewrapper(
                    834:  &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).'</b> ('.
                    835: $content{'sendername'}.'@'.
                    836:             $content{'senderdomain'}.') '.$content{'time'}.
1.106     www       837:             '<br />'.&mt('Subject').': '.$content{'subject'}.
1.130     albertel  838:             '<br /><pre>'.
1.36      www       839:               &Apache::lontexconvert::msgtexconverted($content{'message'}).
1.130     albertel  840:             '</pre><small>'.
1.84      www       841: &mt('You have to confirm that you received this message. After confirmation, this message will be moved to your regular inbox').
                    842:             '</small><br />'.
1.136     albertel  843:             '<input type="submit" name="rec_'.$_.'" value="'.&mt('Confirm Receipt').'" />'.
                    844:             '<input type="submit" name="reprec_'.$_.'" '.
                    845:                   'value="'.&mt('Confirm Receipt and Reply').'" />';
1.30      matthew   846:     }
                    847:     # Check to see if there were any messages.
                    848:     if ($result eq '') {
1.67      www       849:         $result = "<h2>".&mt('You have no critical messages.')."</h2>".
1.106     www       850: 	    '<a href="/adm/roles">'.&mt('Select a course').'</a><br />'.
                    851:             '<a href="/adm/email">'.&mt('Communicate').'</a>';
1.30      matthew   852:     } else {
                    853:         $r->print($header);
                    854:     }
                    855:     $r->print($result);
1.108     www       856:     $r->print('<input type="hidden" name="displayedcrit" value="true" /></form>');
1.12      www       857: }
                    858: 
1.65      www       859: sub sortedmessages {
1.106     www       860:     my ($blocked,$startblock,$endblock,$numblocked,$folder) = @_;
                    861:     my $suffix=&foldersuffix($folder);
                    862:     my @messages = &Apache::lonnet::getkeys('nohist_email'.$suffix);
1.65      www       863:     #unpack the varibles and repack into temp for sorting
                    864:     my @temp;
1.167     raeburn   865:     my %descriptions;
1.169   ! albertel  866:     my %status_cache = 
        !           867: 	&Apache::lonnet::get('email_status'.&foldersuffix($folder),\@messages);
1.65      www       868:     foreach (@messages) {
                    869: 	my $msgid=&Apache::lonnet::escape($_);
1.141     raeburn   870: 	my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$fromcid)=
1.169   ! albertel  871: 	    &Apache::lonmsg::unpackmsgid($msgid,$folder,undef,
        !           872: 					 \%status_cache);
1.167     raeburn   873:         my $description = &get_course_desc($fromcid,\%descriptions);
1.65      www       874: 	my @temp1 = ($sendtime,$shortsubj,$fromname,$fromdomain,$status,
1.157     raeburn   875: 		     $msgid,$description);
1.101     raeburn   876:         # Check whether message was sent during blocking period.
                    877:         if ($sendtime >= $startblock && ($sendtime <= $endblock && $endblock > 0) ) {
                    878:             my $escid = &Apache::lonnet::unescape($msgid);
                    879:             $$blocked{$escid} = 'ON';
                    880:             $$numblocked ++;
                    881:         } else { 
                    882:             push @temp ,\@temp1;
                    883:         }
1.65      www       884:     }
                    885:     #default sort
                    886:     @temp = sort  {$a->[0] <=> $b->[0]} @temp;    
1.140     albertel  887:     if ($env{'form.sortedby'} eq "date"){
1.65      www       888:         @temp = sort  {$a->[0] <=> $b->[0]} @temp;    
                    889:     }
1.140     albertel  890:     if ($env{'form.sortedby'} eq "revdate"){
1.65      www       891:     	@temp = sort  {$b->[0] <=> $a->[0]} @temp; 
                    892:     }
1.140     albertel  893:     if ($env{'form.sortedby'} eq "user"){
1.65      www       894: 	@temp = sort  {lc($a->[2]) cmp lc($b->[2])} @temp;
                    895:     }
1.140     albertel  896:     if ($env{'form.sortedby'} eq "revuser"){
1.65      www       897: 	@temp = sort  {lc($b->[2]) cmp lc($a->[2])} @temp;
                    898:     }
1.140     albertel  899:     if ($env{'form.sortedby'} eq "domain"){
1.65      www       900:         @temp = sort  {$a->[3] cmp $b->[3]} @temp;
                    901:     }
1.140     albertel  902:     if ($env{'form.sortedby'} eq "revdomain"){
1.65      www       903:         @temp = sort  {$b->[3] cmp $a->[3]} @temp;
                    904:     }
1.140     albertel  905:     if ($env{'form.sortedby'} eq "subject"){
1.65      www       906:         @temp = sort  {lc($a->[1]) cmp lc($b->[1])} @temp;
                    907:     }
1.140     albertel  908:     if ($env{'form.sortedby'} eq "revsubject"){
1.65      www       909:         @temp = sort  {lc($b->[1]) cmp lc($a->[1])} @temp;
                    910:     }
1.157     raeburn   911:     if ($env{'form.sortedby'} eq "course"){
                    912:         @temp = sort  {lc($a->[6]) cmp lc($b->[6])} @temp;
                    913:     }
                    914:     if ($env{'form.sortedby'} eq "revcourse"){
                    915:         @temp = sort  {lc($b->[6]) cmp lc($a->[6])} @temp;
                    916:     }
1.140     albertel  917:     if ($env{'form.sortedby'} eq "status"){
1.65      www       918:         @temp = sort  {$a->[4] cmp $b->[4]} @temp;
                    919:     }
1.140     albertel  920:     if ($env{'form.sortedby'} eq "revstatus"){
1.65      www       921:         @temp = sort  {$b->[4] cmp $a->[4]} @temp;
                    922:     }
                    923:     return @temp;
                    924: }
                    925: 
1.157     raeburn   926: sub get_course_desc {
1.167     raeburn   927:     my ($fromcid,$descriptions) = @_;
1.166     raeburn   928:     my $description;
1.167     raeburn   929:     if (!$fromcid) {
                    930:         return $description;
1.157     raeburn   931:     } else {
1.167     raeburn   932:         if (defined($$descriptions{$fromcid})) {
                    933:             $description = $$descriptions{$fromcid};
                    934:         } else {
                    935:             if (defined($env{'course.'.$fromcid.'.description'})) {
                    936:                 $description = $env{'course.'.$fromcid.'.description'};
                    937:             } else {
                    938:                 my %courseinfo=&Apache::lonnet::coursedescription($fromcid);                $description = $courseinfo{'description'};
                    939:                 $description = $courseinfo{'description'};
                    940:             }
                    941:             $$descriptions{$fromcid} = $description;
                    942:         }
                    943:         return $description;
1.157     raeburn   944:     }
                    945: }
                    946: 
1.112     www       947: # ======================================================== Display new messages
                    948: 
                    949: 
                    950: sub disnew {
                    951:     my $r=shift;
                    952:     my %lt=&Apache::lonlocal::texthash(
                    953: 				       'nm' => 'New Messages',
                    954: 				       'su' => 'Subject',
1.157     raeburn   955:                                        'co' => 'Course',
1.112     www       956: 				       'da' => 'Date',
                    957: 				       'us' => 'Username',
                    958: 				       'op' => 'Open',
                    959: 				       'do' => 'Domain'
                    960: 				       );
1.169   ! albertel  961:     my @msgids = sort(&Apache::lonnet::getkeys('nohist_email'));
1.112     www       962:     my @newmsgs;
                    963:     my %setters = ();
                    964:     my $startblock = 0;
                    965:     my $endblock = 0;
                    966:     my %blocked = ();
                    967:     my $numblocked = 0;
                    968:     # Check for blocking of display because of scheduled online exams.
                    969:     &blockcheck(\%setters,\$startblock,\$endblock);
1.169   ! albertel  970:     my %status_cache = 
        !           971: 	&Apache::lonnet::get('email_status',\@msgids);
1.167     raeburn   972:     my %descriptions;
1.112     www       973:     foreach (@msgids) {
1.169   ! albertel  974: 	my $msgid=&Apache::lonnet::escape($_);
1.141     raeburn   975:         my ($sendtime,$shortsubj,$fromname,$fromdom,$status,$fromcid)=
1.169   ! albertel  976: 	    &Apache::lonmsg::unpackmsgid($msgid,undef,undef,\%status_cache);
1.112     www       977:         if (defined($sendtime) && $sendtime!~/error/) {
1.167     raeburn   978:             my $description = &get_course_desc($fromcid,\%descriptions);
1.112     www       979:             my $numsendtime = $sendtime;
                    980:             $sendtime = &Apache::lonlocal::locallocaltime($sendtime);
                    981:             if ($status eq 'new') {
                    982:                 if ($numsendtime >= $startblock && ($numsendtime <= $endblock && $endblock > 0) ) {
                    983:                     $blocked{$_} = 'ON';
                    984:                     $numblocked ++;
                    985:                 } else {
                    986:                     push @newmsgs, { 
1.169   ! albertel  987:                         msgid    => $msgid,
1.112     www       988:                         sendtime => $sendtime,
                    989:                         shortsub => &Apache::lonnet::unescape($shortsubj),
                    990:                         from     => $fromname,
1.157     raeburn   991:                         fromdom  => $fromdom,
                    992:                         course   => $description 
1.112     www       993:                         }
                    994:                 }
                    995:             }
                    996:         }
                    997:     }
                    998:     if ($#newmsgs >= 0) {
                    999:         $r->print(<<TABLEHEAD);
                   1000: <h2>$lt{'nm'}</h2>
                   1001: <table border=2><tr><th>&nbsp</th>
1.157     raeburn  1002: <th>$lt{'da'}</th><th>$lt{'us'}</th><th>$lt{'do'}</th><th>$lt{'su'}</th><th>$lt{'co'}</th></tr>
1.112     www      1003: TABLEHEAD
                   1004:         foreach my $msg (@newmsgs) {
                   1005:             $r->print(<<"ENDLINK");
1.152     www      1006: <tr class="new" bgcolor="#FFBB77" onMouseOver="javascript:style.backgroundColor='#DD9955'" 
                   1007: onMouseOut="javascript:style.backgroundColor='#FFBB77'">
1.131     www      1008: <td><a href="/adm/email?dismode=new&display=$msg->{'msgid'}">$lt{'op'}</a></td>
1.112     www      1009: ENDLINK
1.157     raeburn  1010:             foreach ('sendtime','from','fromdom','shortsub','course') {
1.112     www      1011:                 $r->print("<td>$msg->{$_}</td>");
                   1012:             }
                   1013:             $r->print("</td></tr>");
                   1014:         }
1.139     albertel 1015:         $r->print('</table>'.&Apache::loncommon::endbodytag().'</html>');
1.112     www      1016:     } elsif ($numblocked == 0) {
                   1017:         $r->print("<h3>".&mt('You have no unread messages')."</h3>");
                   1018:     }
                   1019:     if ($numblocked > 0) {
                   1020:         my $beginblock = &Apache::lonlocal::locallocaltime($startblock);
                   1021:         my $finishblock = &Apache::lonlocal::locallocaltime($endblock);
                   1022:         if ($numblocked == 1) {
                   1023:             $r->print("<h3>".&mt('You have').' '.$numblocked.' '.&mt('blocked unread message').".</h3>");
                   1024:             $r->print(&mt('This message is not viewable because').' ');
                   1025:         } else {
                   1026:             $r->print("<h3>".&mt('You have').' '.$numblocked.' '.&mt('blocked unread messages').".</h3>");
                   1027:             $r->print(&mt('These').' '.$numblocked.' '.&mt('messages are not viewable because '));
                   1028:         }
                   1029:         $r->print(
                   1030: &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').'.');
                   1031:         &build_block_table($r,$startblock,$endblock,\%setters);
                   1032:     }
                   1033: }
                   1034: 
                   1035: 
1.15      www      1036: # ======================================================== Display all messages
                   1037: 
1.14      www      1038: sub disall {
1.106     www      1039:     my ($r,$folder)=@_;
1.113     www      1040:     $r->print(&folderlist($folder));
1.114     www      1041:     if ($folder eq 'new') {
                   1042: 	&disnew($r);
                   1043:     } elsif ($folder eq 'critical') {
                   1044: 	&discrit($r);
                   1045:     } else {
                   1046: 	&disfolder($r,$folder);
1.113     www      1047:     }
1.114     www      1048: }
                   1049: 
                   1050: # ============================================================ Display a folder
                   1051: 
                   1052: sub disfolder {
                   1053:     my ($r,$folder)=@_;
1.101     raeburn  1054:     my %blocked = ();
                   1055:     my %setters = ();
                   1056:     my $startblock;
                   1057:     my $endblock;
                   1058:     my $numblocked = 0;
                   1059:     &blockcheck(\%setters,\$startblock,\$endblock);
                   1060:     $r->print(<<ENDDISHEADER);
1.29      www      1061: <script>
                   1062:     function checkall() {
                   1063: 	for (i=0; i<document.forms.disall.elements.length; i++) {
                   1064:             if 
                   1065:           (document.forms.disall.elements[i].name.indexOf('delmark_')==0) {
                   1066: 	      document.forms.disall.elements[i].checked=true;
                   1067:             }
                   1068:         }
                   1069:     }
                   1070: 
                   1071:     function uncheckall() {
                   1072: 	for (i=0; i<document.forms.disall.elements.length; i++) {
                   1073:             if 
                   1074:           (document.forms.disall.elements[i].name.indexOf('delmark_')==0) {
                   1075: 	      document.forms.disall.elements[i].checked=false;
                   1076:             }
                   1077:         }
                   1078:     }
                   1079: </script>
                   1080: ENDDISHEADER
1.108     www      1081:     my $fsqs='&folder='.$folder;
                   1082:     my @temp=sortedmessages(\%blocked,$startblock,$endblock,\$numblocked,$folder);
                   1083:     my $totalnumber=$#temp+1;
1.124     www      1084:     unless ($totalnumber>0) {
                   1085: 	$r->print('<h2>'.&mt('Empty Folder').'</h2>');
                   1086: 	return;
                   1087:     }
1.125     www      1088:     unless ($interdis) {
                   1089: 	$interdis=20;
                   1090:     }
1.118     www      1091:     my $number=int($totalnumber/$interdis);
                   1092:     if (($startdis<0) || ($startdis>$number)) { $startdis=$number; }
1.108     www      1093:     my $firstdis=$interdis*$startdis;
                   1094:     if ($firstdis>$#temp) { $firstdis=$#temp-$interdis+1; }
                   1095:     my $lastdis=$firstdis+$interdis-1;
                   1096:     if ($lastdis>$#temp) { $lastdis=$#temp; }
1.118     www      1097:     $r->print(&scrollbuttons($startdis,$number,$firstdis,$lastdis,$totalnumber));
1.113     www      1098:     $r->print('<form method="post" name="disall" action="/adm/email">'.
1.106     www      1099: 	      '<table border=2><tr><th colspan="3">&nbsp</th><th>');
1.140     albertel 1100:     if ($env{'form.sortedby'} eq "revdate") {
1.108     www      1101: 	$r->print('<a href = "?sortedby=date'.$fsqs.'">'.&mt('Date').'</a></th>');
1.62      www      1102:     } else {
1.108     www      1103: 	$r->print('<a href = "?sortedby=revdate'.$fsqs.'">'.&mt('Date').'</a></th>');
1.62      www      1104:     }
                   1105:     $r->print('<th>');
1.140     albertel 1106:     if ($env{'form.sortedby'} eq "revuser") {
1.108     www      1107: 	$r->print('<a href = "?sortedby=user'.$fsqs.'">'.&mt('Username').'</a>');
1.62      www      1108:     } else {
1.108     www      1109: 	$r->print('<a href = "?sortedby=revuser'.$fsqs.'">'.&mt('Username').'</a>');
1.62      www      1110:     }
                   1111:     $r->print('</th><th>');
1.140     albertel 1112:     if ($env{'form.sortedby'} eq "revdomain") {
1.108     www      1113: 	$r->print('<a href = "?sortedby=domain'.$fsqs.'">'.&mt('Domain').'</a>');
1.62      www      1114:     } else {
1.108     www      1115: 	$r->print('<a href = "?sortedby=revdomain'.$fsqs.'">'.&mt('Domain').'</a>');
1.62      www      1116:     }
                   1117:     $r->print('</th><th>');
1.140     albertel 1118:     if ($env{'form.sortedby'} eq "revsubject") {
1.108     www      1119: 	$r->print('<a href = "?sortedby=subject'.$fsqs.'">'.&mt('Subject').'</a>');
1.62      www      1120:     } else {
1.108     www      1121:     	$r->print('<a href = "?sortedby=revsubject'.$fsqs.'">'.&mt('Subject').'</a>');
1.62      www      1122:     }
                   1123:     $r->print('</th><th>');
1.157     raeburn  1124:     if ($env{'form.sortedby'} eq "revcourse") {
                   1125:         $r->print('<a href = "?sortedby=course'.$fsqs.'">'.&mt('Course').'</a>');
                   1126:     } else {
                   1127:         $r->print('<a href = "?sortedby=revcourse'.$fsqs.'">'.&mt('Course').'</a>');
                   1128:     }
                   1129:     $r->print('</th><th>');
1.140     albertel 1130:     if ($env{'form.sortedby'} eq "revstatus") {
1.135     albertel 1131: 	$r->print('<a href = "?sortedby=status'.$fsqs.'">'.&mt('Status').'</a></th>');
1.62      www      1132:     } else {
1.135     albertel 1133:      	$r->print('<a href = "?sortedby=revstatus'.$fsqs.'">'.&mt('Status').'</a></th>');
1.62      www      1134:     }
1.126     www      1135:     $r->print("</tr>\n");
1.108     www      1136:     for (my $n=$firstdis;$n<=$lastdis;$n++) {
1.157     raeburn  1137: 	my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$origID,$description)= @{$temp[$n]};
1.63      albertel 1138: 	if (($status ne 'deleted') && defined($sendtime) && $sendtime!~/error/) {
1.39      albertel 1139: 	    if ($status eq 'new') {
1.152     www      1140: 		$r->print('<tr bgcolor="#FFBB77" onMouseOver="javascript:style.backgroundColor=\'#DD9955\'"  onMouseOut="javascript:style.backgroundColor=\'#FFBB77\'">');
1.39      albertel 1141: 	    } elsif ($status eq 'read') {
1.152     www      1142: 		$r->print('<tr bgcolor="#BBBB77" onMouseOver="javascript:style.backgroundColor=\'#999944\'"  onMouseOut="javascript:style.backgroundColor=\'#BBBB77\'">');
1.39      albertel 1143: 	    } elsif ($status eq 'replied') {
1.152     www      1144: 		$r->print('<tr bgcolor="#AAAA88" onMouseOver="javascript:style.backgroundColor=\'#888855\'"  onMouseOut="javascript:style.backgroundColor=\'#AAAA88\'">'); 
1.39      albertel 1145: 	    } else {
1.152     www      1146: 		$r->print('<tr bgcolor="#99BBBB" onMouseOver="javascript:style.backgroundColor=\'#669999\'"  onMouseOut="javascript:style.backgroundColor=\'#99BBBB\'">');
1.39      albertel 1147: 	    }
1.136     albertel 1148: 	    $r->print('<td><input type="checkbox" name="delmark_'.$origID.'" /></td><td><a href="/adm/email?display='.$origID.$sqs. 
1.106     www      1149: 		      '">'.&mt('Open').'</a></td><td>'.
                   1150: 		      ($folder ne 'trash'?'<a href="/adm/email?markdel='.$origID.$sqs.
1.135     albertel 1151: 		      '">'.&mt('Delete'):'&nbsp').'</a></td>'.
1.66      www      1152: 		      '<td>'.&Apache::lonlocal::locallocaltime($sendtime).'</td><td>'.
1.39      albertel 1153: 		      $fromname.'</td><td>'.$fromdomain.'</td><td>'.
1.14      www      1154: 		      &Apache::lonnet::unescape($shortsubj).'</td><td>'.
1.157     raeburn  1155:                       $description.'</td><td>'.$status.'</td></tr>'."\n");
1.106     www      1156: 	} elsif ($status eq 'deleted') {
                   1157: # purge
1.108     www      1158: 	    &movemsg(&Apache::lonnet::unescape($origID),$folder,'trash');
1.63      albertel 1159: 	}
                   1160:     }   
1.126     www      1161:     $r->print("</table>\n<p>".
1.106     www      1162:   '<a href="javascript:checkall()">'.&mt('Check All').'</a>&nbsp;'.
                   1163:   '<a href="javascript:uncheckall()">'.&mt('Uncheck All').'</a></p>'.
1.140     albertel 1164:   '<input type="hidden" name="sortedby" value="'.$env{'form.sortedby'}.'" />');
1.106     www      1165:     if ($folder ne 'trash') {
                   1166: 	$r->print(
                   1167: 	      '<p><input type="submit" name="markeddel" value="'.&mt('Delete Checked').'" /></p>');
                   1168:     }
1.118     www      1169:     $r->print('<p><input type="submit" name="markedmove" value="'.&mt('Move Checked to Folder').'" />');
1.106     www      1170:     my @allfolders=&Apache::lonnet::getkeys('email_folders');
                   1171:     if ($allfolders[0]=~/^error:/) { @allfolders=(); }
                   1172:     $r->print(
                   1173: 	&Apache::loncommon::select_form('','movetofolder',
                   1174: 			     ( map { $_ => $_ } @allfolders))
                   1175: 	      );
1.126     www      1176:     my $postedstartdis=$startdis+1;
1.140     albertel 1177:     $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  1178:     if ($numblocked > 0) {
                   1179:         my $beginblock = &Apache::lonlocal::locallocaltime($startblock);
                   1180:         my $finishblock = &Apache::lonlocal::locallocaltime($endblock);
                   1181:         $r->print('<br /><br />'.
                   1182:                   $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.'));
                   1183:         &build_block_table($r,$startblock,$endblock,\%setters);
                   1184:     }
1.14      www      1185: }
                   1186: 
1.15      www      1187: # ============================================================== Compose output
                   1188: 
                   1189: sub compout {
1.142     www      1190:     my ($r,$forwarding,$replying,$broadcast,$replycrit,$folder,$dismode)=@_;
1.121     www      1191:     my $suffix=&foldersuffix($folder);
1.92      www      1192: 
                   1193:     if ($broadcast eq 'individual') {
                   1194: 	&printheader($r,'/adm/email?compose=individual',
                   1195: 	     'Send a Message');
                   1196:     } elsif ($broadcast) {
                   1197: 	&printheader($r,'/adm/email?compose=group',
                   1198: 	     'Broadcast Message');
                   1199:     } elsif ($forwarding) {
                   1200: 	&Apache::lonhtmlcommon::add_breadcrumb
                   1201:         ({href=>"/adm/email?display=".&Apache::lonnet::escape($forwarding),
                   1202:           text=>"Display Message"});
                   1203: 	&printheader($r,'/adm/email?forward='.&Apache::lonnet::escape($forwarding),
                   1204: 	     'Forwarding a Message');
                   1205:     } elsif ($replying) {
                   1206: 	&Apache::lonhtmlcommon::add_breadcrumb
                   1207:         ({href=>"/adm/email?display=".&Apache::lonnet::escape($replying),
                   1208:           text=>"Display Message"});
                   1209: 	&printheader($r,'/adm/email?replyto='.&Apache::lonnet::escape($replying),
                   1210: 	     'Replying to a Message');
1.94      www      1211:     } elsif ($replycrit) {
                   1212: 	$r->print('<h3>'.&mt('Replying to a Critical Message').'</h3>');
                   1213: 	$replying=$replycrit;
1.92      www      1214:     } else {
                   1215: 	&printheader($r,'/adm/email?compose=upload',
                   1216: 	     'Distribute from Uploaded File');
                   1217:     }
                   1218: 
1.89      www      1219:     my $dispcrit='';
1.15      www      1220:     my $dissub='';
                   1221:     my $dismsg='';
1.115     www      1222:     my $disbase='';
1.67      www      1223:     my $func=&mt('Send New');
1.69      www      1224:     my %lt=&Apache::lonlocal::texthash('us' => 'Username',
                   1225: 				       'do' => 'Domain',
                   1226: 				       'ad' => 'Additional Recipients',
                   1227: 				       'sb' => 'Subject',
                   1228: 				       'ca' => 'Cancel',
                   1229: 				       'ma' => 'Mail');
                   1230: 
1.140     albertel 1231:     if (&Apache::lonnet::allowed('srm',$env{'request.course.id'})) {
1.35      bowersj2 1232: 	 my $crithelp = Apache::loncommon::help_open_topic("Course_Critical_Message");
1.15      www      1233:          $dispcrit=
1.136     albertel 1234:  '<p><label><input type="checkbox" name="critmsg" /> '.&mt('Send as critical message').'</label> ' . $crithelp . 
                   1235:  '</p><p>'.
                   1236:  '<label><input type="checkbox" name="sendbck" /> '.&mt('Send as critical message').'  ' .
                   1237:  &mt('and return receipt') . '</label>' . $crithelp . 
                   1238:  '</p><p><label><input type="checkbox" name="permanent" /> '.
1.154     www      1239: &mt('Send copy to permanent email address (if known)').'</label></p>'.
1.161     albertel 1240: '<!-- <p><label><input type="checkbox" name="rsspost" /> '.
                   1241: 		  &mt('Include in course RSS newsfeed').'</label></p>-->';      }
1.92      www      1242:     my %message;
                   1243:     my %content;
1.140     albertel 1244:     my $defdom=$env{'user.domain'};
1.15      www      1245:     if ($forwarding) {
1.121     www      1246: 	%message=&Apache::lonnet::get('nohist_email'.$suffix,[$forwarding]);
1.108     www      1247: 	%content=&unpackagemsg($message{$forwarding},$folder);
1.92      www      1248: 	$dispcrit.='<input type="hidden" name="forwid" value="'.
                   1249: 	    $forwarding.'" />';
                   1250: 	$func=&mt('Forward');
                   1251: 	
                   1252: 	$dissub=&mt('Forwarding').': '.$content{'subject'};
                   1253: 	$dismsg=&mt('Forwarded message from').' '.
                   1254: 	    $content{'sendername'}.' '.&mt('at').' '.$content{'senderdomain'};
1.115     www      1255: 	if ($content{'baseurl'}) {
                   1256: 	    $disbase='<input type="hidden" name="baseurl" value="'.&Apache::lonnet::escape($content{'baseurl'}).'" />';
                   1257: 	}
1.92      www      1258:     }
                   1259:     if ($replying) {
1.121     www      1260: 	%message=&Apache::lonnet::get('nohist_email'.$suffix,[$replying]);
1.108     www      1261: 	%content=&unpackagemsg($message{$replying},$folder);
1.105     albertel 1262: 	$dispcrit.='<input type="hidden" name="replyid" value="'.
                   1263: 	    $replying.'" />';
1.108     www      1264: 	$func=&mt('Send Reply to');
1.92      www      1265: 	
                   1266: 	$dissub=&mt('Reply').': '.$content{'subject'};       
                   1267: 	$dismsg='> '.$content{'message'};
                   1268: 	$dismsg=~s/\r/\n/g;
                   1269: 	$dismsg=~s/\f/\n/g;
                   1270: 	$dismsg=~s/\n+/\n\> /g;
1.115     www      1271: 	if ($content{'baseurl'}) {
                   1272: 	    $disbase='<input type="hidden" name="baseurl" value="'.&Apache::lonnet::escape($content{'baseurl'}).'" />';
1.140     albertel 1273: 	    if ($env{'user.adv'}) {
1.136     albertel 1274: 		$disbase.='<label><input type="checkbox" name="storebasecomment" />'.&mt('Store message for re-use').
                   1275: 		    '</label> <a href="/adm/email?showcommentbaseurl='.
1.120     www      1276: 		    &Apache::lonnet::escape($content{'baseurl'}).'" target="comments">'.
                   1277: 		    &mt('Show re-usable messages').'</a><br />';
1.115     www      1278: 	    }
                   1279: 	}
1.15      www      1280:     }
1.111     www      1281:     my $citation=&displayresource(%content);
1.140     albertel 1282:     if ($env{'form.recdom'}) { $defdom=$env{'form.recdom'}; }
1.22      www      1283:       $r->print(
1.31      matthew  1284:                 '<form action="/adm/email"  name="compemail" method="post"'.
                   1285:                 ' enctype="multipart/form-data">'."\n".
1.92      www      1286:                 '<input type="hidden" name="sendmail" value="on" />'."\n".
1.31      matthew  1287:                 '<table>');
1.22      www      1288:     unless (($broadcast eq 'group') || ($broadcast eq 'upload')) {
1.92      www      1289: 	if ($replying) {
                   1290: 	    $r->print('<tr><td colspan="2">'.&mt('Replying to').' '.
                   1291: 		      &Apache::loncommon::aboutmewrapper(
                   1292: 							 &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).' ('.
                   1293: 		      $content{'sendername'}.'@'.
                   1294: 		      $content{'senderdomain'}.')'.
                   1295: 		      '<input type="hidden" name="recuname" value="'.$content{'sendername'}.'" />'.
                   1296: 		      '<input type="hidden" name="recdomain" value="'.$content{'senderdomain'}.'" />'.
                   1297: 		      '</td></tr>');
                   1298: 	} else {
                   1299: 	    my $domform = &Apache::loncommon::select_dom_form($defdom,'recdomain');
                   1300: 	    my $selectlink=&Apache::loncommon::selectstudent_link
1.46      www      1301: 	    ('compemail','recuname','recdomain');
1.92      www      1302: 	    $r->print(<<"ENDREC");
1.140     albertel 1303: <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      1304: <tr><td>$lt{'do'}:</td>
1.31      matthew  1305: <td>$domform</td></tr>
1.17      www      1306: ENDREC
1.92      www      1307:         }
1.17      www      1308:     }
1.55      bowersj2 1309:     my $latexHelp = Apache::loncommon::helpLatexCheatsheet();
1.31      matthew  1310:     if ($broadcast ne 'upload') {
1.22      www      1311:        $r->print(<<"ENDCOMP");
1.69      www      1312: <tr><td>$lt{'ad'}<br /><tt>username\@domain,username\@domain, ...
1.20      www      1313: </tt></td><td>
1.91      www      1314: <input type="text" size="50" name="additionalrec" /></td></tr>
                   1315: <tr><td>$lt{'sb'}:</td><td><input type="text" size="50" name="subject" value="$dissub" />
1.15      www      1316: </td></tr></table>
1.55      bowersj2 1317: $latexHelp
1.144     albertel 1318: <textarea name="message" id="message" cols="80" rows="15" wrap="hard">$dismsg
1.69      www      1319: </textarea></p><br />
1.15      www      1320: $dispcrit
1.115     www      1321: $disbase
1.142     www      1322: <input type="hidden" name="folder" value="$folder" />
                   1323: <input type="hidden" name="dismode" value="$dismode" />
1.69      www      1324: <input type="submit" name="send" value="$func $lt{'ma'}" />
1.111     www      1325: <input type="submit" name="cancel" value="$lt{'ca'}" /><hr />
                   1326: $citation
1.15      www      1327: ENDCOMP
1.31      matthew  1328:     } else { # $broadcast is 'upload'
1.22      www      1329: 	$r->print(<<ENDUPLOAD);
1.91      www      1330: <input type="hidden" name="sendmode" value="upload" />
1.86      www      1331: <input type="hidden" name="send" value="on" />
1.22      www      1332: <h3>Generate messages from a file</h3>
1.31      matthew  1333: <p>
1.91      www      1334: Subject: <input type="text" size="50" name="subject" />
1.31      matthew  1335: </p>
                   1336: <p>General message text<br />
1.144     albertel 1337: <textarea name="message" id="message" cols="60" rows="10" wrap="hard">$dismsg
1.31      matthew  1338: </textarea></p>
                   1339: <p>
                   1340: The file format for the uploaded portion of the message is:
1.22      www      1341: <pre>
                   1342: username1\@domain1: text
                   1343: username2\@domain2: text
1.31      matthew  1344: username3\@domain1: text
1.22      www      1345: </pre>
1.31      matthew  1346: </p>
                   1347: <p>
1.22      www      1348: The messages will be assembled from all lines with the respective 
1.31      matthew  1349: <tt>username\@domain</tt>, and appended to the general message text.</p>
                   1350: <p>
1.91      www      1351: <input type="file" name="upfile" size="40" /></p><p>
1.22      www      1352: $dispcrit
1.92      www      1353: <input type="submit" value="Upload and Send" /></p>
1.22      www      1354: ENDUPLOAD
                   1355:     }
1.17      www      1356:     if ($broadcast eq 'group') {
                   1357:        &discourse;
                   1358:     }
1.144     albertel 1359:     $r->print('</form>'.
1.153     www      1360: 	      &Apache::lonfeedback::generate_preview_button('compemail','message').
1.144     albertel 1361: 	      &Apache::lonhtmlcommon::htmlareaselectactive('message'));
1.15      www      1362: }
                   1363: 
1.45      www      1364: # ---------------------------------------------------- Display all face to face
                   1365: 
1.104     matthew  1366: sub retrieve_instructor_comments {
                   1367:     my ($user,$domain)=@_;
1.140     albertel 1368:     my $target=$env{'form.grade_target'};
                   1369:     if (! $env{'request.course.id'}) { return; }
                   1370:     if (! &Apache::lonnet::allowed('srm',$env{'request.course.id'})) {
1.104     matthew  1371: 	return;
                   1372:     }
                   1373:     my %records=&Apache::lonnet::dump('nohist_email',
1.140     albertel 1374: 			 $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1375: 			 $env{'course.'.$env{'request.course.id'}.'.num'},
1.104     matthew  1376:                          '%255b'.$user.'%253a'.$domain.'%255d');
                   1377:     my $result='';
                   1378:     foreach (sort(keys(%records))) {
                   1379:         my %content=&unpackagemsg($records{$_});
                   1380:         next if ($content{'senderdomain'} eq '');
                   1381:         next if ($content{'subject'} !~ /^Record/);
1.145     albertel 1382: 	# &Apache::lonfeedback::newline_to_br(\$content{'message'});
                   1383: 	$result.='Recorded by '.
1.104     matthew  1384:             $content{'sendername'}.'@'.$content{'senderdomain'}."\n";
                   1385:         $result.=
                   1386:             &Apache::lontexconvert::msgtexconverted($content{'message'})."\n";
                   1387:      }
                   1388:     return $result;
                   1389: }
                   1390: 
1.45      www      1391: sub disfacetoface {
                   1392:     my ($r,$user,$domain)=@_;
1.140     albertel 1393:     my $target=$env{'form.grade_target'};
                   1394:     unless ($env{'request.course.id'}) { return; }
                   1395:     unless (&Apache::lonnet::allowed('srm',$env{'request.course.id'})) {
1.45      www      1396: 	return;
                   1397:     }
                   1398:     my %records=&Apache::lonnet::dump('nohist_email',
1.140     albertel 1399: 			 $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1400: 			 $env{'course.'.$env{'request.course.id'}.'.num'},
1.45      www      1401:                          '%255b'.$user.'%253a'.$domain.'%255d');
                   1402:     my $result='';
                   1403:     foreach (sort keys %records) {
                   1404:         my %content=&unpackagemsg($records{$_});
                   1405:         next if ($content{'senderdomain'} eq '');
1.145     albertel 1406: 	&Apache::lonfeedback::newline_to_br(\$content{'message'});
1.45      www      1407:         if ($content{'subject'}=~/^Record/) {
1.69      www      1408: 	    $result.='<h3>'.&mt('Record').'</h3>';
1.102     raeburn  1409:         } elsif ($content{'subject'}=~/^Broadcast/) {
                   1410:             $result .='<h3>'.&mt('Broadcast Message').'</h3>';
1.159     raeburn  1411:             if ($content{'subject'}=~/^Broadcast\./) {
                   1412:                 %content=&unpackagemsg($content{'message'});
                   1413:                 $content{'message'}=
                   1414:                     '<b>'.&mt('Subject').': '.$content{'subject'}.'</b><br />'.
                   1415:                     $content{'message'};
                   1416:             }    
1.45      www      1417:         } else {
1.102     raeburn  1418:             $result.='<h3>'.&mt('Critical Message').'</h3>';
1.45      www      1419:             %content=&unpackagemsg($content{'message'});
                   1420:             $content{'message'}=
1.92      www      1421:                 '<b>'.&mt('Subject').': '.$content{'subject'}.'</b><br />'.
1.45      www      1422: 		$content{'message'};
                   1423:         }
1.69      www      1424:         $result.=&mt('By').': <b>'.
1.45      www      1425: &Apache::loncommon::aboutmewrapper(
                   1426:  &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),$content{'sendername'},$content{'senderdomain'}).'</b> ('.
                   1427: $content{'sendername'}.'@'.
                   1428:             $content{'senderdomain'}.') '.$content{'time'}.
1.130     albertel 1429:             '<br /><pre>'.
1.45      www      1430:               &Apache::lontexconvert::msgtexconverted($content{'message'}).
1.130     albertel 1431: 	      '</pre>';
1.45      www      1432:      }
                   1433:     # Check to see if there were any messages.
                   1434:     if ($result eq '') {
1.98      sakharuk 1435: 	if ($target ne 'tex') { 
1.102     raeburn  1436: 	    $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 1437: 	} else {
1.102     raeburn  1438: 	    $r->print('\textbf{'.&mt("No notes, face-to-face discussion records, critical messages or broadcast messages in this course.").'}\\\\');
1.98      sakharuk 1439: 	}
1.45      www      1440:     } else {
                   1441:        $r->print($result);
                   1442:     }
                   1443: }
                   1444: 
1.44      www      1445: # ---------------------------------------------------------------- Face to face
                   1446: 
                   1447: sub facetoface {
                   1448:     my ($r,$stage)=@_;
1.140     albertel 1449:     unless (&Apache::lonnet::allowed('srm',$env{'request.course.id'})) {
1.44      www      1450: 	return;
                   1451:     }
1.89      www      1452:     &printheader($r,
                   1453: 		 '/adm/email?recordftf=query',
1.102     raeburn  1454: 		 "User Notes, Face-to-Face, Critical Messages, Broadcast Messages");
1.46      www      1455: # from query string
1.88      www      1456: 
1.140     albertel 1457:     if ($env{'form.recname'}) { $env{'form.recuname'}=$env{'form.recname'}; }
                   1458:     if ($env{'form.recdom'}) { $env{'form.recdomain'}=$env{'form.recdom'}; }
1.46      www      1459: 
1.140     albertel 1460:     my $defdom=$env{'user.domain'};
1.46      www      1461: # already filled in
1.140     albertel 1462:     if ($env{'form.recdomain'}) { $defdom=$env{'form.recdomain'}; }
1.46      www      1463: # generate output
1.44      www      1464:     my $domform = &Apache::loncommon::select_dom_form($defdom,'recdomain');
1.46      www      1465:     my $stdbrws = &Apache::loncommon::selectstudent_link
                   1466: 	('stdselect','recuname','recdomain');
1.88      www      1467:     my %lt=&Apache::lonlocal::texthash('user' => 'Username',
                   1468: 				       'dom' => 'Domain',
1.102     raeburn  1469: 				       'head' => 'User Notes, Records of Face-To-Face Discussions, Critical Messages, and Broadcast Messages in Course',
1.88      www      1470: 				       'subm' => 'Retrieve discussion and message records',
                   1471: 				       'newr' => 'New Record (record is visible to course faculty and staff)',
                   1472: 				       'post' => 'Post this Record');
1.44      www      1473:     $r->print(<<"ENDTREC");
1.88      www      1474: <h3>$lt{'head'}</h3>
1.46      www      1475: <form method="post" action="/adm/email" name="stdselect">
1.44      www      1476: <input type="hidden" name="recordftf" value="retrieve" />
                   1477: <table>
1.140     albertel 1478: <tr><td>$lt{'user'}:</td><td><input type="text" size="12" name="recuname" value="$env{'form.recuname'}" /></td>
1.44      www      1479: <td rowspan="2">
1.46      www      1480: $stdbrws
1.88      www      1481: <input type="submit" value="$lt{'subm'}" /></td>
1.44      www      1482: </tr>
1.88      www      1483: <tr><td>$lt{'dom'}:</td>
1.44      www      1484: <td>$domform</td></tr>
                   1485: </table>
                   1486: </form>
                   1487: ENDTREC
                   1488:     if (($stage ne 'query') &&
1.140     albertel 1489:         ($env{'form.recdomain'}) && ($env{'form.recuname'})) {
                   1490:         chomp($env{'form.newrecord'});
                   1491:         if ($env{'form.newrecord'}) {
1.159     raeburn  1492:            my $recordtxt = $env{'form.newrecord'};
1.45      www      1493:            &user_normal_msg_raw(
1.140     albertel 1494:             $env{'course.'.$env{'request.course.id'}.'.num'},
                   1495:             $env{'course.'.$env{'request.course.id'}.'.domain'},
1.88      www      1496:             &mt('Record').
1.140     albertel 1497: 	     ' ['.$env{'form.recuname'}.':'.$env{'form.recdomain'}.']',
1.159     raeburn  1498: 	    $recordtxt);
1.44      www      1499:         }
1.140     albertel 1500:         $r->print('<h3>'.&Apache::loncommon::plainname($env{'form.recuname'},
                   1501: 				     $env{'form.recdomain'}).'</h3>');
                   1502:         &disfacetoface($r,$env{'form.recuname'},$env{'form.recdomain'});
1.44      www      1503: 	$r->print(<<ENDRHEAD);
                   1504: <form method="post" action="/adm/email">
1.140     albertel 1505: <input name="recdomain" value="$env{'form.recdomain'}" type="hidden" />
                   1506: <input name="recuname" value="$env{'form.recuname'}" type="hidden" />
1.44      www      1507: ENDRHEAD
                   1508:         $r->print(<<ENDBFORM);
1.88      www      1509: <hr />$lt{'newr'}<br />
1.44      www      1510: <textarea name="newrecord" cols="80" rows="10" wrap="hard"></textarea>
1.45      www      1511: <br />
                   1512: <input type="hidden" name="recordftf" value="post" />
1.88      www      1513: <input type="submit" value="$lt{'post'}" />
1.44      www      1514: </form>
                   1515: ENDBFORM
                   1516:     }
                   1517: }
1.91      www      1518: 
1.101     raeburn  1519: # ----------------------------------------------------------- Blocking during exams
                   1520: 
                   1521: sub examblock {
                   1522:     my ($r,$action) = @_;
1.140     albertel 1523:     unless ($env{'request.course.id'}) { return;}
                   1524:     unless (&Apache::lonnet::allowed('srm',$env{'request.course.id'})) { $r->print('Not allowed'); }
1.101     raeburn  1525:     my %lt=&Apache::lonlocal::texthash(
                   1526:             'comb' => 'Communication Blocking',
                   1527:             'cbds' => 'Communication blocking during scheduled exams',
                   1528:             '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.',
                   1529:              'mecb' => 'Modify existing communication blocking periods',
                   1530:              'ncbc' => 'No communication blocks currently stored'
                   1531:     );
                   1532: 
                   1533:     my %ltext = &Apache::lonlocal::texthash(
                   1534:             'dura' => 'Duration',
                   1535:             'setb' => 'Set by',
                   1536:             'even' => 'Event',
                   1537:             'actn' => 'Action',
                   1538:             'star' => 'Start',
                   1539:             'endd' => 'End'
                   1540:     );
                   1541: 
                   1542:     &printheader($r,'/adm/email?block=display',$lt{'comb'});
                   1543:     $r->print('<h3>'.$lt{'cbds'}.'</h3>');
                   1544: 
                   1545:     if ($action eq 'store') {
                   1546:         &blockstore($r);
                   1547:     }
                   1548: 
                   1549:     $r->print($lt{'desc'}.'<br /><br />
                   1550:                <form name="blockform" method="post" action="/adm/email?block=store">
                   1551:              ');
                   1552: 
                   1553:     $r->print('<h4>'.$lt{'mecb'}.'</h4>');
                   1554:     my %records = ();
                   1555:     my $blockcount = 0;
                   1556:     my $parmcount = 0;
                   1557:     &get_blockdates(\%records,\$blockcount);
                   1558:     if ($blockcount > 0) {
                   1559:         $parmcount = &display_blocker_status($r,\%records,\%ltext);
                   1560:     } else {
                   1561:         $r->print($lt{'ncbc'}.'<br /><br />');
                   1562:     }
                   1563:     &display_addblocker_table($r,$parmcount,\%ltext);
1.139     albertel 1564:     my $endbody=&Apache::loncommon::endbodytag();
1.101     raeburn  1565:     $r->print(<<"END");
                   1566: <br />
                   1567: <input type="hidden" name="blocktotal" value="$blockcount" />
                   1568: <input type ="submit" value="Save Changes" />
                   1569: </form>
1.139     albertel 1570: $endbody
1.101     raeburn  1571: </html>
                   1572: END
                   1573:     return;
                   1574: }
                   1575: 
                   1576: sub blockstore {
                   1577:     my $r = shift;
                   1578:     my %lt=&Apache::lonlocal::texthash(
                   1579:             'tfcm' => 'The following changes were made',
                   1580:             'cbps' => 'communication blocking period(s)',
                   1581:             'werm' => 'was/were removed',
                   1582:             'wemo' => 'was/were modified',
                   1583:             'wead' => 'was/were added',
                   1584:             'ncwm' => 'No changes were made.' 
                   1585:     );
                   1586:     my %adds = ();
                   1587:     my %removals = ();
                   1588:     my %cancels = ();
                   1589:     my $modtotal = 0;
                   1590:     my $canceltotal = 0;
                   1591:     my $addtotal = 0;
                   1592:     my %blocking = ();
                   1593:     $r->print('<h3>'.$lt{'head'}.'</h3>');
1.140     albertel 1594:     foreach (keys %env) {
1.101     raeburn  1595:         if ($_ =~ m/^form\.modify_(\w+)$/) {
                   1596:             $adds{$1} = $1;
                   1597:             $removals{$1} = $1;
                   1598:             $modtotal ++;
                   1599:         } elsif ($_ =~ m/^form\.cancel_(\d+)$/) {
                   1600:             $cancels{$1} = $1;
                   1601:             unless ( defined($removals{$1}) ) {
                   1602:                 $removals{$1} = $1;
                   1603:                 $canceltotal ++;
                   1604:             }
                   1605:         } elsif ($_ =~ m/^form\.add_(\d+)$/) {
                   1606:             $adds{$1} = $1;
                   1607:             $addtotal ++;
                   1608:         }
                   1609:     }
                   1610: 
                   1611:     foreach (keys %removals) {
1.140     albertel 1612:         my $hashkey = $env{'form.key_'.$_};
1.101     raeburn  1613:         &Apache::lonnet::del('comm_block',["$hashkey"],
1.140     albertel 1614:                          $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1615:                          $env{'course.'.$env{'request.course.id'}.'.num'}
1.101     raeburn  1616:                          );
                   1617:     }
                   1618:     foreach (keys %adds) {
                   1619:         unless ( defined($cancels{$_}) ) {
                   1620:             my ($newstart,$newend) = &get_dates_from_form($_);
                   1621:             my $newkey = $newstart.'____'.$newend;
1.140     albertel 1622:             $blocking{$newkey} = $env{'user.name'}.'@'.$env{'user.domain'}.':'.$env{'form.title_'.$_};
1.101     raeburn  1623:         }
                   1624:     }
                   1625:     if ($addtotal + $modtotal > 0) {
                   1626:         &Apache::lonnet::put('comm_block',\%blocking,
1.140     albertel 1627:                      $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1628:                      $env{'course.'.$env{'request.course.id'}.'.num'}
1.101     raeburn  1629:                      );
                   1630:     }
                   1631:     my $chgestotal = $canceltotal + $modtotal + $addtotal;
                   1632:     if ($chgestotal > 0) {
                   1633:         $r->print($lt{'tfcm'}.'<ul>');
                   1634:         if ($canceltotal > 0) {
                   1635:             $r->print('<li>'.$canceltotal.' '.$lt{'cbps'},' '.$lt{'werm'}.'</li>');
                   1636:         }
                   1637:         if ($modtotal > 0) {
                   1638:             $r->print('<li>'.$modtotal.' '.$lt{'cbps'},' '.$lt{'wemo'}.'</li>');
                   1639:         }
                   1640:         if ($addtotal > 0) {
                   1641:             $r->print('<li>'.$addtotal.' '.$lt{'cbps'},' '.$lt{'wead'}.'</li>');
                   1642:         }
                   1643:         $r->print('</ul>');
                   1644:     } else {
                   1645:         $r->print($lt{'ncwm'});
                   1646:     }
                   1647:     $r->print('<br />');
                   1648:     return;
                   1649: }
                   1650: 
                   1651: sub get_dates_from_form {
                   1652:     my $item = shift;
                   1653:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate_'.$item);
                   1654:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate_'.$item);
                   1655:     return ($startdate,$enddate);
                   1656: }
                   1657: 
                   1658: sub get_blockdates {
                   1659:     my ($records,$blockcount) = @_;
                   1660:     $$blockcount = 0;
                   1661:     %{$records} = &Apache::lonnet::dump('comm_block',
1.140     albertel 1662:                          $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1663:                          $env{'course.'.$env{'request.course.id'}.'.num'}
1.101     raeburn  1664:                          );
                   1665:     $$blockcount = keys %{$records};
                   1666:                                                                                                              
                   1667:     foreach (keys %{$records}) {
                   1668:         if ($_ eq 'error: 2 tie(GDBM) Failed while attempting dump') {
                   1669:             $$blockcount = 0;
                   1670:             last;
                   1671:         }
                   1672:     }
                   1673: }
                   1674: 
                   1675: sub display_blocker_status {
                   1676:     my ($r,$records,$ltext) = @_;
                   1677:     my $parmcount = 0;
                   1678:     my @bgcols = ("#eeeeee","#dddddd");
                   1679:     my $function = &Apache::loncommon::get_users_function();
                   1680:     my $color = &Apache::loncommon::designparm($function.'.tabbg',
1.140     albertel 1681:                                                     $env{'user.domain'});
1.101     raeburn  1682:     my %lt = &Apache::lonlocal::texthash(
                   1683:         'modi' => 'Modify',
                   1684:         'canc' => 'Cancel',
                   1685:     );
                   1686:     $r->print(<<"END");
                   1687: <table border="0" cellpadding="0" cellspacing="0">
                   1688:  <tr>
                   1689:   <td width="100%" bgcolor="#000000">
                   1690:    <table width="100%" border="0" cellpadding="1" cellspacing="0">
                   1691:     <tr>
                   1692:      <td width="100%" bgcolor="#000000">
                   1693:       <table border="0" cellpadding="3" cellspacing="3" bgcolor="#FFFFFF">
                   1694:        <tr bgcolor="$color">
                   1695:         <td><b>$$ltext{'dura'}</b></td>
                   1696:         <td><b>$$ltext{'setb'}</b></td>
                   1697:         <td><b>$$ltext{'even'}</b></td>
                   1698:         <td><b>$$ltext{'actn'}?</b></td>
                   1699:        </tr>
                   1700: END
                   1701:     foreach (sort keys %{$records}) {
                   1702:         my $iter = $parmcount%2;
                   1703:         my $onchange = 'onFocus="javascript:window.document.forms['.
                   1704:                        "'blockform'].elements['modify_".$parmcount."'].".
                   1705:                        'checked=true;"';
                   1706:         my ($start,$end) = split/____/,$_;
                   1707:         my $startform = &Apache::lonhtmlcommon::date_setter('blockform','startdate_'.$parmcount,$start,$onchange);
                   1708:         my $endform = &Apache::lonhtmlcommon::date_setter('blockform','enddate_'.$parmcount,$end,$onchange);
                   1709:         my ($setter,$title) = split/:/,$$records{$_};
                   1710:         my ($setuname,$setudom) = split/@/,$setter;
                   1711:         my $settername = &Apache::loncommon::plainname($setuname,$setudom);
                   1712:         $r->print(<<"END");
                   1713:        <tr bgcolor="$bgcols[$iter]">
                   1714:         <td>$$ltext{'star'}:&nbsp;$startform<br/>$$ltext{'endd'}:&nbsp;&nbsp;$endform</td>
                   1715:         <td>$settername</td>
1.136     albertel 1716:         <td><input type="text" name="title_$parmcount" size="15" value="$title" /><input type="hidden" name="key_$parmcount" value="$_" /></td>
                   1717:         <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  1718:        </tr>
                   1719: END
                   1720:         $parmcount ++;
                   1721:     }
                   1722:     $r->print(<<"END");
                   1723:       </table>
                   1724:      </td>
                   1725:     </tr>
                   1726:    </table>
                   1727:   </td>
                   1728:  </tr>
                   1729: </table>
                   1730: <br />
                   1731: <br />
                   1732: END
                   1733:     return $parmcount;
                   1734: }
                   1735: 
                   1736: sub display_addblocker_table {
                   1737:     my ($r,$parmcount,$ltext) = @_;
                   1738:     my $start = time;
                   1739:     my $end = $start + (60 * 60 * 2); #Default is an exam of 2 hours duration.
                   1740:     my $onchange = 'onFocus="javascript:window.document.forms['.
                   1741:                    "'blockform'].elements['add_".$parmcount."'].".
                   1742:                    'checked=true;"';
                   1743:     my $startform = &Apache::lonhtmlcommon::date_setter('blockform','startdate_'.$parmcount,$start,$onchange);
                   1744:     my $endform = &Apache::lonhtmlcommon::date_setter('blockform','enddate_'.$parmcount,$end,$onchange);
                   1745:     my $function = &Apache::loncommon::get_users_function();
                   1746:     my $color = &Apache::loncommon::designparm($function.'.tabbg',
1.140     albertel 1747:                                                     $env{'user.domain'});
1.101     raeburn  1748:     my %lt = &Apache::lonlocal::texthash(
                   1749:         'addb' => 'Add block',
                   1750:         'exam' => 'e.g., Exam 1',
                   1751:         'addn' => 'Add new communication blocking periods'
                   1752:     );
                   1753:     $r->print(<<"END");
                   1754: <h4>$lt{'addn'}</h4> 
                   1755: <table border="0" cellpadding="0" cellspacing="0">
                   1756:  <tr>
                   1757:   <td width="100%" bgcolor="#000000">
                   1758:    <table width="100%" border="0" cellpadding="1" cellspacing="0">
                   1759:     <tr>
                   1760:      <td width="100%" bgcolor="#000000">
                   1761:       <table border="0" cellpadding="3" cellspacing="3" bgcolor="#FFFFFF">
                   1762:        <tr bgcolor="#CCCCFF">
                   1763:         <td><b>$$ltext{'dura'}</b></td>
                   1764:         <td><b>$$ltext{'even'} $lt{'exam'}</b></td>
                   1765:         <td><b>$$ltext{'actn'}?</b></td>
                   1766:        </tr>
                   1767:        <tr bgcolor="#eeeeee">
                   1768:         <td>$$ltext{'star'}:&nbsp;$startform<br />$$ltext{'endd'}:&nbsp;&nbsp;$endform</td>
1.136     albertel 1769:         <td><input type="text" name="title_$parmcount" size="15" value="" /></td>
                   1770:         <td><label>$lt{'addb'}?&nbsp;<input type="checkbox" name="add_$parmcount" value="1" /></label></td>
1.101     raeburn  1771:        </tr>
                   1772:       </table>
                   1773:      </td>
                   1774:     </tr>
                   1775:    </table>
                   1776:   </td>
                   1777:  </tr>
                   1778: </table>
                   1779: END
                   1780:     return;
                   1781: }
                   1782: 
                   1783: sub blockcheck {
                   1784:     my ($setters,$startblock,$endblock) = @_;
                   1785:     # Retrieve active student roles and active course coordinator/instructor roles
                   1786:     my @livecses = ();
                   1787:     my @staffcses = ();
                   1788:     $$startblock = 0;
                   1789:     $$endblock = 0;
1.140     albertel 1790:     foreach (keys %env) {
1.101     raeburn  1791:         if ($_ =~ m-^user\.role\.(st|cc|in)\./(.+)$-) {
                   1792:             my $role = $1;
                   1793:             my $cse = $2;
                   1794:             $cse =~ s|/|_|;
1.140     albertel 1795:             if ($env{$_} =~ m/^(\d*)\.(\d*)$/) {
1.101     raeburn  1796:                 unless (($2 > 0 && $2 < time) || ($1 > time)) {
                   1797:                     if ($role eq 'st') {
                   1798:                         push @livecses, $cse;
                   1799:                     } else {
                   1800:                         unless (grep/^$cse$/,@staffcses) {
                   1801:                             push @staffcses, $cse;
                   1802:                         }
                   1803:                     }
                   1804:                 }
                   1805:             }
                   1806:         } elsif ($_ =~ m-user\.role\.cr/(\w+)/(\w+)/([^/]+)\./(.+)$- ) { 
1.140     albertel 1807:             my $rolepriv = $env{'user.role..rolesdef_'.$3};
1.101     raeburn  1808:         }
                   1809:     }
                   1810:     # Retrieve blocking times and identity of blocker for active courses for students.
                   1811:     if (@livecses > 0) {
                   1812:         foreach my $cse (@livecses) {
                   1813:             my ($cdom,$crs) = split/_/,$cse;
1.140     albertel 1814:             if ( (grep/^$cse$/,@staffcses) && ($env{'request.role'} !~ m-^st\./$cdom/$crs$-) ) {
1.101     raeburn  1815:                 next;
                   1816:             } else {
                   1817:                 %{$$setters{$cse}} = ();
                   1818:                 @{$$setters{$cse}{'staff'}} = ();
                   1819:                 @{$$setters{$cse}{'times'}} = ();
                   1820:                 my %records = &Apache::lonnet::dump('comm_block',$cdom,$crs);
                   1821:                 foreach (keys %records) {
                   1822:                     if ($_ =~ m/^(\d+)____(\d+)$/) {
                   1823:                         if ($1 <= time && $2 >= time) {
                   1824:                             my ($staff,$title) = split/:/,$records{$_};
                   1825:                             push @{$$setters{$cse}{'staff'}}, $staff;
                   1826:                             push @{$$setters{$cse}{'times'}}, $_;
                   1827:                             if ( ($$startblock == 0) || ($$startblock > $1) ) {
                   1828:                                 $$startblock = $1;
                   1829:                             }
                   1830:                             if ( ($$endblock == 0) || ($$endblock < $2) ) {
                   1831:                                 $$endblock = $2;
                   1832:                             }
                   1833:                         }
                   1834:                     }
                   1835:                 }
                   1836:             }
                   1837:         }
                   1838:     }
                   1839: }
                   1840: 
                   1841: sub build_block_table {
                   1842:     my ($r,$startblock,$endblock,$setters) = @_;
                   1843:     my $function = &Apache::loncommon::get_users_function();
                   1844:     my $color = &Apache::loncommon::designparm($function.'.tabbg',
1.140     albertel 1845:                                                     $env{'user.domain'});
1.101     raeburn  1846:     my %lt = &Apache::lonlocal::texthash(
                   1847:         'cacb' => 'Currently active communication blocks',
                   1848:         'cour' => 'Course',
                   1849:         'dura' => 'Duration',
                   1850:         'blse' => 'Block set by'
                   1851:     ); 
                   1852:     $r->print(<<"END");
                   1853: <br /<br />$lt{'cacb'}:<br /><br />
                   1854: <table border="0" cellpadding="0" cellspacing="0">
                   1855:  <tr>
                   1856:   <td width="100%" bgcolor="#000000">
                   1857:    <table width="100%" border="0" cellpadding="1" cellspacing="0">
                   1858:     <tr>
                   1859:      <td width="100%" bgcolor="#000000">
                   1860:       <table border="0" cellpadding="3" cellspacing="3" bgcolor="#FFFFFF">
                   1861:        <tr bgcolor="$color">
                   1862:         <td><b>$lt{'cour'}</b></td>
                   1863:         <td><b>$lt{'dura'}</b></td>
                   1864:         <td><b>$lt{'blse'}</b></td>
                   1865:        </tr>
                   1866: END
                   1867:     foreach (keys %{$setters}) {
                   1868:         my %courseinfo=&Apache::lonnet::coursedescription($_);
                   1869:         for (my $i=0; $i<@{$$setters{$_}{staff}}; $i++) {
                   1870:             my ($uname,$udom) = split/\@/,$$setters{$_}{staff}[$i];
                   1871:             my $fullname = &Apache::loncommon::plainname($uname,$udom);
                   1872:             my ($openblock,$closeblock) = split/____/,$$setters{$_}{times}[$i];
                   1873:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
                   1874:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
                   1875:             $r->print('<tr><td>'.$courseinfo{'description'}.'</td>'.
                   1876:                       '<td>'.$openblock.' to '.$closeblock.'</td>'.
                   1877:                       '<td>'.$fullname.' ('.$uname.'@'.$udom.
                   1878:                       ')</td></tr>');
                   1879:         }
                   1880:     }
                   1881:     $r->print('</table></td></tr></table></td></tr></table>');
                   1882: }
                   1883: 
1.90      www      1884: # ----------------------------------------------------------- Display a message
                   1885: 
                   1886: sub displaymessage {
1.106     www      1887:     my ($r,$msgid,$folder)=@_;
                   1888:     my $suffix=&foldersuffix($folder);
1.101     raeburn  1889:     my %blocked = ();
                   1890:     my %setters = ();
                   1891:     my $startblock = 0;
                   1892:     my $endblock = 0;
                   1893:     my $numblocked = 0;
                   1894: # info to generate "next" and "previous" buttons and check if message is blocked
                   1895:     &blockcheck(\%setters,\$startblock,\$endblock);
1.107     www      1896:     my @messages=&sortedmessages(\%blocked,$startblock,$endblock,\$numblocked,$folder);
1.101     raeburn  1897:     if ( $blocked{$msgid} eq 'ON' ) {
                   1898:         &printheader($r,'/adm/email',&mt('Display a Message'));
                   1899:         $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.'));
                   1900:         &build_block_table($r,$startblock,$endblock,\%setters);
                   1901:         return;
                   1902:     }
1.107     www      1903:     &statuschange($msgid,'read',$folder);
1.106     www      1904:     my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
1.90      www      1905:     my %content=&unpackagemsg($message{$msgid});
1.107     www      1906: 
1.90      www      1907:     my $counter=0;
                   1908:     $r->print('<pre>');
                   1909:     my $escmsgid=&Apache::lonnet::escape($msgid);
                   1910:     foreach (@messages) {
                   1911: 	if ($_->[5] eq $escmsgid){
                   1912: 	    last;
                   1913: 	}
                   1914: 	$counter++;
                   1915:     }
                   1916:     $r->print('</pre>');
                   1917:     my $number_of_messages = scalar(@messages); #subtract 1 for last index
                   1918: # start output
1.92      www      1919:     &printheader($r,'/adm/email?display='.&Apache::lonnet::escape($msgid),'Display a Message','',$content{'baseurl'});
1.90      www      1920:     my %courseinfo=&Apache::lonnet::coursedescription($content{'courseid'});
                   1921: # Functions
                   1922:     $r->print('<table border="2" width="100%"><tr bgcolor="#FFFFAA"><td>'.&mt('Functions').':</td>'.
                   1923: 	      '<td><a href="/adm/email?replyto='.&Apache::lonnet::escape($msgid).$sqs.
                   1924: 	      '"><b>'.&mt('Reply').'</b></a></td>'.
                   1925: 	      '<td><a href="/adm/email?forward='.&Apache::lonnet::escape($msgid).$sqs.
                   1926: 	      '"><b>'.&mt('Forward').'</b></a></td>'.
                   1927: 	      '<td><a href="/adm/email?markunread='.&Apache::lonnet::escape($msgid).$sqs.
                   1928: 	      '"><b>'.&mt('Mark Unread').'</b></a></td>'.
                   1929: 	      '<td><a href="/adm/email?markdel='.&Apache::lonnet::escape($msgid).$sqs.
1.148     www      1930: 	      '"><b>'.&mt('Delete').'</b></a></td>'.
1.125     www      1931: 	      '<td><a href="/adm/email?'.$sqs.
1.140     albertel 1932: 	      ($env{'form.dismode'} eq 'new'?'&folder=new':'').
1.125     www      1933: 	      '"><b>'.&mt('Back to Folder Display').'</b></a></td>');
1.90      www      1934:     if ($counter > 0){
                   1935: 	$r->print('<td><a href="/adm/email?display='.$messages[$counter-1]->[5].$sqs.
                   1936: 		  '"><b>'.&mt('Previous').'</b></a></td>');
                   1937:     }
                   1938:     if ($counter < $number_of_messages - 1){
                   1939: 	$r->print('<td><a href="/adm/email?display='.$messages[$counter+1]->[5].$sqs.
                   1940: 		  '"><b>'.&mt('Next').'</b></a></td>');
                   1941:     }
                   1942:     $r->print('</tr></table>');
1.146     www      1943:     if ($env{'user.adv'}) {
                   1944: 	$r->print('<table border="2" width="100%"><tr bgcolor="#FFAAAA"><td>'.&mt('Currently available actions (will open extra window)').':</td>');
1.151     www      1945: 	my $symb=&Apache::lonnet::symbread($content{'baseurl'});      
1.146     www      1946: 	if (&Apache::lonnet::allowed('vgr',$env{'request.course.id'})) {
                   1947: 		$r->print('<td><b>'.&Apache::loncommon::track_student_link(&mt('View recent activity'),$content{'sendername'},$content{'senderdomain'},'check').'</b></td>');
                   1948: 	    }
1.151     www      1949: 	if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) && $symb) {
1.147     www      1950: 	    $r->print('<td><b>'.&Apache::loncommon::pprmlink(&mt('Set/Change parameters'),$content{'sendername'},$content{'senderdomain'},$symb,'check').'</b></td>');
1.146     www      1951: 	}
1.151     www      1952: 	if (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}) && $symb) {
1.147     www      1953: 	    $r->print('<td><b>'.&Apache::loncommon::pgrdlink(&mt('Set/Change grades'),$content{'sendername'},$content{'senderdomain'},$symb,'check').'</b></td>');
1.146     www      1954: 	}
                   1955: 	$r->print('</tr></table>');
                   1956:     }
1.156     raeburn  1957:     my $tolist;
                   1958:     my @recipients = ();
                   1959:     for (my $i=0; $i<@{$content{'recuser'}}; $i++) {
                   1960:         $recipients[$i] =  &Apache::loncommon::aboutmewrapper(
                   1961:            &Apache::loncommon::plainname($content{'recuser'}[$i],
                   1962:                                       $content{'recdomain'}[$i]),
                   1963:               $content{'recuser'}[$i],$content{'recdomain'}[$i]).
                   1964:        ' ('.$content{'recuser'}[$i].' at '.$content{'recdomain'}[$i].') ';
                   1965:     }
                   1966:     $tolist = join(', ',@recipients);
1.90      www      1967:     $r->print('<br /><b>'.&mt('Subject').':</b> '.$content{'subject'}.
1.108     www      1968: 	      ($folder ne 'sent'?'<br /><b>'.&mt('From').':</b> '.
1.90      www      1969: 	      &Apache::loncommon::aboutmewrapper(
                   1970: 						 &Apache::loncommon::plainname($content{'sendername'},$content{'senderdomain'}),
                   1971: 						 $content{'sendername'},$content{'senderdomain'}).' ('.
                   1972: 	      $content{'sendername'}.' at '.
1.108     www      1973: 	      $content{'senderdomain'}.') ':'<br /><b>'.&mt('To').':</b> '.
1.156     raeburn  1974:               $tolist).
1.90      www      1975: 	      ($content{'courseid'}?'<br /><b>'.&mt('Course').':</b> '.$courseinfo{'description'}.
                   1976: 	       ($content{'coursesec'}?' ('.&mt('Group/Section').': '.$content{'coursesec'}.')':''):'').
                   1977: 	      '<br /><b>'.&mt('Time').':</b> '.$content{'time'}.
1.115     www      1978: 	      ($content{'baseurl'}?'<br /><b>'.&mt('Refers to').':</b> <a href="'.$content{'baseurl'}.'">'.
                   1979: 	       $content{'baseurl'}.' ('.&Apache::lonnet::gettitle($content{'baseurl'}).')</a>':'').
1.90      www      1980: 	      '<p><pre>'.
                   1981: 	      &Apache::lontexconvert::msgtexconverted($content{'message'},1).
1.111     www      1982: 	      '</pre><hr />'.&displayresource(%content).'</p>');
1.90      www      1983:     return;   
                   1984: }
1.44      www      1985: 
1.111     www      1986: # =========================================================== Show the citation
                   1987: 
                   1988: sub displayresource {
                   1989:     my %content=@_;
                   1990: #
                   1991: # If the recipient is in the same course that the message was sent from and
                   1992: # has sufficient privileges, show "all details," else show citation
                   1993: #
1.140     albertel 1994:     if (($env{'request.course.id'} eq $content{'courseid'})
1.111     www      1995:      && (&Apache::lonnet::allowed('vgr',$content{'courseid'}))) {
                   1996: 	my $symb=&Apache::lonnet::symbread($content{'baseurl'});
                   1997: # Could not get a symb, give up
                   1998: 	unless ($symb) { return $content{'citation'}; }
                   1999: # Have a symb, can render
                   2000: 	return '<h2>'.&mt('Current attempts of student (if applicable)').'</h2>'.
                   2001: 	    &Apache::loncommon::get_previous_attempt($symb,
                   2002: 						     $content{'sendername'},
                   2003: 						     $content{'senderdomain'},
                   2004: 						     $content{'courseid'}).
                   2005: 	    '<hr /><h2>'.&mt('Current screen output (if applicable)').'</h2>'.
                   2006: 	    &Apache::loncommon::get_student_view($symb,
                   2007: 						 $content{'sendername'},
                   2008: 						 $content{'senderdomain'},
                   2009: 						 $content{'courseid'}).
                   2010: 	    '<h2>'.&mt('Correct Answer(s) (if applicable)').'</h2>'.
                   2011: 	    &Apache::loncommon::get_student_answers($symb,
                   2012: 						    $content{'sendername'},
                   2013: 						    $content{'senderdomain'},
                   2014: 						    $content{'courseid'});
                   2015:     } else {
                   2016: 	return $content{'citation'};
                   2017:     }
                   2018: }
                   2019: 
1.88      www      2020: # ================================================================== The Header
                   2021: 
                   2022: sub header {
1.90      www      2023:     my ($r,$title,$baseurl)=@_;
1.137     albertel 2024:     $r->print(&Apache::lonxml::xmlbegin().
                   2025: 	      '<head>'.&Apache::lonxml::fontsettings().
1.144     albertel 2026: 	      '<title>Communication and Messages</title>'.
                   2027: 	      &Apache::lonhtmlcommon::htmlareaheaders());
1.88      www      2028:     if ($baseurl) {
                   2029: 	$r->print("<base href=\"http://$ENV{'SERVER_NAME'}/$baseurl\" />");
                   2030:     }
                   2031:     $r->print(&Apache::loncommon::studentbrowser_javascript().'</head>'.
                   2032: 	      &Apache::loncommon::bodytag('Communication and Messages'));
                   2033:         $r->print(&Apache::lonhtmlcommon::breadcrumbs
1.90      www      2034:                   (undef,($title?$title:'Communication and Messages')));
1.88      www      2035: 
                   2036: }
                   2037: 
1.90      www      2038: # ---------------------------------------------------------------- Print header
                   2039: 
                   2040: sub printheader {
                   2041:     my ($r,$url,$desc,$title,$baseurl)=@_;
                   2042:     &Apache::lonhtmlcommon::add_breadcrumb
                   2043: 	({href=>$url,
                   2044: 	  text=>$desc});
                   2045:     &header($r,$title,$baseurl);
                   2046: }
                   2047: 
1.120     www      2048: # ------------------------------------------------------------ Store the comment
                   2049: 
                   2050: sub storecomment {
                   2051:     my ($r)=@_;
1.140     albertel 2052:     my $msgtxt=&Apache::lonfeedback::clear_out_html($env{'form.message'});
1.120     www      2053:     my $cleanmsgtxt='';
                   2054:     foreach (split(/[\n\r]/,$msgtxt)) {
                   2055: 	unless ($_=~/^\s*(\>|\&gt\;)/) {
                   2056: 	    $cleanmsgtxt.=$_."\n";
                   2057: 	}
                   2058:     }
1.140     albertel 2059:     my $key=&Apache::lonnet::escape($env{'form.baseurl'}).'___'.time;
1.120     www      2060:     &Apache::lonnet::put('nohist_stored_comments',{ $key => $cleanmsgtxt });
                   2061: }
                   2062: 
                   2063: sub storedcommentlisting {
                   2064:     my ($r)=@_;
                   2065:     my %msgs=&Apache::lonnet::dump('nohist_stored_comments',undef,undef,
1.140     albertel 2066:        '^'.&Apache::lonnet::escape(&Apache::lonnet::escape($env{'form.showcommentbaseurl'})));
1.137     albertel 2067:     $r->print(&Apache::lonxml::xmlbegin().'<head>'.
                   2068: 	      &Apache::lonxml::fontsettings().'</head><body>');
1.120     www      2069:     if ((keys %msgs)[0]=~/^error\:/) {
                   2070: 	$r->print(&mt('No stored comments yet.'));
                   2071:     } else {
                   2072: 	my $found=0;
                   2073: 	foreach (sort keys %msgs) {
                   2074: 	    $r->print("\n".$msgs{$_}."<hr />");
                   2075: 	    $found=1;
                   2076: 	}
                   2077: 	unless ($found) {
                   2078: 	    $r->print(&mt('No stored comments yet for this resource.'));
                   2079: 	}
                   2080:     }
                   2081: }
                   2082: 
1.115     www      2083: # ---------------------------------------------------------------- Send an email
                   2084: 
                   2085: sub sendoffmail {
1.120     www      2086:     my ($r,$folder)=@_;
                   2087:     my $suffix=&foldersuffix($folder);
1.115     www      2088:     my $sendstatus='';
1.159     raeburn  2089:     my %specialmsg_status;
                   2090:     my $numspecial = 0;
1.140     albertel 2091:     if ($env{'form.send'}) {
1.115     www      2092: 	&printheader($r,'','Messages being sent.');
                   2093: 	$r->rflush();
                   2094: 	my %content=();
                   2095: 	undef %content;
1.140     albertel 2096: 	if ($env{'form.forwid'}) {
                   2097: 	    my $msgid=$env{'form.forwid'};
1.120     www      2098: 	    my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
1.115     www      2099: 	    %content=&unpackagemsg($message{$msgid},1);
1.120     www      2100: 	    &statuschange($msgid,'forwarded',$folder);
1.140     albertel 2101: 	    $env{'form.message'}.="\n\n-- Forwarded message --\n\n".
1.115     www      2102: 		$content{'message'};
                   2103: 	}
1.140     albertel 2104: 	if ($env{'form.replyid'}) {
                   2105: 	    my $msgid=$env{'form.replyid'};
1.120     www      2106: 	    my %message=&Apache::lonnet::get('nohist_email'.$suffix,[$msgid]);
1.115     www      2107: 	    %content=&unpackagemsg($message{$msgid},1);
1.120     www      2108: 	    &statuschange($msgid,'replied',$folder);
1.115     www      2109: 	}
                   2110: 	my %toaddr=();
                   2111: 	undef %toaddr;
1.140     albertel 2112: 	if ($env{'form.sendmode'} eq 'group') {
                   2113: 	    foreach (keys %env) {
1.115     www      2114: 		if ($_=~/^form\.send\_to\_\&\&\&[^\&]*\&\&\&\_(.+)$/) {
                   2115: 		    $toaddr{$1}='';
                   2116: 		}
                   2117: 	    }
1.140     albertel 2118: 	} elsif ($env{'form.sendmode'} eq 'upload') {
                   2119: 	    foreach (split(/[\n\r\f]+/,$env{'form.upfile'})) {
1.115     www      2120: 		my ($rec,$txt)=split(/\s*\:\s*/,$_);
                   2121: 		if ($txt) {
                   2122: 		    $rec=~s/\@/\:/;
                   2123: 		    $toaddr{$rec}.=$txt."\n";
                   2124: 		}
                   2125: 	    }
                   2126: 	} else {
1.140     albertel 2127: 	    $toaddr{$env{'form.recuname'}.':'.$env{'form.recdomain'}}='';
1.115     www      2128: 	}
1.140     albertel 2129: 	if ($env{'form.additionalrec'}) {
                   2130: 	    foreach (split(/\,/,$env{'form.additionalrec'})) {
1.115     www      2131: 		my ($auname,$audom)=split(/\@/,$_);
                   2132: 		$toaddr{$auname.':'.$audom}='';
                   2133: 	    }
                   2134: 	}
1.156     raeburn  2135: 
1.159     raeburn  2136:         my $savemsg;
1.156     raeburn  2137:         my $msgtype;
1.159     raeburn  2138:         my %sentmessage;
1.156     raeburn  2139:         if ((($env{'form.critmsg'}) || ($env{'form.sendbck'})) &&
                   2140:             (&Apache::lonnet::allowed('srm',$env{'request.course.id'}))) {
1.159     raeburn  2141:             $savemsg=&Apache::lonfeedback::clear_out_html($env{'form.message'},1);
                   2142:             $msgtype = 'critical';
1.156     raeburn  2143:         } else {
1.159     raeburn  2144:             $savemsg=&Apache::lonfeedback::clear_out_html($env{'form.message'});
1.156     raeburn  2145:         }
1.115     www      2146: 	
                   2147: 	foreach (keys %toaddr) {
                   2148: 	    my ($recuname,$recdomain)=split(/\:/,$_);
1.159     raeburn  2149:             my $msgtxt = $savemsg;
1.115     www      2150: 	    if ($toaddr{$_}) { $msgtxt.='<hr />'.$toaddr{$_}; }
1.156     raeburn  2151: 	    my $thismsg;
1.140     albertel 2152: 	    if ((($env{'form.critmsg'}) || ($env{'form.sendbck'})) && 
                   2153: 		(&Apache::lonnet::allowed('srm',$env{'request.course.id'}))) {
1.115     www      2154: 		$r->print(&mt('Sending critical message').' '.$recuname.'@'.$recdomain.': ');
                   2155: 		$thismsg=&user_crit_msg($recuname,$recdomain,
1.140     albertel 2156: 					&Apache::lonfeedback::clear_out_html($env{'form.subject'}),
1.115     www      2157: 					$msgtxt,
1.159     raeburn  2158: 					$env{'form.sendbck'},$env{'form.permanent'},\$sentmessage{$_});
1.115     www      2159: 	    } else {
                   2160: 		$r->print(&mt('Sending').' '.$recuname.'@'.$recdomain.': ');
                   2161: 		$thismsg=&user_normal_msg($recuname,$recdomain,
1.140     albertel 2162: 					  &Apache::lonfeedback::clear_out_html($env{'form.subject'}),
1.115     www      2163: 					  $msgtxt,
1.159     raeburn  2164: 					  $content{'citation'},undef,undef,$env{'form.permanent'},\$sentmessage{$_});
1.156     raeburn  2165:             }
1.159     raeburn  2166: 	    if (($env{'request.course.id'}) && (($msgtype eq 'critical') || 
                   2167:                                          ($env{'form.sendmode'} eq 'group'))) {
                   2168: 	        $specialmsg_status{$recuname.':'.$recdomain}  = $thismsg;
1.156     raeburn  2169:                 if ($thismsg eq 'ok') {
1.159     raeburn  2170:                     $numspecial ++;
1.156     raeburn  2171:                 }
1.115     www      2172: 	    }
                   2173: 	    $r->print($thismsg.'<br />');
                   2174: 	    $sendstatus.=' '.$thismsg;
                   2175: 	}
1.159     raeburn  2176:         if (($env{'request.course.id'}) && (($env{'form.sendmode'} eq 'group')
                   2177:                                               || ($msgtype eq 'critical'))) {
1.156     raeburn  2178:             my $subj_prefix;
                   2179:             if ($msgtype eq 'critical') {
1.159     raeburn  2180:                 $subj_prefix = 'Critical.';
1.156     raeburn  2181:             } else {
1.159     raeburn  2182:                 $subj_prefix = 'Broadcast.';
1.156     raeburn  2183:             }
1.159     raeburn  2184:             my ($specialmsgid,$specialresult);
                   2185:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2186:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2187:             my $course_str = &Apache::lonnet::escape('['.$cnum.':'.$cdom.']');
                   2188: 
                   2189:             if ($numspecial) {
                   2190:                 $specialresult = &user_normal_msg_raw($cnum,$cdom,$subj_prefix.
                   2191:                     ' '.$course_str,$savemsg,undef,undef,undef,
                   2192:                     undef,undef,\$specialmsgid);
                   2193:                 $specialmsgid = &Apache::lonnet::unescape($specialmsgid);
1.156     raeburn  2194:             }
1.159     raeburn  2195:             if ($specialresult eq 'ok') {
1.156     raeburn  2196:                 my $record_sent;
                   2197:                 my @recusers = ();
                   2198:                 my @recudoms = ();
1.159     raeburn  2199:                 my ($stamp,$msgsubj,$msgname,$msgdom,$msgcount,$context,$pid) = 
                   2200:                             split(/\:/,&Apache::lonnet::unescape($specialmsgid));
1.156     raeburn  2201:                 foreach my $recipient (sort(keys(%toaddr))) {
1.159     raeburn  2202:                     if ($specialmsg_status{$recipient} eq 'ok') {
                   2203:                         my $usersubj = $subj_prefix.'['.$recipient.']';
                   2204:                         my $usermsgid = &buildmsgid($stamp,$usersubj,$msgname,
                   2205:                                               $msgdom,$msgcount,$context,$pid);
                   2206:                         &user_normal_msg_raw($cnum,$cdom,$subj_prefix.
                   2207:                         ' ['.$recipient.']',$sentmessage{$recipient},
                   2208:                         undef,undef,undef,undef,$usermsgid);
1.156     raeburn  2209:                         my ($uname,$udom) = split/:/,$recipient;
                   2210:                         push(@recusers,$uname);
                   2211:                         push(@recudoms,$udom);
                   2212:                     }
                   2213:                 }
                   2214:                 if (@recusers) {
1.159     raeburn  2215:                     my $specialmessage;
                   2216:                     my $sentsubj = $subj_prefix.' ('.$numspecial.' sent) '.
                   2217:                     &Apache::lonfeedback::clear_out_html($env{'form.subject'});
                   2218:                     $sentsubj = &HTML::Entities::encode($sentsubj,'<>&"');
                   2219:                     my $sentmsgid = &buildmsgid($stamp,$sentsubj,$msgname,
                   2220:                                               $msgdom,$msgcount,$context,$pid);
                   2221:                     ($specialmsgid,$specialmessage) =
                   2222:                          &packagemsg(&Apache::lonfeedback::clear_out_html(
                   2223:                              $env{'form.subject'}),$savemsg,undef,undef,undef,
                   2224:                                             \@recusers,\@recudoms,$sentmsgid);
                   2225:                     $record_sent = &store_sent_mail($specialmsgid,$specialmessage);
1.156     raeburn  2226:                 }
                   2227:             } else {
1.159     raeburn  2228:                 &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  2229:             }
                   2230:         }
1.115     www      2231:     } else {
                   2232: 	&printheader($r,'','No messages sent.'); 
                   2233:     }
                   2234:     if ($sendstatus=~/^(\s*(?:ok|con_delayed)\s*)*$/) {
                   2235: 	$r->print('<br /><font color="green">'.&mt('Completed.').'</font>');
1.140     albertel 2236: 	if ($env{'form.displayedcrit'}) {
1.115     www      2237: 	    &discrit($r);
                   2238: 	} else {
                   2239: 	    &Apache::loncommunicate::menu($r);
                   2240: 	}
                   2241:     } else {
                   2242: 	$r->print(
                   2243: 		  '<h2><font color="red">'.&mt('Could not deliver message').'</font></h2>'.
                   2244: 		  &mt('Please use the browser "Back" button and correct the recipient addresses')
                   2245: 		  );
                   2246:     }
                   2247: }
1.90      www      2248: 
1.13      www      2249: # ===================================================================== Handler
                   2250: 
1.5       www      2251: sub handler {
                   2252:     my $r=shift;
                   2253: 
                   2254: # ----------------------------------------------------------- Set document type
1.87      www      2255:     
                   2256:     &Apache::loncommon::content_type($r,'text/html');
                   2257:     $r->send_http_header;
                   2258:     
                   2259:     return OK if $r->header_only;
                   2260:     
1.6       www      2261: # --------------------------- Get query string for limited number of parameters
1.32      matthew  2262:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   2263:         ['display','replyto','forward','markread','markdel','markunread',
1.44      www      2264:          'sendreply','compose','sendmail','critical','recname','recdom',
1.120     www      2265:          'recordftf','sortedby','block','folder','startdis','interdis',
1.131     www      2266: 	 'showcommentbaseurl','dismode']);
1.140     albertel 2267:     $sqs='&sortedby='.$env{'form.sortedby'};
1.108     www      2268: 
1.40      www      2269: # ------------------------------------------------------ They checked for email
1.140     albertel 2270:     unless ($env{'form.block'}) {
1.101     raeburn  2271:         &Apache::lonnet::put('email_status',{'recnewemail'=>0});
                   2272:     }
1.88      www      2273: 
                   2274: # ----------------------------------------------------------------- Breadcrumbs
                   2275: 
                   2276:     &Apache::lonhtmlcommon::clear_breadcrumbs();
                   2277:     &Apache::lonhtmlcommon::add_breadcrumb
                   2278:         ({href=>"/adm/communicate",
                   2279:           text=>"Communication/Messages",
                   2280:           faq=>12,bug=>'Communication Tools',});
                   2281: 
1.106     www      2282: # ------------------------------------------------------------------ Get Folder
                   2283: 
1.140     albertel 2284:     my $folder=$env{'form.folder'};
1.106     www      2285:     unless ($folder) { 
                   2286: 	$folder=''; 
                   2287:     } else {
1.125     www      2288: 	$sqs.='&folder='.&Apache::lonnet::escape($folder);
1.106     www      2289:     }
1.142     www      2290: # ------------------------------------------------------------ Get Display Mode
                   2291: 
                   2292:     my $dismode=$env{'form.dismode'};
                   2293:     unless ($dismode) { 
                   2294: 	$dismode=''; 
                   2295:     } else {
                   2296: 	$sqs.='&dismode='.&Apache::lonnet::escape($dismode);
                   2297:     }
1.106     www      2298: 
1.108     www      2299: # --------------------------------------------------------------------- Display
                   2300: 
1.140     albertel 2301:     $startdis=$env{'form.startdis'};
1.118     www      2302:     $startdis--;
1.108     www      2303:     unless ($startdis) { $startdis=0; }
1.125     www      2304: 
1.140     albertel 2305:     $interdis=$env{'form.interdis'};
1.108     www      2306:     unless ($interdis) { $interdis=20; }
1.125     www      2307:     $sqs.='&interdis='.$interdis;
                   2308: 
1.140     albertel 2309:     if ($env{'form.firstview'}) {
1.117     www      2310: 	$startdis=0;
                   2311:     }
1.140     albertel 2312:     if ($env{'form.lastview'}) {
1.117     www      2313: 	$startdis=-1;
                   2314:     }
1.140     albertel 2315:     if ($env{'form.prevview'}) {
1.117     www      2316: 	$startdis--;
                   2317:     }
1.140     albertel 2318:     if ($env{'form.nextview'}) {
1.117     www      2319: 	$startdis++;
                   2320:     }
1.125     www      2321:     my $postedstartdis=$startdis+1;
                   2322:     $sqs.='&startdis='.$postedstartdis;
1.108     www      2323: 
1.5       www      2324: # --------------------------------------------------------------- Render Output
1.88      www      2325: 
1.140     albertel 2326:     if ($env{'form.display'}) {
                   2327: 	&displaymessage($r,$env{'form.display'},$folder);
                   2328:     } elsif ($env{'form.replyto'}) {
1.142     www      2329: 	&compout($r,'',$env{'form.replyto'},undef,undef,$folder,$dismode);
1.140     albertel 2330:     } elsif ($env{'form.confirm'}) {
1.92      www      2331: 	&printheader($r,'','Confirmed Receipt');
1.140     albertel 2332: 	foreach (keys %env) {
1.87      www      2333: 	    if ($_=~/^form\.rec\_(.*)$/) {
1.92      www      2334: 		$r->print('<b>'.&mt('Confirming Receipt').':</b> '.
1.87      www      2335: 			  &user_crit_received($1).'<br>');
                   2336: 	    }
                   2337: 	    if ($_=~/^form\.reprec\_(.*)$/) {
                   2338: 		my $msgid=$1;
1.92      www      2339: 		$r->print('<b>'.&mt('Confirming Receipt').':</b> '.
1.87      www      2340: 			  &user_crit_received($msgid).'<br>');
1.94      www      2341: 		&compout($r,'','','',$msgid);
1.87      www      2342: 	    }
                   2343: 	}
                   2344: 	&discrit($r);
1.140     albertel 2345:     } elsif ($env{'form.critical'}) {
1.92      www      2346: 	&printheader($r,'','Displaying Critical Messages');
1.87      www      2347: 	&discrit($r);
1.140     albertel 2348:     } elsif ($env{'form.forward'}) {
                   2349: 	&compout($r,$env{'form.forward'},undef,undef,undef,$folder);
                   2350:     } elsif ($env{'form.markdel'}) {
1.92      www      2351: 	&printheader($r,'','Deleted Message');
1.140     albertel 2352: 	&statuschange($env{'form.markdel'},'deleted',$folder);
1.120     www      2353: 	&Apache::loncommunicate::menu($r);
1.142     www      2354: 	&disall($r,($folder?$folder:$dismode));
1.140     albertel 2355:     } elsif ($env{'form.markedmove'}) {
1.106     www      2356: 	my $total=0;
1.140     albertel 2357: 	foreach (keys %env) {
1.106     www      2358: 	    if ($_=~/^form\.delmark_(.*)$/) {
                   2359: 		&movemsg(&Apache::lonnet::unescape($1),$folder,
1.140     albertel 2360: 			 $env{'form.movetofolder'});
1.106     www      2361: 		$total++;
                   2362: 	    }
                   2363: 	}
                   2364: 	&printheader($r,'','Moved Messages');
                   2365: 	$r->print('Moved '.$total.' message(s)<p>');
1.120     www      2366: 	&Apache::loncommunicate::menu($r);
1.142     www      2367: 	&disall($r,($folder?$folder:$dismode));
1.140     albertel 2368:     } elsif ($env{'form.markeddel'}) {
1.87      www      2369: 	my $total=0;
1.140     albertel 2370: 	foreach (keys %env) {
1.87      www      2371: 	    if ($_=~/^form\.delmark_(.*)$/) {
1.108     www      2372: 		&statuschange(&Apache::lonnet::unescape($1),'deleted',$folder);
1.87      www      2373: 		$total++;
                   2374: 	    }
                   2375: 	}
1.92      www      2376: 	&printheader($r,'','Deleted Messages');
1.87      www      2377: 	$r->print('Deleted '.$total.' message(s)<p>');
1.120     www      2378: 	&Apache::loncommunicate::menu($r);
1.142     www      2379: 	&disall($r,($folder?$folder:$dismode));
1.140     albertel 2380:     } elsif ($env{'form.markunread'}) {
1.92      www      2381: 	&printheader($r,'','Marked Message as Unread');
1.140     albertel 2382: 	&statuschange($env{'form.markunread'},'new');
1.120     www      2383: 	&Apache::loncommunicate::menu($r);
1.142     www      2384: 	&disall($r,($folder?$folder:$dismode));
1.140     albertel 2385:     } elsif ($env{'form.compose'}) {
                   2386: 	&compout($r,'','',$env{'form.compose'});
                   2387:     } elsif ($env{'form.recordftf'}) {
                   2388: 	&facetoface($r,$env{'form.recordftf'});
                   2389:     } elsif ($env{'form.block'}) {
                   2390:         &examblock($r,$env{'form.block'});
                   2391:     } elsif ($env{'form.sendmail'}) {
1.120     www      2392: 	&sendoffmail($r,$folder);
1.140     albertel 2393: 	if ($env{'form.storebasecomment'}) {
1.120     www      2394: 	    &storecomment($r);
                   2395: 	}
1.154     www      2396: 	if (($env{'form.rsspost'}) && ($env{'request.course.id'})) {
                   2397: 	    &Apache::lonrss::addentry($env{'course.'.$env{'request.course.id'}.'.num'},
                   2398: 				      $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2399: 				      'Course_Announcements',
                   2400: 				      $env{'form.subject'},
                   2401: 				      $env{'form.message'},'/adm/communicate','public');
                   2402: 	}
1.142     www      2403: 	&disall($r,($folder?$folder:$dismode));
1.140     albertel 2404:     } elsif ($env{'form.newfolder'}) {
1.106     www      2405: 	&printheader($r,'','New Folder');
1.140     albertel 2406: 	&makefolder($env{'form.newfolder'});
1.120     www      2407: 	&Apache::loncommunicate::menu($r);
1.140     albertel 2408: 	&disall($r,$env{'form.newfolder'});
                   2409:     } elsif ($env{'form.showcommentbaseurl'}) {
1.120     www      2410: 	&storedcommentlisting($r);
1.87      www      2411:     } else {
1.92      www      2412: 	&printheader($r,'','Display All Messages');
1.142     www      2413: 	&Apache::loncommunicate::menu($r); 
                   2414: 	&disall($r,($folder?$folder:$dismode));
1.87      www      2415:     }
1.139     albertel 2416:     $r->print(&Apache::loncommon::endbodytag().'</html>');
1.87      www      2417:     return OK;
1.5       www      2418: }
1.2       www      2419: # ================================================= Main program, reset counter
                   2420: 
1.27      www      2421: BEGIN {
1.2       www      2422:     $msgcount=0;
1.1       www      2423: }
1.58      bowersj2 2424: 
                   2425: =pod
                   2426: 
                   2427: =back
                   2428: 
1.59      bowersj2 2429: =cut
                   2430: 
                   2431: 1; 
1.1       www      2432: 
                   2433: __END__
                   2434: 
                   2435: 
                   2436: 
                   2437: 
                   2438: 
                   2439: 
                   2440: 

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