File:  [LON-CAPA] / loncom / interface / lonmsgdisplay.pm
Revision 1.35.2.3: download - view: text, annotated - select for diffs
Wed Jul 19 10:20:11 2006 UTC (17 years, 9 months ago) by albertel
Branches: version_2_2_X
- backport 1.37 1.38

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

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