File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.210: download - view: text, annotated - select for diffs
Sat Aug 18 00:32:52 2007 UTC (16 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: version_2_6_X, version_2_6_3, version_2_6_2, version_2_6_1, version_2_6_0, version_2_5_99_1, version_2_5_99_0, HEAD
- switch from calling critical directly to using cput

    1: # The LearningOnline Network with CAPA
    2: # Routines for messaging
    3: #
    4: # $Id: lonmsg.pm,v 1.210 2007/08/18 00:32:52 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 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,$recipid)=@_;
   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:     if (defined($recipid)) {
  164:         $result.= '<recipid>'.$recipid.'</recipid>';
  165:     }
  166:     if ($env{'form.can_reply'} eq 'N') {
  167:         $result .= '<noreplies>1</noreplies>';
  168:     }
  169:     if ($env{'form.reply_to_addr'}) {
  170:         my ($replytoname,$replytodom) = split(/:/,$env{'form.reply_to_addr'});
  171:         if (!($replytoname eq $env{'user.name'} && $replytodom eq $env{'user.domain'})) {
  172:             if (&Apache::lonnet::homeserver($replytoname,$replytodom) ne 'no_host') {
  173:                 $result .= '<replytoaddr>'.$env{'form.reply_to_addr'}.'</replytoaddr>';
  174:             }
  175:         }
  176:     }
  177:     return ($msgid,$result);
  178: }
  179: 
  180: sub get_course_context {
  181:     my $course_context;
  182:     if (defined($env{'form.replyid'})) {
  183:         my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$origcid)=
  184:                    split(/\:/,&unescape($env{'form.replyid'}));
  185:         $course_context = $origcid;
  186:     }
  187:     foreach my $key (keys(%env)) {
  188:         if ($key=~/^form\.(rep)?rec\_(.*)$/) {
  189:             my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$origcid) =
  190:                                     split(/\:/,&unescape($2));
  191:             $course_context = $origcid;
  192:             last;
  193:         }
  194:     }
  195:     if ($course_context eq '') {
  196:         $course_context = $env{'request.course.id'};
  197:     }
  198:     return $course_context;
  199: }
  200: 
  201: # ================================================== Unpack message into a hash
  202: 
  203: sub unpackagemsg {
  204:     my ($message,$notoken)=@_;
  205:     my %content=();
  206:     my $parser=HTML::TokeParser->new(\$message);
  207:     my $token;
  208:     while ($token=$parser->get_token) {
  209:        if ($token->[0] eq 'S') {
  210: 	   my $entry=$token->[1];
  211:            my $value=$parser->get_text('/'.$entry);
  212:            if (($entry eq 'recuser') || ($entry eq 'recdomain')) {
  213:                push(@{$content{$entry}},$value);
  214:            } elsif ($entry eq 'recipient') {
  215:                my $username = $token->[2]{'username'};
  216:                $username = &HTML::Entities::decode($username,'<>&"');
  217:                $content{$entry}{$username} = $value;
  218:            } else {
  219:                $content{$entry}=$value;
  220:            }
  221:        }
  222:     }
  223:     if (!exists($content{'recuser'})) { $content{'recuser'} = []; }
  224:     if ($content{'attachmenturl'}) {
  225:        my ($fname)=($content{'attachmenturl'}=~m|/([^/]+)$|);
  226:        if ($notoken) {
  227: 	   $content{'message'}.='<p>'.&mt('Attachment').': <tt>'.$fname.'</tt>';
  228:        } else {
  229: 	   &Apache::lonnet::allowuploaded('/adm/msg',
  230: 					  $content{'attachmenturl'});
  231: 	   $content{'message'}.='<p>'.&mt('Attachment').
  232: 	       ': <a href="'.$content{'attachmenturl'}.'"><tt>'.
  233: 	       $fname.'</tt></a>';
  234:        }
  235:     }
  236:     return %content;
  237: }
  238: 
  239: # ======================================================= Get info out of msgid
  240: 
  241: sub buildmsgid {
  242:     my ($now,$subject,$uname,$udom,$msgcount,$course_context,$symb,$error,$pid) = @_;
  243:     $subject=&escape($subject);
  244:     $symb = &escape($symb);
  245:     return(&escape($now.':'.$subject.':'.$uname.':'.
  246:            $udom.':'.$msgcount.':'.$course_context.':'.$pid.':'.$symb.':'.$error));
  247: }
  248: 
  249: sub unpackmsgid {
  250:     my ($msgid,$folder,$skipstatus,$status_cache)=@_;
  251:     $msgid=&unescape($msgid);
  252:     my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$fromcid,
  253:         $processid,$symb,$error) = split(/\:/,&unescape($msgid));
  254:     $shortsubj = &unescape($shortsubj);
  255:     $shortsubj = &HTML::Entities::decode($shortsubj);
  256:     $symb = &unescape($symb);
  257:     if (!defined($processid)) { $fromcid = ''; }
  258:     my %status=();
  259:     unless ($skipstatus) {
  260: 	if (ref($status_cache)) {
  261: 	    $status{$msgid} = $status_cache->{$msgid};
  262: 	} else {
  263: 	    my $suffix=&foldersuffix($folder);
  264: 	    %status=&Apache::lonnet::get('email_status'.$suffix,[$msgid]);
  265: 	}
  266: 	if ($status{$msgid}=~/^error\:/) { $status{$msgid}=''; }
  267:         unless ($status{$msgid}) { $status{$msgid}='new'; }
  268:     }
  269:     return ($sendtime,$shortsubj,$fromname,$fromdomain,$status{$msgid},$fromcid,$symb,$error);
  270: }
  271: 
  272: 
  273: sub sendemail {
  274:     my ($to,$subject,$body)=@_;
  275:     my %senderemails=&Apache::loncommon::getemails();
  276:     my $senderaddress='';
  277:     foreach my $type ('notification','permanentemail','critnotification') {
  278: 	if ($senderemails{$type}) {
  279: 	    $senderaddress=$senderemails{$type};
  280: 	}
  281:     }
  282:     $body=
  283:     "*** ".&mt('This is an automatic message generated by the LON-CAPA system.')."\n".
  284:     "*** ".($senderaddress?&mt('You can reply to this message'):&mt('Please do not reply to this address.')."\n*** ".
  285: 	    &mt('A reply will not be received by the recipient!'))."\n\n".$body;
  286:     my $msg = new Mail::Send;
  287:     $msg->to($to);
  288:     $msg->subject('[LON-CAPA] '.$subject);
  289:     if ($senderaddress) { $msg->add('Reply-to',$senderaddress); $msg->add('From',$senderaddress); }
  290:     if (my $fh = $msg->open()) {
  291: 	print $fh $body;
  292: 	$fh->close;
  293:     }
  294: }
  295: 
  296: # ==================================================== Send notification emails
  297: 
  298: sub sendnotification {
  299:     my ($to,$touname,$toudom,$subj,$crit,$text,$msgid)=@_;
  300:     my $sender=$env{'environment.firstname'}.' '.$env{'environment.lastname'};
  301:     unless ($sender=~/\w/) { 
  302: 	$sender=$env{'user.name'}.':'.$env{'user.domain'};
  303:     }
  304:     my $critical=($crit?' critical':'');
  305: 
  306:     $text=~s/\&lt\;/\</gs;
  307:     $text=~s/\&gt\;/\>/gs;
  308:     my $url='http://'.
  309: 	&Apache::lonnet::hostname(&Apache::lonnet::homeserver($touname,$toudom)).
  310:       '/adm/email?username='.$touname.'&domain='.$toudom;
  311:     my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$fromcid,
  312:         $symb,$error) = &Apache::lonmsg::unpackmsgid($msgid);
  313:     my ($coursetext,$body,$bodybegin,$bodysubj,$bodyend);
  314:     if ($fromcid ne '') {
  315:         $coursetext = "\n".&mt('Course').': ';
  316:         if ($env{'course.'.$fromcid.'.description'} ne '') {
  317:             $coursetext .= $env{'course.'.$fromcid.'.description'};
  318:         } else {
  319:             my %coursehash = &Apache::lonnet::coursedescription($fromcid,);
  320:             if ($coursehash{'description'} ne '') {
  321:                 $coursetext .= $coursehash{'description'};
  322:             }
  323:         }
  324:         $coursetext .= "\n\n";
  325:     }
  326:     my @recipients = split(/,/,$to);
  327:     $bodybegin = $coursetext. 
  328:                &mt('You received a'.$critical.' message from [_1] in LON-CAPA.',$sender).' ';
  329:     $bodysubj = &mt('The subject is 
  330: 
  331:  [_1]
  332: 
  333: ',$subj)."\n".
  334: '=== '.&mt('Excerpt')." ============================================================
  335: ";
  336:     $bodyend = "
  337: ========================================================================
  338: 
  339: ".&mt('Use 
  340: 
  341:  [_1]
  342: 
  343: to access the full message.',$url);
  344:     my %userenv = &Apache::lonnet::get('environment',['notifywithhtml'],$toudom,$touname);
  345:     my $subject = &mt("'New' $critical message from ").$sender;
  346:  
  347:     my ($blocked,$blocktext);
  348:     if (!$crit) {
  349:         my %setters;
  350:         my ($startblock,$endblock) = 
  351:             &Apache::loncommon::blockcheck(\%setters,'com',$touname,$toudom);
  352:         if ($startblock && $endblock) {
  353:             $blocked = 1;
  354:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
  355:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
  356:             $blocktext = &mt('LON-CAPA messages sent to you between [_1] and [_2] will be inaccessible until the end of this time period, because you are a student in a course with an active communications block.',$showstart,$showend);
  357:         }
  358:     }
  359:     if ($userenv{'notifywithhtml'} ne '') {
  360:         my @htmlexcerpt = split(/,/,$userenv{'notifywithhtml'});
  361:         foreach my $addr (@recipients) {
  362:             if ($blocked) {
  363:                 $body = $bodybegin."\n".$blocktext."\n".$bodyend;
  364:             } else {
  365:                 my $sendtext = $text;
  366:                 if (!grep/^\Q$addr\E/,@htmlexcerpt) {
  367:                     $sendtext =~ s/\<\/*[^\>]+\>//gs;
  368:                 }
  369:                 $body = $bodybegin.$bodysubj.$sendtext.$bodyend;
  370:             }
  371:             &sendemail($addr,$subject,$body);
  372:         }
  373:     } else {
  374:         if ($blocked) {
  375:             $body = $bodybegin."\n".$blocktext."\n".$bodyend;
  376:         } else {
  377:             $text =~ s/\<\/*[^\>]+\>//gs;
  378:             $body = $bodybegin.$bodysubj.$text.$bodyend;
  379:         }
  380:         &sendemail($to,$subject,$body);
  381:     }
  382: }
  383: # ============================================================= Check for email
  384: 
  385: sub newmail {
  386:     if ((time-$env{'user.mailcheck.time'})>300) {
  387:         my %what=&Apache::lonnet::get('email_status',['recnewemail']);
  388:         &Apache::lonnet::appenv('user.mailcheck.time'=>time);
  389:         if ($what{'recnewemail'}>0) { return 1; }
  390:     }
  391:     return 0;
  392: }
  393: 
  394: # =============================== Automated message to the author of a resource
  395: 
  396: =pod
  397: 
  398: =item * B<author_res_msg($filename, $message)>: Sends message $message to the owner
  399:     of the resource with the URI $filename.
  400: 
  401: =cut
  402: 
  403: sub author_res_msg {
  404:     my ($filename,$message)=@_;
  405:     unless ($message) { return 'empty'; }
  406:     $filename=&Apache::lonnet::declutter($filename);
  407:     my ($domain,$author,@dummy)=split(/\//,$filename);
  408:     my $homeserver=&Apache::lonnet::homeserver($author,$domain);
  409:     if ($homeserver ne 'no_host') {
  410:        my $id=unpack("%32C*",$message);
  411:        $message .= " <p>This error occurred on machine ".
  412: 	   $Apache::lonnet::perlvar{'lonHostID'}."</p>";
  413:        my $msgid;
  414:        ($msgid,$message)=&packagemsg($filename,$message);
  415:        return &Apache::lonnet::reply('put:'.$domain.':'.$author.
  416:          ':nohist_res_msgs:'.
  417:           &escape($filename.'_'.$id).'='.
  418:           &escape($message),$homeserver);
  419:     }
  420:     return 'no_host';
  421: }
  422: 
  423: # =========================================== Retrieve author resource messages
  424: 
  425: sub retrieve_author_res_msg {
  426:     my $url=shift;
  427:     $url=&Apache::lonnet::declutter($url);
  428:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
  429:     my %errormsgs=&Apache::lonnet::dump('nohist_res_msgs',$domain,$author);
  430:     my $msgs='';
  431:     foreach (keys %errormsgs) {
  432: 	if ($_=~/^\Q$url\E\_\d+$/) {
  433: 	    my %content=&unpackagemsg($errormsgs{$_});
  434: 	    $msgs.='<p><img src="/adm/lonMisc/bomb.gif" /><b>'.
  435: 		$content{'time'}.'</b>: '.$content{'message'}.
  436: 		'<br /></p>';
  437: 	}
  438:     } 
  439:     return $msgs;     
  440: }
  441: 
  442: 
  443: # =============================== Delete all author messages related to one URL
  444: 
  445: sub del_url_author_res_msg {
  446:     my $url=shift;
  447:     $url=&Apache::lonnet::declutter($url);
  448:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
  449:     my @delmsgs=();
  450:     foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
  451: 	if ($_=~/^\Q$url\E\_\d+$/) {
  452: 	    push (@delmsgs,$_);
  453: 	}
  454:     }
  455:     return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
  456: }
  457: # =================================== Clear out all author messages in URL path
  458: 
  459: sub clear_author_res_msg {
  460:     my $url=shift;
  461:     $url=&Apache::lonnet::declutter($url);
  462:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
  463:     my @delmsgs=();
  464:     foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
  465: 	if ($_=~/^\Q$url\E/) {
  466: 	    push (@delmsgs,$_);
  467: 	}
  468:     }
  469:     return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
  470: }
  471: # ================= Return hash with URLs for which there is a resource message
  472: 
  473: sub all_url_author_res_msg {
  474:     my ($author,$domain)=@_;
  475:     my %returnhash=();
  476:     foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
  477: 	$_=~/^(.+)\_\d+/;
  478: 	$returnhash{$1}=1;
  479:     }
  480:     return %returnhash;
  481: }
  482: 
  483: # ====================================== Add a comment to the User Notes screen
  484: 
  485: sub store_instructor_comment {
  486:     my ($msg,$uname,$udom) = @_;
  487:     my $cid  = $env{'request.course.id'};
  488:     my $cnum = $env{'course.'.$cid.'.num'};
  489:     my $cdom = $env{'course.'.$cid.'.domain'};
  490:     my $subject= &mt('Record').' ['.$uname.':'.$udom.']';
  491:     my $result = &user_normal_msg_raw($cnum,$cdom,$subject,$msg);
  492:     if ($result eq 'ok' || $result eq 'con_delayed') {
  493:         
  494:     }
  495:     return $result;
  496: }
  497: 
  498: # ================================================== Critical message to a user
  499: 
  500: sub user_crit_msg_raw {
  501:     my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage,
  502:         $nosentstore,$recipid)=@_;
  503: # Check if allowed missing
  504:     my ($status,$packed_message);
  505:     my $msgid='undefined';
  506:     unless (($message)&&($user)&&($domain)) { $status='empty'; };
  507:     my $text=$message;
  508:     my $homeserver=&Apache::lonnet::homeserver($user,$domain);
  509:     if ($homeserver ne 'no_host') {
  510:        ($msgid,$packed_message)=&packagemsg($subject,$message,undef,undef,
  511:                                   undef,undef,undef,undef,undef,undef,undef,
  512:                                   undef,$recipid);
  513:        if ($sendback) { $packed_message.='<sendback>true</sendback>'; }
  514:        $status=&Apache::lonnet::cput('critical', {$msgid => $packed_message},
  515: 				     $domain,$user);
  516:         if (defined($sentmessage)) {
  517:             $$sentmessage = $packed_message;
  518:         }
  519:         if (!$nosentstore) {
  520:             (undef,my $packed_message_no_citation) =
  521:             &packagemsg($subject,$message,undef,undef,undef,$user,$domain,
  522:                         $msgid);
  523:             if ($status eq 'ok' || $status eq 'con_delayed') {
  524:                 &store_sent_mail($msgid,$packed_message_no_citation);
  525:             }
  526:         }
  527:     } else {
  528:        $status='no_host';
  529:     }
  530: 
  531: # Notifications
  532:     my %userenv = &Apache::loncommon::getemails($user,$domain);
  533:     if ($userenv{'critnotification'}) {
  534:       &sendnotification($userenv{'critnotification'},$user,$domain,$subject,1,
  535: 			$text,$msgid);
  536:     }
  537:     if ($toperm && $userenv{'permanentemail'}) {
  538:       &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,1,
  539: 			$text,$msgid);
  540:     }
  541: # Log this
  542:     &Apache::lonnet::logthis(
  543:       'Sending critical email '.$msgid.
  544:       ', log status: '.
  545:       &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  546:                          $env{'user.home'},
  547:       'Sending critical '.$msgid.' to '.$user.' at '.$domain.' with status: '
  548:       .$status));
  549:     return $status;
  550: }
  551: 
  552: # New routine that respects "forward" and calls old routine
  553: 
  554: =pod
  555: 
  556: =item * B<user_crit_msg($user, $domain, $subject, $message, $sendback, $nosentstore,$recipid)>: 
  557:     Sends a critical message $message to the $user at $domain.  If $sendback
  558:     is true,  a receipt will be sent to the current user when $user receives 
  559:     the message.
  560: 
  561:     Additionally it will check if the user has a Forwarding address
  562:     set, and send the message to that address instead
  563: 
  564:     returns 
  565:       - in array context a list of results for each message that was sent
  566:       - in scalar context a space seperated list of results for each 
  567:            message sent
  568: 
  569: =cut
  570: 
  571: sub user_crit_msg {
  572:     my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage,
  573:         $nosentstore,$recipid)=@_;
  574:     my @status;
  575:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
  576:                                        $domain,$user);
  577:     my $msgforward=$userenv{'msgforward'};
  578:     if ($msgforward) {
  579:        foreach my $addr (split(/\,/,$msgforward)) {
  580: 	 my ($forwuser,$forwdomain)=split(/\:/,$addr);
  581:          push(@status,
  582: 	      &user_crit_msg_raw($forwuser,$forwdomain,$subject,$message,
  583: 				 $sendback,$toperm,$sentmessage,$nosentstore,
  584:                                  $recipid));
  585:        }
  586:     } else { 
  587: 	push(@status,
  588: 	     &user_crit_msg_raw($user,$domain,$subject,$message,$sendback,
  589: 				$toperm,$sentmessage,$nosentstore,$recipid));
  590:     }
  591:     if (wantarray) {
  592: 	return @status;
  593:     }
  594:     return join(' ',@status);
  595: }
  596: 
  597: # =================================================== Critical message received
  598: 
  599: sub user_crit_received {
  600:     my $msgid=shift;
  601:     my %message=&Apache::lonnet::get('critical',[$msgid]);
  602:     my %contents=&unpackagemsg($message{$msgid},1);
  603:     my $destname = $contents{'sendername'};
  604:     my $destdom = $contents{'senderdomain'};
  605:     if ($contents{'replytoaddr'}) {
  606:         my ($repname,$repdom) = split(/:/,$contents{'replytoaddr'});
  607:         if (&Apache::lonnet::homeserver($repname,$repdom) ne 'no_host') {
  608:             $destname = $repname;
  609:             $destdom = $repdom;    
  610:         }
  611:     }
  612:     my $status='rec: '.($contents{'sendback'}?
  613:      &user_normal_msg($destname,$destdom,&mt('Receipt').': '.$env{'user.name'}.
  614:                       ' '.&mt('at').' '.$env{'user.domain'}.', '.
  615:                       $contents{'subject'},&mt('User').' '.$env{'user.name'}.
  616:                       ' '.&mt('at').' '.$env{'user.domain'}.
  617:                       ' acknowledged receipt of message'."\n".'   "'.
  618:                       $contents{'subject'}.'"'."\n".&mt('dated').' '.
  619:                       $contents{'time'}.".\n"
  620:                       ):'no msg req');
  621:     $status.=' trans: '.
  622:      &Apache::lonnet::put(
  623:      'nohist_email',{$contents{'msgid'} => $message{$msgid}});
  624:     $status.=' del: '.
  625:      &Apache::lonnet::del('critical',[$contents{'msgid'}]);
  626:     &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  627:                          $env{'user.home'},'Received critical message '.
  628:                          $contents{'msgid'}.
  629:                          ', '.$status);
  630:     return $status;
  631: }
  632: 
  633: # ======================================================== Normal communication
  634: 
  635: sub user_normal_msg_raw {
  636:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
  637:         $toperm,$currid,$newid,$sentmessage,$crsmsgid,$symb,$restitle,
  638:         $error,$nosentstore,$recipid)=@_;
  639: # Check if allowed missing
  640:     my ($status,$packed_message);
  641:     my $msgid='undefined';
  642:     my $text=$message;
  643:     unless (($message)&&($user)&&($domain)) { $status='empty'; };
  644:     my $homeserver=&Apache::lonnet::homeserver($user,$domain);
  645:     if ($homeserver ne 'no_host') {
  646:        ($msgid,$packed_message)=
  647: 	                 &packagemsg($subject,$message,$citation,$baseurl,
  648:                                      $attachmenturl,$user,$domain,$currid,
  649:                                      undef,$crsmsgid,$symb,$error,$recipid);
  650: 
  651: # Store in user folder
  652:        $status=
  653: 	   &Apache::lonnet::cput('nohist_email',{$msgid => $packed_message},
  654: 				 $domain,$user);
  655: # Save new message received time
  656:        &Apache::lonnet::put
  657:                          ('email_status',{'recnewemail'=>time},$domain,$user);
  658: # Into sent-mail folder if sent mail storage required
  659:        if (!$nosentstore) {
  660:            (undef,my $packed_message_no_citation) =
  661:                &packagemsg($subject,$message,undef,$baseurl,$attachmenturl,
  662:                            $user,$domain,$currid,undef,$crsmsgid,$symb,$error);
  663:            if ($status eq 'ok' || $status eq 'con_delayed') {
  664:                &store_sent_mail($msgid,$packed_message_no_citation);
  665:            }
  666:        }
  667:        if (ref($newid) eq 'SCALAR') {
  668: 	   $$newid = $msgid;
  669:        }
  670:        if (ref($sentmessage) eq 'SCALAR') {
  671: 	   $$sentmessage = $packed_message;
  672:        }
  673: # Notifications
  674:        my %userenv = &Apache::loncommon::getemails($user,$domain);
  675:        if ($userenv{'notification'}) {
  676: 	   &sendnotification($userenv{'notification'},$user,$domain,$subject,0,
  677: 			     $text,$msgid);
  678:        }
  679:        if ($toperm && $userenv{'permanentemail'}) {
  680: 	   &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,0,
  681: 			     $text,$msgid);
  682:        }
  683:        &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  684: 			    $env{'user.home'},
  685: 			    'Sending '.$msgid.' to '.$user.' at '.$domain.' with status: '.$status);
  686:    } else {
  687:        $status='no_host';
  688:    }
  689:     return $status;
  690: }
  691: 
  692: # New routine that respects "forward" and calls old routine
  693: 
  694: =pod
  695: 
  696: =item * B<user_normal_msg($user, $domain, $subject, $message, $citation,
  697:        $baseurl, $attachmenturl, $toperm, $sentmessage, $symb, $restitle,
  698:        $error,$nosentstore,$recipid)>:
  699:  Sends a message to the  $user at $domain, with subject $subject and message $message.
  700: 
  701:     Additionally it will check if the user has a Forwarding address
  702:     set, and send the message to that address instead
  703: 
  704:     returns
  705:       - in array context a list of results for each message that was sent
  706:       - in scalar context a space seperated list of results for each
  707:            message sent
  708: 
  709: =cut
  710: 
  711: sub user_normal_msg {
  712:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
  713: 	$toperm,$sentmessage,$symb,$restitle,$error,$nosentstore,$recipid)=@_;
  714:     my @status;
  715:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
  716:                                        $domain,$user);
  717:     my $msgforward=$userenv{'msgforward'};
  718:     if ($msgforward) {
  719:         foreach (split(/\,/,$msgforward)) {
  720: 	    my ($forwuser,$forwdomain)=split(/\:/,$_);
  721: 	    push(@status,
  722: 	        &user_normal_msg_raw($forwuser,$forwdomain,$subject,$message,
  723: 				     $citation,$baseurl,$attachmenturl,$toperm,
  724: 				     undef,undef,$sentmessage,undef,$symb,
  725:                                      $restitle,$error,$nosentstore,$recipid));
  726:         }
  727:     } else {
  728: 	push(@status,&user_normal_msg_raw($user,$domain,$subject,$message,
  729: 				     $citation,$baseurl,$attachmenturl,$toperm,
  730: 				     undef,undef,$sentmessage,undef,$symb,
  731:                                      $restitle,$error,$nosentstore,$recipid));
  732:     }
  733:     if (wantarray) {
  734:         return @status;
  735:     }
  736:     return join(' ',@status);
  737: }
  738: 
  739: sub process_sent_mail {
  740:     my ($msgsubj,$subj_prefix,$numsent,$stamp,$msgname,$msgdom,$msgcount,$context,$pid,$savemsg,$recusers,$recudoms,$baseurl,$attachmenturl,$symb,$error,$senderuname,$senderdom) = @_;
  741:     my $sentsubj;
  742:     if ($numsent > 1) {
  743:         $sentsubj = $subj_prefix.' ('.$numsent.' sent) '.$msgsubj;
  744:     } else {
  745:         if ($subj_prefix) {
  746:             $sentsubj = $subj_prefix.' ';
  747:         }
  748:         $sentsubj .= $msgsubj;
  749:     }
  750:     $sentsubj = &HTML::Entities::encode($sentsubj,'<>&"');
  751:     my $sentmsgid = 
  752:         &buildmsgid($stamp,$sentsubj,$msgname,$msgdom,$msgcount,$context,$pid);
  753:     (undef,my $sentmessage) =
  754:         &packagemsg($msgsubj,$savemsg,undef,$baseurl,$attachmenturl,$recusers,
  755:                     $recudoms,$sentmsgid,undef,undef,$symb,$error);
  756:     my $status = &store_sent_mail($sentmsgid,$sentmessage,$senderuname,
  757:                                   $senderdom);
  758:     return $status;
  759: }
  760: 
  761: sub store_sent_mail {
  762:     my ($msgid,$message,$senderuname,$senderdom) = @_;
  763:     if ($senderuname eq '') {
  764:         $senderuname = $env{'user.name'};
  765:     }
  766:     if ($senderdom eq '') {
  767:         $senderdom = $env{'user.domain'};
  768:     }
  769:     my $status =' '.&Apache::lonnet::cput('nohist_email_sent',
  770: 					  {$msgid => $message},
  771: 					  $senderdom,$senderuname);
  772:     return $status;
  773: }
  774: 
  775: sub store_recipients {
  776:     my ($subject,$sendername,$senderdom,$reciphash) = @_;
  777:     my $context = &get_course_context();
  778:     my $now = time();
  779:     my $msgcount = &get_uniq();
  780:     my $recipid =
  781:         &buildmsgid($now,$subject,$sendername,$senderdom,$msgcount,$context,$$);
  782:     my %recipinfo = (
  783:                          $recipid => $reciphash,
  784:                     );
  785:     my $status = &Apache::lonnet::put('nohist_emailrecip',\%recipinfo,
  786:                                       $senderdom,$sendername); 
  787:     if ($status eq 'ok') {
  788:         return ($recipid,$status);
  789:     } else {
  790:         return (undef,$status);
  791:     }
  792: }
  793: 
  794: # =============================================================== Folder suffix
  795: 
  796: sub foldersuffix {
  797:     my $folder=shift;
  798:     unless ($folder) { return ''; }
  799:     my $suffix;
  800:     my %folderhash = &get_user_folders($folder);
  801:     if (ref($folderhash{$folder}) eq 'HASH') {
  802:         $suffix = '_'.&escape($folderhash{$folder}{'id'});
  803:     } else {
  804:         $suffix = '_'.&escape($folder);
  805:     }
  806:     return $suffix;
  807: }
  808: 
  809: # ========================================================= User-defined folders 
  810: 
  811: sub get_user_folders {
  812:     my ($folder) = @_;
  813:     my %userfolders = 
  814:           &Apache::lonnet::dump('email_folders',undef,undef,$folder);
  815:     my $lock = "\0".'lock_counter'; # locks db while counter incremented
  816:     my $counter = "\0".'idcount';   # used in suffix for email db files
  817:     if (defined($userfolders{$lock})) {
  818:         delete($userfolders{$lock});
  819:     }
  820:     if (defined($userfolders{$counter})) {
  821:         delete($userfolders{$counter});
  822:     }
  823:     return %userfolders;
  824: }
  825: 
  826: sub secapply {
  827:     my $rec=shift;
  828:     my $defaultflag=shift;
  829:     $rec=~s/\s+//g;
  830:     $rec=~s/\@/\:/g;
  831:     my ($adr,$sections_or_groups)=($rec=~/^([^\(]+)\(([^\)]+)\)/);
  832:     if ($sections_or_groups) {
  833: 	foreach my $item (split(/\;/,$sections_or_groups)) {
  834:             if (($item eq $env{'request.course.sec'}) ||
  835:                 ($defaultflag && ($item eq '*'))) {
  836:                 return $adr; 
  837:             } elsif ($env{'request.course.groups'}) {
  838:                 my @usersgroups = split(/:/,$env{'request.course.groups'});
  839:                 if (grep(/^\Q$item\E$/,@usersgroups)) {
  840:                     return $adr;
  841:                 }
  842:             } 
  843:         }
  844:     } else {
  845:        return $rec;
  846:     }
  847:     return '';
  848: }
  849: 
  850: =pod 
  851: 
  852: =item * B<decide_receiver($feedurl,$author,$question,$course,$policy,$defaultflag)>:
  853: 
  854: Arguments
  855:   $feedurl - /res/ url of resource (only need if $author is true)
  856:   $author,$question,$course,$policy - all true/false parameters
  857:     if true will attempt to find the addresses of user that should receive
  858:     this type of feedback (author - feedback to author of resource $feedurl,
  859:     $question 'Resource Content Questions', $course 'Course Content Question',
  860:     $policy 'Course Policy')
  861:     (Additionally it also checks $env for whether the corresponding form.<name>
  862:     element exists, for ease of use in a html response context)
  863:    
  864:   $defaultflag - (internal should be left blank) if true gather addresses 
  865:                  that aren't for a section even if I have a section
  866:                  (used for reccursion internally, first we look for
  867:                  addresses for our specific section then we recurse
  868:                  and look for non section addresses)
  869: 
  870: Returns
  871:   $typestyle - string of html text, describing what addresses were found
  872:   %to - a hash, which keys are addresses of users to send messages to
  873:         the keys will look like   name:domain
  874: 
  875: =cut
  876: 
  877: sub decide_receiver {
  878:     my ($feedurl,$author,$question,$course,$policy,$defaultflag) = @_;
  879:     &Apache::lonenc::check_decrypt(\$feedurl);
  880:     my $typestyle='';
  881:     my %to=();
  882:     if ($env{'form.discuss'} eq 'author' ||$author) {
  883: 	$typestyle.='Submitting as Author Feedback<br />';
  884: 	$feedurl=~ m{^/res/($LONCAPA::domain_re)/($LONCAPA::username_re)/};
  885: 	$to{$2.':'.$1}=1;
  886:     }
  887:     my $cid = $env{'request.course.id'};
  888:     if ($env{'form.discuss'} eq 'question' ||$question) {
  889: 	$typestyle.=&mt('Submitting as Question').'<br />';
  890: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.question.email'})) {
  891: 	    my $rec=&secapply($item,$defaultflag);
  892: 	    if ($rec) { $to{$rec}=1; }
  893: 	} 
  894:     }
  895:     if ($env{'form.discuss'} eq 'course' ||$course) {
  896: 	$typestyle.=&mt('Submitting as Comment').'<br />';
  897: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.comment.email'})) {
  898: 	    my $rec=&secapply($item,$defaultflag);
  899: 	    if ($rec) { $to{$rec}=1; }
  900: 	} 
  901:     }
  902:     if ($env{'form.discuss'} eq 'policy' ||$policy) {
  903: 	$typestyle.=&mt('Submitting as Policy Feedback').'<br />';
  904: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.policy.email'})) {
  905: 	    my $rec=&secapply($item,$defaultflag);
  906: 	    if ($rec) { $to{$rec}=1; }
  907: 	} 
  908:     }
  909:     if ((scalar(%to) eq '0') && (!$defaultflag)) {
  910: 	($typestyle,%to)=
  911: 	    &decide_receiver($feedurl,$author,$question,$course,$policy,1);
  912:     }
  913:     return ($typestyle,%to);
  914: }
  915: 
  916: =pod
  917: 
  918: =back
  919: 
  920: =cut
  921: 
  922: 1;
  923: __END__
  924: 

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