File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.200: download - view: text, annotated - select for diffs
Sun Apr 22 13:41:22 2007 UTC (17 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 4551.  Users with dff privilege in a course can add a copy of a message to a User's Record (category Archive).
- Wording change for forwarding screen

    1: # The LearningOnline Network with CAPA
    2: # Routines for messaging
    3: #
    4: # $Id: lonmsg.pm,v 1.200 2007/04/22 13:41:22 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: package Apache::lonmsg;
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: Apache::lonmsg: supports internal messaging
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: lonmsg provides routines for sending messages.
   40: 
   41: Right now, this document will cover just how to send a message, since
   42: it is likely you will not need to programmatically read messages,
   43: since lonmsg already implements that functionality.
   44: 
   45: The routines used to package messages and unpackage messages are not
   46: only used by lonmsg when creating/extracting messages for LON-CAPA's
   47: internal messaging system, but also by lonnotify.pm which is available
   48: for use by Domain Coordinators to broadcast standard e-mail to specified
   49: users in their domain.  The XML packaging used in the two cases is very
   50: similar.  The differences are the use of <recuser>$uname</recuser> and
   51: <recdomain>$udom</recdomain> in stored internal messages, compared
   52: with <recipient username="$uname:$udom">$email</recipient> in stored
   53: Domain Coordinator e-mail for the storage of information about
   54: recipients of the message/e-mail.
   55: 
   56: =head1 FUNCTIONS
   57: 
   58: =over 4
   59: 
   60: =cut
   61: 
   62: use strict;
   63: use Apache::lonnet;
   64: use HTML::TokeParser();
   65: use Apache::lonlocal;
   66: use Mail::Send;
   67: use LONCAPA qw(:DEFAULT :match);
   68: 
   69: {
   70:     my $uniq;
   71:     sub get_uniq {
   72: 	$uniq++;
   73: 	return $uniq;
   74:     }
   75: }
   76: 
   77: # ===================================================================== Package
   78: 
   79: sub packagemsg {
   80:     my ($subject,$message,$citation,$baseurl,$attachmenturl,
   81: 	$recuser,$recdomain,$msgid,$type,$crsmsgid,$symb,$error)=@_;
   82:     $message =&HTML::Entities::encode($message,'<>&"');
   83:     $citation=&HTML::Entities::encode($citation,'<>&"');
   84:     $subject =&HTML::Entities::encode($subject,'<>&"');
   85:     #remove machine specification
   86:     $baseurl =~ s|^http://[^/]+/|/|;
   87:     $baseurl =&HTML::Entities::encode($baseurl,'<>&"');
   88:     #remove machine specification
   89:     $attachmenturl =~ s|^http://[^/]+/|/|;
   90:     $attachmenturl =&HTML::Entities::encode($attachmenturl,'<>&"');
   91:     my $course_context;
   92:     if (defined($env{'form.replyid'})) {
   93:         my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$origcid)=
   94:                    split(/\:/,&unescape($env{'form.replyid'}));
   95:         $course_context = $origcid;
   96:     }
   97:     foreach my $key (keys(%env)) {
   98:         if ($key=~/^form\.(rep)?rec\_(.*)$/) {
   99:             my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$origcid) =
  100:                                     split(/\:/,&unescape($2));
  101:             $course_context = $origcid;
  102:             last;
  103:         }
  104:     }
  105:     unless(defined($course_context)) {
  106:         $course_context = $env{'request.course.id'};
  107:     }
  108:     my $now=time;
  109:     my $msgcount = &get_uniq();
  110:     unless(defined($msgid)) {
  111:         $msgid = &buildmsgid($now,$subject,$env{'user.name'},$env{'user.domain'},
  112:                            $msgcount,$course_context,$symb,$error,$$);
  113:     }
  114:     my $result = '<sendername>'.$env{'user.name'}.'</sendername>'.
  115:            '<senderdomain>'.$env{'user.domain'}.'</senderdomain>'.
  116:            '<subject>'.$subject.'</subject>'.
  117:            '<time>'.&Apache::lonlocal::locallocaltime($now).'</time>';
  118:     if (defined($crsmsgid)) {
  119:         $result.= '<courseid>'.$course_context.'</courseid>'.
  120:                   '<coursesec>'.$env{'request.course.sec'}.'</coursesec>'.
  121:                   '<msgid>'.$msgid.'</msgid>'.
  122:                   '<coursemsgid>'.$crsmsgid.'</coursemsgid>'.
  123:                   '<message>'.$message.'</message>';
  124:         return ($msgid,$result);
  125:     }
  126:     $result .= '<servername>'.$ENV{'SERVER_NAME'}.'</servername>'.
  127:            '<host>'.$ENV{'HTTP_HOST'}.'</host>'.
  128: 	   '<client>'.$ENV{'REMOTE_ADDR'}.'</client>'.
  129: 	   '<browsertype>'.$env{'browser.type'}.'</browsertype>'.
  130: 	   '<browseros>'.$env{'browser.os'}.'</browseros>'.
  131: 	   '<browserversion>'.$env{'browser.version'}.'</browserversion>'.
  132:            '<browsermathml>'.$env{'browser.mathml'}.'</browsermathml>'.
  133: 	   '<browserraw>'.$ENV{'HTTP_USER_AGENT'}.'</browserraw>'.
  134: 	   '<courseid>'.$course_context.'</courseid>'.
  135: 	   '<coursesec>'.$env{'request.course.sec'}.'</coursesec>'.
  136: 	   '<role>'.$env{'request.role'}.'</role>'.
  137: 	   '<resource>'.$env{'request.filename'}.'</resource>'.
  138:            '<msgid>'.$msgid.'</msgid>';
  139:     if (ref($recuser) eq 'ARRAY') {
  140:         for (my $i=0; $i<@{$recuser}; $i++) {
  141:             if ($type eq 'dcmail') {
  142:                 my ($username,$email) = split(/:/,$$recuser[$i]);
  143:                 $username = &unescape($username);
  144:                 $email = &unescape($email);
  145:                 $username = &HTML::Entities::encode($username,'<>&"');
  146:                 $email = &HTML::Entities::encode($email,'<>&"');
  147:                 $result .= '<recipient username="'.$username.'">'.
  148:                                             $email.'</recipient>';
  149:             } else {
  150:                 $result .= '<recuser>'.$$recuser[$i].'</recuser>'.
  151:                            '<recdomain>'.$$recdomain[$i].'</recdomain>';
  152:             }
  153:         }
  154:     } else {
  155:         $result .= '<recuser>'.$recuser.'</recuser>'.
  156:                    '<recdomain>'.$recdomain.'</recdomain>';
  157:     }
  158:     $result .= '<message>'.$message.'</message>';
  159:     if (defined($citation)) {
  160: 	$result.='<citation>'.$citation.'</citation>';
  161:     }
  162:     if (defined($baseurl)) {
  163: 	$result.= '<baseurl>'.$baseurl.'</baseurl>';
  164:     }
  165:     if (defined($attachmenturl)) {
  166: 	$result.= '<attachmenturl>'.$attachmenturl.'</attachmenturl>';
  167:     }
  168:     if (defined($symb)) {
  169:         $result.= '<symb>'.$symb.'</symb>';
  170:         if (defined($course_context)) {
  171:             if ($course_context eq $env{'request.course.id'}) {
  172:                 my $resource_title = &Apache::lonnet::gettitle($symb);
  173:                 if (defined($resource_title)) {
  174:                     $result .= '<resource_title>'.$resource_title.'</resource_title>';
  175:                 }
  176:             }
  177:         }
  178:     }
  179:     return ($msgid,$result);
  180: }
  181: 
  182: # ================================================== Unpack message into a hash
  183: 
  184: sub unpackagemsg {
  185:     my ($message,$notoken)=@_;
  186:     my %content=();
  187:     my $parser=HTML::TokeParser->new(\$message);
  188:     my $token;
  189:     while ($token=$parser->get_token) {
  190:        if ($token->[0] eq 'S') {
  191: 	   my $entry=$token->[1];
  192:            my $value=$parser->get_text('/'.$entry);
  193:            if (($entry eq 'recuser') || ($entry eq 'recdomain')) {
  194:                push(@{$content{$entry}},$value);
  195:            } elsif ($entry eq 'recipient') {
  196:                my $username = $token->[2]{'username'};
  197:                $username = &HTML::Entities::decode($username,'<>&"');
  198:                $content{$entry}{$username} = $value;
  199:            } else {
  200:                $content{$entry}=$value;
  201:            }
  202:        }
  203:     }
  204:     if (!exists($content{'recuser'})) { $content{'recuser'} = []; }
  205:     if ($content{'attachmenturl'}) {
  206:        my ($fname)=($content{'attachmenturl'}=~m|/([^/]+)$|);
  207:        if ($notoken) {
  208: 	   $content{'message'}.='<p>'.&mt('Attachment').': <tt>'.$fname.'</tt>';
  209:        } else {
  210: 	   &Apache::lonnet::allowuploaded('/adm/msg',
  211: 					  $content{'attachmenturl'});
  212: 	   $content{'message'}.='<p>'.&mt('Attachment').
  213: 	       ': <a href="'.$content{'attachmenturl'}.'"><tt>'.
  214: 	       $fname.'</tt></a>';
  215:        }
  216:     }
  217:     return %content;
  218: }
  219: 
  220: # ======================================================= Get info out of msgid
  221: 
  222: sub buildmsgid {
  223:     my ($now,$subject,$uname,$udom,$msgcount,$course_context,$symb,$error,$pid) = @_;
  224:     $subject=&escape($subject);
  225:     $symb = &escape($symb);
  226:     return(&escape($now.':'.$subject.':'.$uname.':'.
  227:            $udom.':'.$msgcount.':'.$course_context.':'.$pid.':'.$symb.':'.$error));
  228: }
  229: 
  230: sub unpackmsgid {
  231:     my ($msgid,$folder,$skipstatus,$status_cache)=@_;
  232:     $msgid=&unescape($msgid);
  233:     my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$fromcid,
  234:         $processid,$symb,$error) = split(/\:/,&unescape($msgid));
  235:     $shortsubj = &unescape($shortsubj);
  236:     $shortsubj = &HTML::Entities::decode($shortsubj);
  237:     $symb = &unescape($symb);
  238:     if (!defined($processid)) { $fromcid = ''; }
  239:     my %status=();
  240:     unless ($skipstatus) {
  241: 	if (ref($status_cache)) {
  242: 	    $status{$msgid} = $status_cache->{$msgid};
  243: 	} else {
  244: 	    my $suffix=&foldersuffix($folder);
  245: 	    %status=&Apache::lonnet::get('email_status'.$suffix,[$msgid]);
  246: 	}
  247: 	if ($status{$msgid}=~/^error\:/) { $status{$msgid}=''; }
  248:         unless ($status{$msgid}) { $status{$msgid}='new'; }
  249:     }
  250:     return ($sendtime,$shortsubj,$fromname,$fromdomain,$status{$msgid},$fromcid,$symb,$error);
  251: }
  252: 
  253: 
  254: sub sendemail {
  255:     my ($to,$subject,$body)=@_;
  256:     my %senderemails=&Apache::loncommon::getemails();
  257:     my $senderaddress='';
  258:     foreach my $type ('notification','permanentemail','critnotification') {
  259: 	if ($senderemails{$type}) {
  260: 	    $senderaddress=$senderemails{$type};
  261: 	}
  262:     }
  263:     $body=
  264:     "*** ".&mt('This is an automatic message generated by the LON-CAPA system.')."\n".
  265:     "*** ".($senderaddress?&mt('You can reply to this message'):&mt('Please do not reply to this address.')."\n*** ".
  266: 	    &mt('A reply will not be received by the recipient!'))."\n\n".$body;
  267:     my $msg = new Mail::Send;
  268:     $msg->to($to);
  269:     $msg->subject('[LON-CAPA] '.$subject);
  270:     if ($senderaddress) { $msg->add('Reply-to',$senderaddress); $msg->add('From',$senderaddress); }
  271:     if (my $fh = $msg->open()) {
  272: 	print $fh $body;
  273: 	$fh->close;
  274:     }
  275: }
  276: 
  277: # ==================================================== Send notification emails
  278: 
  279: sub sendnotification {
  280:     my ($to,$touname,$toudom,$subj,$crit,$text,$msgid)=@_;
  281:     my $sender=$env{'environment.firstname'}.' '.$env{'environment.lastname'};
  282:     unless ($sender=~/\w/) { 
  283: 	$sender=$env{'user.name'}.'@'.$env{'user.domain'};
  284:     }
  285:     my $critical=($crit?' critical':'');
  286:     $text=~s/\&lt\;/\</gs;
  287:     $text=~s/\&gt\;/\>/gs;
  288:     $text=~s/\<\/*[^\>]+\>//gs;
  289:     my $url='http://'.
  290: 	&Apache::lonnet::hostname(&Apache::lonnet::homeserver($touname,$toudom)).
  291:       '/adm/email?username='.$touname.'&domain='.$toudom;
  292:     my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$fromcid,
  293:         $symb,$error) = &Apache::lonmsg::unpackmsgid($msgid);
  294:     my $coursetext;
  295:     if ($fromcid ne '') {
  296:         $coursetext = "\n".&mt('Course').': ';
  297:         if ($env{'course.'.$fromcid.'.description'} ne '') {
  298:             $coursetext .= $env{'course.'.$fromcid.'.description'};
  299:         } else {
  300:             my %coursehash = &Apache::lonnet::coursedescription($fromcid,);
  301:             if ($coursehash{'description'} ne '') {
  302:                 $coursetext .= $coursehash{'description'};
  303:             }
  304:         }
  305:         $coursetext .= "\n\n";
  306:     }
  307:     my $body = $coursetext. 
  308:                &mt('You received a'.$critical.' message from [_1] in LON-CAPA.',$sender).' '.&mt('The subject is 
  309: 
  310:  [_1]
  311: 
  312: ',$subj)."\n".
  313: '=== '.&mt('Excerpt')." ============================================================
  314: $text
  315: ========================================================================
  316: 
  317: ".&mt('Use 
  318: 
  319:  [_1]
  320: 
  321: to access the full message.',$url);
  322:     &sendemail($to,'New'.$critical.' message from '.$sender,$body);
  323: }
  324: # ============================================================= Check for email
  325: 
  326: sub newmail {
  327:     if ((time-$env{'user.mailcheck.time'})>300) {
  328:         my %what=&Apache::lonnet::get('email_status',['recnewemail']);
  329:         &Apache::lonnet::appenv('user.mailcheck.time'=>time);
  330:         if ($what{'recnewemail'}>0) { return 1; }
  331:     }
  332:     return 0;
  333: }
  334: 
  335: # =============================== Automated message to the author of a resource
  336: 
  337: =pod
  338: 
  339: =item * B<author_res_msg($filename, $message)>: Sends message $message to the owner
  340:     of the resource with the URI $filename.
  341: 
  342: =cut
  343: 
  344: sub author_res_msg {
  345:     my ($filename,$message)=@_;
  346:     unless ($message) { return 'empty'; }
  347:     $filename=&Apache::lonnet::declutter($filename);
  348:     my ($domain,$author,@dummy)=split(/\//,$filename);
  349:     my $homeserver=&Apache::lonnet::homeserver($author,$domain);
  350:     if ($homeserver ne 'no_host') {
  351:        my $id=unpack("%32C*",$message);
  352:        $message .= " <p>This error occurred on machine ".
  353: 	   $Apache::lonnet::perlvar{'lonHostID'}."</p>";
  354:        my $msgid;
  355:        ($msgid,$message)=&packagemsg($filename,$message);
  356:        return &Apache::lonnet::reply('put:'.$domain.':'.$author.
  357:          ':nohist_res_msgs:'.
  358:           &escape($filename.'_'.$id).'='.
  359:           &escape($message),$homeserver);
  360:     }
  361:     return 'no_host';
  362: }
  363: 
  364: # =========================================== Retrieve author resource messages
  365: 
  366: sub retrieve_author_res_msg {
  367:     my $url=shift;
  368:     $url=&Apache::lonnet::declutter($url);
  369:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
  370:     my %errormsgs=&Apache::lonnet::dump('nohist_res_msgs',$domain,$author);
  371:     my $msgs='';
  372:     foreach (keys %errormsgs) {
  373: 	if ($_=~/^\Q$url\E\_\d+$/) {
  374: 	    my %content=&unpackagemsg($errormsgs{$_});
  375: 	    $msgs.='<p><img src="/adm/lonMisc/bomb.gif" /><b>'.
  376: 		$content{'time'}.'</b>: '.$content{'message'}.
  377: 		'<br /></p>';
  378: 	}
  379:     } 
  380:     return $msgs;     
  381: }
  382: 
  383: 
  384: # =============================== Delete all author messages related to one URL
  385: 
  386: sub del_url_author_res_msg {
  387:     my $url=shift;
  388:     $url=&Apache::lonnet::declutter($url);
  389:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
  390:     my @delmsgs=();
  391:     foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
  392: 	if ($_=~/^\Q$url\E\_\d+$/) {
  393: 	    push (@delmsgs,$_);
  394: 	}
  395:     }
  396:     return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
  397: }
  398: # =================================== Clear out all author messages in URL path
  399: 
  400: sub clear_author_res_msg {
  401:     my $url=shift;
  402:     $url=&Apache::lonnet::declutter($url);
  403:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
  404:     my @delmsgs=();
  405:     foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
  406: 	if ($_=~/^\Q$url\E/) {
  407: 	    push (@delmsgs,$_);
  408: 	}
  409:     }
  410:     return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
  411: }
  412: # ================= Return hash with URLs for which there is a resource message
  413: 
  414: sub all_url_author_res_msg {
  415:     my ($author,$domain)=@_;
  416:     my %returnhash=();
  417:     foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
  418: 	$_=~/^(.+)\_\d+/;
  419: 	$returnhash{$1}=1;
  420:     }
  421:     return %returnhash;
  422: }
  423: 
  424: # ====================================== Add a comment to the User Notes screen
  425: 
  426: sub store_instructor_comment {
  427:     my ($msg,$uname,$udom) = @_;
  428:     my $cid  = $env{'request.course.id'};
  429:     my $cnum = $env{'course.'.$cid.'.num'};
  430:     my $cdom = $env{'course.'.$cid.'.domain'};
  431:     my $subject= &mt('Record').' ['.$uname.':'.$udom.']';
  432:     my $result = &user_normal_msg_raw($cnum,$cdom,$subject,$msg);
  433:     return $result;
  434: }
  435: 
  436: # ================================================== Critical message to a user
  437: 
  438: sub user_crit_msg_raw {
  439:     my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage)=@_;
  440: # Check if allowed missing
  441:     my ($status,$packed_message);
  442:     my $msgid='undefined';
  443:     unless (($message)&&($user)&&($domain)) { $status='empty'; };
  444:     my $text=$message;
  445:     my $homeserver=&Apache::lonnet::homeserver($user,$domain);
  446:     if ($homeserver ne 'no_host') {
  447:        ($msgid,$packed_message)=&packagemsg($subject,$message);
  448:        if ($sendback) { $packed_message.='<sendback>true</sendback>'; }
  449:        $status=&Apache::lonnet::critical(
  450:            'put:'.$domain.':'.$user.':critical:'.
  451:            &escape($msgid).'='.
  452:            &escape($packed_message),$homeserver);
  453:         if (defined($sentmessage)) {
  454:             $$sentmessage = $packed_message;
  455:         }
  456:         if ($env{'request.course.id'} eq '') {
  457:             (undef,my $packed_message_no_citation) =
  458:             &packagemsg($subject,$message,undef,undef,undef,$user,$domain,
  459:                         $msgid);
  460:             if ($status eq 'ok' || $status eq 'con_delayed') {
  461:                 &store_sent_mail($msgid,$packed_message_no_citation);
  462:             }
  463:         }
  464:     } else {
  465:        $status='no_host';
  466:     }
  467: 
  468: # Notifications
  469:     my %userenv = &Apache::loncommon::getemails($user,$domain);
  470:     if ($userenv{'critnotification'}) {
  471:       &sendnotification($userenv{'critnotification'},$user,$domain,$subject,1,
  472: 			$text,$msgid);
  473:     }
  474:     if ($toperm && $userenv{'permanentemail'}) {
  475:       &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,1,
  476: 			$text,$msgid);
  477:     }
  478: # Log this
  479:     &Apache::lonnet::logthis(
  480:       'Sending critical email '.$msgid.
  481:       ', log status: '.
  482:       &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  483:                          $env{'user.home'},
  484:       'Sending critical '.$msgid.' to '.$user.' at '.$domain.' with status: '
  485:       .$status));
  486:     return $status;
  487: }
  488: 
  489: # New routine that respects "forward" and calls old routine
  490: 
  491: =pod
  492: 
  493: =item * B<user_crit_msg($user, $domain, $subject, $message, $sendback)>: Sends
  494:     a critical message $message to the $user at $domain. If $sendback is true,
  495:     a reciept will be sent to the current user when $user recieves the message.
  496: 
  497:     Additionally it will check if the user has a Forwarding address
  498:     set, and send the message to that address instead
  499: 
  500:     returns 
  501:       - in array context a list of results for each message that was sent
  502:       - in scalar context a space seperated list of results for each 
  503:            message sent
  504: 
  505: =cut
  506: 
  507: sub user_crit_msg {
  508:     my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage)=@_;
  509:     my @status;
  510:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
  511:                                        $domain,$user);
  512:     my $msgforward=$userenv{'msgforward'};
  513:     if ($msgforward) {
  514:        foreach my $addr (split(/\,/,$msgforward)) {
  515: 	 my ($forwuser,$forwdomain)=split(/\:/,$addr);
  516:          push(@status,
  517: 	      &user_crit_msg_raw($forwuser,$forwdomain,$subject,$message,
  518: 				 $sendback,$toperm,$sentmessage));
  519:        }
  520:     } else { 
  521: 	push(@status,
  522: 	     &user_crit_msg_raw($user,$domain,$subject,$message,$sendback,
  523: 				$toperm,$sentmessage));
  524:     }
  525:     if (wantarray) {
  526: 	return @status;
  527:     }
  528:     return join(' ',@status);
  529: }
  530: 
  531: # =================================================== Critical message received
  532: 
  533: sub user_crit_received {
  534:     my $msgid=shift;
  535:     my %message=&Apache::lonnet::get('critical',[$msgid]);
  536:     my %contents=&unpackagemsg($message{$msgid},1);
  537:     my $status='rec: '.($contents{'sendback'}?
  538:      &user_normal_msg($contents{'sendername'},$contents{'senderdomain'},
  539:                      &mt('Receipt').': '.$env{'user.name'}.' '.&mt('at').' '.$env{'user.domain'}.', '.$contents{'subject'},
  540:                      &mt('User').' '.$env{'user.name'}.' '.&mt('at').' '.$env{'user.domain'}.
  541:                      ' acknowledged receipt of message'."\n".'   "'.
  542:                      $contents{'subject'}.'"'."\n".&mt('dated').' '.
  543:                      $contents{'time'}.".\n"
  544:                      ):'no msg req');
  545:     $status.=' trans: '.
  546:      &Apache::lonnet::put(
  547:      'nohist_email',{$contents{'msgid'} => $message{$msgid}});
  548:     $status.=' del: '.
  549:      &Apache::lonnet::del('critical',[$contents{'msgid'}]);
  550:     &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  551:                          $env{'user.home'},'Received critical message '.
  552:                          $contents{'msgid'}.
  553:                          ', '.$status);
  554:     return $status;
  555: }
  556: 
  557: # ======================================================== Normal communication
  558: 
  559: sub user_normal_msg_raw {
  560:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
  561:         $toperm,$currid,$newid,$sentmessage,$crsmsgid,$symb,$restitle,
  562:         $error)=@_;
  563: # Check if allowed missing
  564:     my ($status,$packed_message);
  565:     my $msgid='undefined';
  566:     my $text=$message;
  567:     unless (($message)&&($user)&&($domain)) { $status='empty'; };
  568:     my $homeserver=&Apache::lonnet::homeserver($user,$domain);
  569:     if ($homeserver ne 'no_host') {
  570:        ($msgid,$packed_message)=
  571: 	                 &packagemsg($subject,$message,$citation,$baseurl,
  572:                                      $attachmenturl,$user,$domain,$currid,
  573:                                      undef,$crsmsgid,$symb,$error);
  574: 
  575: # Store in user folder
  576:        $status=&Apache::lonnet::critical(
  577:            'put:'.$domain.':'.$user.':nohist_email:'.
  578:            &escape($msgid).'='.
  579:            &escape($packed_message),$homeserver);
  580: # Save new message received time
  581:        &Apache::lonnet::put
  582:                          ('email_status',{'recnewemail'=>time},$domain,$user);
  583: # Into sent-mail folder unless a broadcast message or critical message
  584:        unless (($env{'request.course.id'}) &&
  585:                (($env{'form.courserecord'}) &&
  586:                 (&Apache::lonnet::allowed('dff',$env{'request.course.id'})
  587:                  || &Apache::lonnet::allowed('dff',$env{'request.course.id'}.
  588:                   '/'.$env{'request.course.sec'}))) ||
  589:                 (($env{'form.sendmode'} eq 'group')  ||
  590:                 (($env{'form.critmsg'}) || ($env{'form.sendbck'})) &&
  591:                  (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  592:                  || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  593:                                              '/'.$env{'request.course.sec'})))) {
  594:            (undef,my $packed_message_no_citation) =
  595:                &packagemsg($subject,$message,undef,$baseurl,$attachmenturl,
  596:                            $user,$domain,$currid,undef,$crsmsgid,$symb,$error);
  597:            if ($status eq 'ok' || $status eq 'con_delayed') {
  598:                &store_sent_mail($msgid,$packed_message_no_citation);
  599:            }
  600:        }
  601:        if (defined($newid)) {
  602: 	   $$newid = $msgid;
  603:        }
  604:        if (defined($sentmessage)) {
  605: 	   $$sentmessage = $packed_message;
  606:        }
  607: # Notifications
  608:        my %userenv = &Apache::lonnet::get('environment',['notification',
  609: 							 'permanentemail'],
  610: 					  $domain,$user);
  611:        if ($userenv{'notification'}) {
  612: 	   &sendnotification($userenv{'notification'},$user,$domain,$subject,0,
  613: 			     $text,$msgid);
  614:        }
  615:        if ($toperm && $userenv{'permanentemail'}) {
  616: 	   &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,0,
  617: 			     $text,$msgid);
  618:        }
  619:        &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  620: 			    $env{'user.home'},
  621: 			    'Sending '.$msgid.' to '.$user.' at '.$domain.' with status: '.$status);
  622:    } else {
  623:        $status='no_host';
  624:    }
  625:     return $status;
  626: }
  627: 
  628: # New routine that respects "forward" and calls old routine
  629: 
  630: =pod
  631: 
  632: =item * B<user_normal_msg($user, $domain, $subject, $message, $citation,
  633:        $baseurl, $attachmenturl, $toperm, $sentmessage, $symb, $restitle, $error)>:
  634:  Sends a message to the  $user at $domain, with subject $subject and message $message.
  635: 
  636:     Additionally it will check if the user has a Forwarding address
  637:     set, and send the message to that address instead
  638: 
  639:     returns
  640:       - in array context a list of results for each message that was sent
  641:       - in scalar context a space seperated list of results for each
  642:            message sent
  643: 
  644: =cut
  645: 
  646: sub user_normal_msg {
  647:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
  648: 	$toperm,$sentmessage,$symb,$restitle,$error)=@_;
  649:     my @status;
  650:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
  651:                                        $domain,$user);
  652:     my $msgforward=$userenv{'msgforward'};
  653:     if ($msgforward) {
  654:         foreach (split(/\,/,$msgforward)) {
  655: 	    my ($forwuser,$forwdomain)=split(/\:/,$_);
  656: 	    push(@status,
  657: 	        &user_normal_msg_raw($forwuser,$forwdomain,$subject,$message,
  658: 				     $citation,$baseurl,$attachmenturl,$toperm,
  659: 				     undef,undef,$sentmessage,undef,$symb,$restitle,$error));
  660:         }
  661:     } else {
  662: 	push(@status,&user_normal_msg_raw($user,$domain,$subject,$message,
  663: 				     $citation,$baseurl,$attachmenturl,$toperm,
  664: 				     undef,undef,$sentmessage,undef,$symb,$restitle,$error));
  665:     }
  666:     if (wantarray) {
  667:         return @status;
  668:     }
  669:     return join(' ',@status);
  670: }
  671: 
  672: sub store_sent_mail {
  673:     my ($msgid,$message) = @_;
  674:     my $status =' '.&Apache::lonnet::critical(
  675:                'put:'.$env{'user.domain'}.':'.$env{'user.name'}.
  676:                                           ':nohist_email_sent:'.
  677:                &escape($msgid).'='.
  678:                &escape($message),$env{'user.home'});
  679:     return $status;
  680: }
  681: 
  682: # =============================================================== Folder suffix
  683: 
  684: sub foldersuffix {
  685:     my $folder=shift;
  686:     unless ($folder) { return ''; }
  687:     my $suffix;
  688:     my %folderhash = &get_user_folders($folder);
  689:     if (ref($folderhash{$folder}) eq 'HASH') {
  690:         $suffix = '_'.&escape($folderhash{$folder}{'id'});
  691:     } else {
  692:         $suffix = '_'.&escape($folder);
  693:     }
  694:     return $suffix;
  695: }
  696: 
  697: # ========================================================= User-defined folders 
  698: 
  699: sub get_user_folders {
  700:     my ($folder) = @_;
  701:     my %userfolders = 
  702:           &Apache::lonnet::dump('email_folders',undef,undef,$folder);
  703:     my $lock = "\0".'lock_counter'; # locks db while counter incremented
  704:     my $counter = "\0".'idcount';   # used in suffix for email db files
  705:     if (defined($userfolders{$lock})) {
  706:         delete($userfolders{$lock});
  707:     }
  708:     if (defined($userfolders{$counter})) {
  709:         delete($userfolders{$counter});
  710:     }
  711:     return %userfolders;
  712: }
  713: 
  714: sub secapply {
  715:     my $rec=shift;
  716:     my $defaultflag=shift;
  717:     $rec=~s/\s+//g;
  718:     $rec=~s/\@/\:/g;
  719:     my ($adr,$sections_or_groups)=($rec=~/^([^\(]+)\(([^\)]+)\)/);
  720:     if ($sections_or_groups) {
  721: 	foreach my $item (split(/\;/,$sections_or_groups)) {
  722:             if (($item eq $env{'request.course.sec'}) ||
  723:                 ($defaultflag && ($item eq '*'))) {
  724:                 return $adr; 
  725:             } elsif ($env{'request.course.groups'}) {
  726:                 my @usersgroups = split(/:/,$env{'request.course.groups'});
  727:                 if (grep(/^\Q$item\E$/,@usersgroups)) {
  728:                     return $adr;
  729:                 }
  730:             } 
  731:         }
  732:     } else {
  733:        return $rec;
  734:     }
  735:     return '';
  736: }
  737: 
  738: =pod 
  739: 
  740: =item * B<decide_receiver($feedurl,$author,$question,$course,$policy,$defaultflag)>:
  741: 
  742: Arguments
  743:   $feedurl - /res/ url of resource (only need if $author is true)
  744:   $author,$question,$course,$policy - all true/false parameters
  745:     if true will attempt to find the addresses of user that should receive
  746:     this type of feedback (author - feedback to author of resource $feedurl,
  747:     $question 'Resource Content Questions', $course 'Course Content Question',
  748:     $policy 'Course Policy')
  749:     (Additionally it also checks $env for whether the corresponding form.<name>
  750:     element exists, for ease of use in a html response context)
  751:    
  752:   $defaultflag - (internal should be left blank) if true gather addresses 
  753:                  that aren't for a section even if I have a section
  754:                  (used for reccursion internally, first we look for
  755:                  addresses for our specific section then we recurse
  756:                  and look for non section addresses)
  757: 
  758: Returns
  759:   $typestyle - string of html text, describing what addresses were found
  760:   %to - a hash, which keys are addresses of users to send messages to
  761:         the keys will look like   name:domain
  762: 
  763: =cut
  764: 
  765: sub decide_receiver {
  766:     my ($feedurl,$author,$question,$course,$policy,$defaultflag) = @_;
  767:     &Apache::lonenc::check_decrypt(\$feedurl);
  768:     my $typestyle='';
  769:     my %to=();
  770:     if ($env{'form.discuss'} eq 'author' ||$author) {
  771: 	$typestyle.='Submitting as Author Feedback<br />';
  772: 	$feedurl=~ m{^/res/($LONCAPA::domain_re)/($LONCAPA::username_re)/};
  773: 	$to{$2.':'.$1}=1;
  774:     }
  775:     my $cid = $env{'request.course.id'};
  776:     if ($env{'form.discuss'} eq 'question' ||$question) {
  777: 	$typestyle.=&mt('Submitting as Question').'<br />';
  778: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.question.email'})) {
  779: 	    my $rec=&secapply($item,$defaultflag);
  780: 	    if ($rec) { $to{$rec}=1; }
  781: 	} 
  782:     }
  783:     if ($env{'form.discuss'} eq 'course' ||$course) {
  784: 	$typestyle.=&mt('Submitting as Comment').'<br />';
  785: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.comment.email'})) {
  786: 	    my $rec=&secapply($item,$defaultflag);
  787: 	    if ($rec) { $to{$rec}=1; }
  788: 	} 
  789:     }
  790:     if ($env{'form.discuss'} eq 'policy' ||$policy) {
  791: 	$typestyle.=&mt('Submitting as Policy Feedback').'<br />';
  792: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.policy.email'})) {
  793: 	    my $rec=&secapply($item,$defaultflag);
  794: 	    if ($rec) { $to{$rec}=1; }
  795: 	} 
  796:     }
  797:     if ((scalar(%to) eq '0') && (!$defaultflag)) {
  798: 	($typestyle,%to)=
  799: 	    &decide_receiver($feedurl,$author,$question,$course,$policy,1);
  800:     }
  801:     return ($typestyle,%to);
  802: }
  803: 
  804: =pod
  805: 
  806: =back
  807: 
  808: =cut
  809: 
  810: 1;
  811: __END__
  812: 

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