File:  [LON-CAPA] / loncom / interface / lonmsgdisplay.pm
Revision 1.35.2.4: download - view: text, annotated - select for diffs
Wed Jul 19 16:01:45 2006 UTC (17 years, 9 months ago) by albertel
Branches: version_2_2_X
CVS tags: version_2_2_0, version_2_1_99_3, version_2_1_99_2, version_2_1_99_1
- backport 1.39

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

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