File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.201: download - view: text, annotated - select for diffs
Tue May 1 18:40:57 2007 UTC (17 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 3946. Messages sent with multiple recipients now included only once in "Sent Mail" folder, except when mode is "upload".

lonmsgdisplay.pm
- List of recipients included in message in "Sent Mail" folder for additional cases besides Critical and Broadcast.
- If a recipient has forwarding enabled, sender's record of recipients shows original recipient instead of the user account(s) to which it was forwarded.

lonmsg.pm
- Determination of course context of message moved to subroutine.
- User/domain of sent mail folder can be specified when storing sent mail.

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

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