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

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

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