File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.156: download - view: text, annotated - select for diffs
Wed Nov 23 22:32:11 2005 UTC (18 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Bug 3946.  Only a single copy of a broadcast message is stored in the "Sent" Folder.  To: line now continues list of (multiple) recipients.

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

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