Annotation of loncom/interface/lonmsgdisplay.pm, revision 1.14

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

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