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

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

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