File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.209: download - view: text, annotated - select for diffs
Thu May 10 00:50:52 2007 UTC (16 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: version_2_5_X, version_2_5_2, version_2_5_1, version_2_5_0, version_2_4_X, version_2_4_99_0, version_2_4_2, version_2_4_1, version_2_4_0, version_2_3_99_0, HEAD
- internationalize

    1: # The LearningOnline Network with CAPA
    2: # Routines for messaging
    3: #
    4: # $Id: lonmsg.pm,v 1.209 2007/05/10 00:50: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::critical(
  515:            'put:'.$domain.':'.$user.':critical:'.
  516:            &escape($msgid).'='.
  517:            &escape($packed_message),$homeserver);
  518:         if (defined($sentmessage)) {
  519:             $$sentmessage = $packed_message;
  520:         }
  521:         if (!$nosentstore) {
  522:             (undef,my $packed_message_no_citation) =
  523:             &packagemsg($subject,$message,undef,undef,undef,$user,$domain,
  524:                         $msgid);
  525:             if ($status eq 'ok' || $status eq 'con_delayed') {
  526:                 &store_sent_mail($msgid,$packed_message_no_citation);
  527:             }
  528:         }
  529:     } else {
  530:        $status='no_host';
  531:     }
  532: 
  533: # Notifications
  534:     my %userenv = &Apache::loncommon::getemails($user,$domain);
  535:     if ($userenv{'critnotification'}) {
  536:       &sendnotification($userenv{'critnotification'},$user,$domain,$subject,1,
  537: 			$text,$msgid);
  538:     }
  539:     if ($toperm && $userenv{'permanentemail'}) {
  540:       &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,1,
  541: 			$text,$msgid);
  542:     }
  543: # Log this
  544:     &Apache::lonnet::logthis(
  545:       'Sending critical email '.$msgid.
  546:       ', log status: '.
  547:       &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  548:                          $env{'user.home'},
  549:       'Sending critical '.$msgid.' to '.$user.' at '.$domain.' with status: '
  550:       .$status));
  551:     return $status;
  552: }
  553: 
  554: # New routine that respects "forward" and calls old routine
  555: 
  556: =pod
  557: 
  558: =item * B<user_crit_msg($user, $domain, $subject, $message, $sendback, $nosentstore,$recipid)>: 
  559:     Sends a critical message $message to the $user at $domain.  If $sendback
  560:     is true,  a receipt will be sent to the current user when $user receives 
  561:     the message.
  562: 
  563:     Additionally it will check if the user has a Forwarding address
  564:     set, and send the message to that address instead
  565: 
  566:     returns 
  567:       - in array context a list of results for each message that was sent
  568:       - in scalar context a space seperated list of results for each 
  569:            message sent
  570: 
  571: =cut
  572: 
  573: sub user_crit_msg {
  574:     my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage,
  575:         $nosentstore,$recipid)=@_;
  576:     my @status;
  577:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
  578:                                        $domain,$user);
  579:     my $msgforward=$userenv{'msgforward'};
  580:     if ($msgforward) {
  581:        foreach my $addr (split(/\,/,$msgforward)) {
  582: 	 my ($forwuser,$forwdomain)=split(/\:/,$addr);
  583:          push(@status,
  584: 	      &user_crit_msg_raw($forwuser,$forwdomain,$subject,$message,
  585: 				 $sendback,$toperm,$sentmessage,$nosentstore,
  586:                                  $recipid));
  587:        }
  588:     } else { 
  589: 	push(@status,
  590: 	     &user_crit_msg_raw($user,$domain,$subject,$message,$sendback,
  591: 				$toperm,$sentmessage,$nosentstore,$recipid));
  592:     }
  593:     if (wantarray) {
  594: 	return @status;
  595:     }
  596:     return join(' ',@status);
  597: }
  598: 
  599: # =================================================== Critical message received
  600: 
  601: sub user_crit_received {
  602:     my $msgid=shift;
  603:     my %message=&Apache::lonnet::get('critical',[$msgid]);
  604:     my %contents=&unpackagemsg($message{$msgid},1);
  605:     my $destname = $contents{'sendername'};
  606:     my $destdom = $contents{'senderdomain'};
  607:     if ($contents{'replytoaddr'}) {
  608:         my ($repname,$repdom) = split(/:/,$contents{'replytoaddr'});
  609:         if (&Apache::lonnet::homeserver($repname,$repdom) ne 'no_host') {
  610:             $destname = $repname;
  611:             $destdom = $repdom;    
  612:         }
  613:     }
  614:     my $status='rec: '.($contents{'sendback'}?
  615:      &user_normal_msg($destname,$destdom,&mt('Receipt').': '.$env{'user.name'}.
  616:                       ' '.&mt('at').' '.$env{'user.domain'}.', '.
  617:                       $contents{'subject'},&mt('User').' '.$env{'user.name'}.
  618:                       ' '.&mt('at').' '.$env{'user.domain'}.
  619:                       ' acknowledged receipt of message'."\n".'   "'.
  620:                       $contents{'subject'}.'"'."\n".&mt('dated').' '.
  621:                       $contents{'time'}.".\n"
  622:                       ):'no msg req');
  623:     $status.=' trans: '.
  624:      &Apache::lonnet::put(
  625:      'nohist_email',{$contents{'msgid'} => $message{$msgid}});
  626:     $status.=' del: '.
  627:      &Apache::lonnet::del('critical',[$contents{'msgid'}]);
  628:     &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  629:                          $env{'user.home'},'Received critical message '.
  630:                          $contents{'msgid'}.
  631:                          ', '.$status);
  632:     return $status;
  633: }
  634: 
  635: # ======================================================== Normal communication
  636: 
  637: sub user_normal_msg_raw {
  638:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
  639:         $toperm,$currid,$newid,$sentmessage,$crsmsgid,$symb,$restitle,
  640:         $error,$nosentstore,$recipid)=@_;
  641: # Check if allowed missing
  642:     my ($status,$packed_message);
  643:     my $msgid='undefined';
  644:     my $text=$message;
  645:     unless (($message)&&($user)&&($domain)) { $status='empty'; };
  646:     my $homeserver=&Apache::lonnet::homeserver($user,$domain);
  647:     if ($homeserver ne 'no_host') {
  648:        ($msgid,$packed_message)=
  649: 	                 &packagemsg($subject,$message,$citation,$baseurl,
  650:                                      $attachmenturl,$user,$domain,$currid,
  651:                                      undef,$crsmsgid,$symb,$error,$recipid);
  652: 
  653: # Store in user folder
  654:        $status=&Apache::lonnet::critical(
  655:            'put:'.$domain.':'.$user.':nohist_email:'.
  656:            &escape($msgid).'='.
  657:            &escape($packed_message),$homeserver);
  658: # Save new message received time
  659:        &Apache::lonnet::put
  660:                          ('email_status',{'recnewemail'=>time},$domain,$user);
  661: # Into sent-mail folder if sent mail storage required
  662:        if (!$nosentstore) {
  663:            (undef,my $packed_message_no_citation) =
  664:                &packagemsg($subject,$message,undef,$baseurl,$attachmenturl,
  665:                            $user,$domain,$currid,undef,$crsmsgid,$symb,$error);
  666:            if ($status eq 'ok' || $status eq 'con_delayed') {
  667:                &store_sent_mail($msgid,$packed_message_no_citation);
  668:            }
  669:        }
  670:        if (ref($newid) eq 'SCALAR') {
  671: 	   $$newid = $msgid;
  672:        }
  673:        if (ref($sentmessage) eq 'SCALAR') {
  674: 	   $$sentmessage = $packed_message;
  675:        }
  676: # Notifications
  677:        my %userenv = &Apache::loncommon::getemails($user,$domain);
  678:        if ($userenv{'notification'}) {
  679: 	   &sendnotification($userenv{'notification'},$user,$domain,$subject,0,
  680: 			     $text,$msgid);
  681:        }
  682:        if ($toperm && $userenv{'permanentemail'}) {
  683: 	   &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,0,
  684: 			     $text,$msgid);
  685:        }
  686:        &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  687: 			    $env{'user.home'},
  688: 			    'Sending '.$msgid.' to '.$user.' at '.$domain.' with status: '.$status);
  689:    } else {
  690:        $status='no_host';
  691:    }
  692:     return $status;
  693: }
  694: 
  695: # New routine that respects "forward" and calls old routine
  696: 
  697: =pod
  698: 
  699: =item * B<user_normal_msg($user, $domain, $subject, $message, $citation,
  700:        $baseurl, $attachmenturl, $toperm, $sentmessage, $symb, $restitle,
  701:        $error,$nosentstore,$recipid)>:
  702:  Sends a message to the  $user at $domain, with subject $subject and message $message.
  703: 
  704:     Additionally it will check if the user has a Forwarding address
  705:     set, and send the message to that address instead
  706: 
  707:     returns
  708:       - in array context a list of results for each message that was sent
  709:       - in scalar context a space seperated list of results for each
  710:            message sent
  711: 
  712: =cut
  713: 
  714: sub user_normal_msg {
  715:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
  716: 	$toperm,$sentmessage,$symb,$restitle,$error,$nosentstore,$recipid)=@_;
  717:     my @status;
  718:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
  719:                                        $domain,$user);
  720:     my $msgforward=$userenv{'msgforward'};
  721:     if ($msgforward) {
  722:         foreach (split(/\,/,$msgforward)) {
  723: 	    my ($forwuser,$forwdomain)=split(/\:/,$_);
  724: 	    push(@status,
  725: 	        &user_normal_msg_raw($forwuser,$forwdomain,$subject,$message,
  726: 				     $citation,$baseurl,$attachmenturl,$toperm,
  727: 				     undef,undef,$sentmessage,undef,$symb,
  728:                                      $restitle,$error,$nosentstore,$recipid));
  729:         }
  730:     } else {
  731: 	push(@status,&user_normal_msg_raw($user,$domain,$subject,$message,
  732: 				     $citation,$baseurl,$attachmenturl,$toperm,
  733: 				     undef,undef,$sentmessage,undef,$symb,
  734:                                      $restitle,$error,$nosentstore,$recipid));
  735:     }
  736:     if (wantarray) {
  737:         return @status;
  738:     }
  739:     return join(' ',@status);
  740: }
  741: 
  742: sub process_sent_mail {
  743:     my ($msgsubj,$subj_prefix,$numsent,$stamp,$msgname,$msgdom,$msgcount,$context,$pid,$savemsg,$recusers,$recudoms,$baseurl,$attachmenturl,$symb,$error,$senderuname,$senderdom,$senderhome) = @_;
  744:     my $sentsubj;
  745:     if ($numsent > 1) {
  746:         $sentsubj = $subj_prefix.' ('.$numsent.' sent) '.$msgsubj;
  747:     } else {
  748:         if ($subj_prefix) {
  749:             $sentsubj = $subj_prefix.' ';
  750:         }
  751:         $sentsubj .= $msgsubj;
  752:     }
  753:     $sentsubj = &HTML::Entities::encode($sentsubj,'<>&"');
  754:     my $sentmsgid = 
  755:         &buildmsgid($stamp,$sentsubj,$msgname,$msgdom,$msgcount,$context,$pid);
  756:     (undef,my $sentmessage) =
  757:         &packagemsg($msgsubj,$savemsg,undef,$baseurl,$attachmenturl,$recusers,
  758:                     $recudoms,$sentmsgid,undef,undef,$symb,$error);
  759:     my $status = &store_sent_mail($sentmsgid,$sentmessage,$senderuname,
  760:                                   $senderdom,$senderhome);
  761:     return $status;
  762: }
  763: 
  764: sub store_sent_mail {
  765:     my ($msgid,$message,$senderuname,$senderdom,$senderhome) = @_;
  766:     if ($senderuname eq '') {
  767:         $senderuname = $env{'user.name'};
  768:     }
  769:     if ($senderdom eq '') {
  770:         $senderdom = $env{'user.domain'};
  771:     }
  772:     if ($senderhome eq '') {
  773:         $senderhome = $env{'user.home'};
  774:     }
  775:     my $status =' '.&Apache::lonnet::critical(
  776:                'put:'.$senderdom.':'.$senderuname.':nohist_email_sent:'.
  777:                &escape($msgid).'='.&escape($message),$senderhome);
  778:     return $status;
  779: }
  780: 
  781: sub store_recipients {
  782:     my ($subject,$sendername,$senderdom,$reciphash) = @_;
  783:     my $context = &get_course_context();
  784:     my $now = time();
  785:     my $msgcount = &get_uniq();
  786:     my $recipid =
  787:         &buildmsgid($now,$subject,$sendername,$senderdom,$msgcount,$context,$$);
  788:     my %recipinfo = (
  789:                          $recipid => $reciphash,
  790:                     );
  791:     my $status = &Apache::lonnet::put('nohist_emailrecip',\%recipinfo,
  792:                                       $senderdom,$sendername); 
  793:     if ($status eq 'ok') {
  794:         return ($recipid,$status);
  795:     } else {
  796:         return (undef,$status);
  797:     }
  798: }
  799: 
  800: # =============================================================== Folder suffix
  801: 
  802: sub foldersuffix {
  803:     my $folder=shift;
  804:     unless ($folder) { return ''; }
  805:     my $suffix;
  806:     my %folderhash = &get_user_folders($folder);
  807:     if (ref($folderhash{$folder}) eq 'HASH') {
  808:         $suffix = '_'.&escape($folderhash{$folder}{'id'});
  809:     } else {
  810:         $suffix = '_'.&escape($folder);
  811:     }
  812:     return $suffix;
  813: }
  814: 
  815: # ========================================================= User-defined folders 
  816: 
  817: sub get_user_folders {
  818:     my ($folder) = @_;
  819:     my %userfolders = 
  820:           &Apache::lonnet::dump('email_folders',undef,undef,$folder);
  821:     my $lock = "\0".'lock_counter'; # locks db while counter incremented
  822:     my $counter = "\0".'idcount';   # used in suffix for email db files
  823:     if (defined($userfolders{$lock})) {
  824:         delete($userfolders{$lock});
  825:     }
  826:     if (defined($userfolders{$counter})) {
  827:         delete($userfolders{$counter});
  828:     }
  829:     return %userfolders;
  830: }
  831: 
  832: sub secapply {
  833:     my $rec=shift;
  834:     my $defaultflag=shift;
  835:     $rec=~s/\s+//g;
  836:     $rec=~s/\@/\:/g;
  837:     my ($adr,$sections_or_groups)=($rec=~/^([^\(]+)\(([^\)]+)\)/);
  838:     if ($sections_or_groups) {
  839: 	foreach my $item (split(/\;/,$sections_or_groups)) {
  840:             if (($item eq $env{'request.course.sec'}) ||
  841:                 ($defaultflag && ($item eq '*'))) {
  842:                 return $adr; 
  843:             } elsif ($env{'request.course.groups'}) {
  844:                 my @usersgroups = split(/:/,$env{'request.course.groups'});
  845:                 if (grep(/^\Q$item\E$/,@usersgroups)) {
  846:                     return $adr;
  847:                 }
  848:             } 
  849:         }
  850:     } else {
  851:        return $rec;
  852:     }
  853:     return '';
  854: }
  855: 
  856: =pod 
  857: 
  858: =item * B<decide_receiver($feedurl,$author,$question,$course,$policy,$defaultflag)>:
  859: 
  860: Arguments
  861:   $feedurl - /res/ url of resource (only need if $author is true)
  862:   $author,$question,$course,$policy - all true/false parameters
  863:     if true will attempt to find the addresses of user that should receive
  864:     this type of feedback (author - feedback to author of resource $feedurl,
  865:     $question 'Resource Content Questions', $course 'Course Content Question',
  866:     $policy 'Course Policy')
  867:     (Additionally it also checks $env for whether the corresponding form.<name>
  868:     element exists, for ease of use in a html response context)
  869:    
  870:   $defaultflag - (internal should be left blank) if true gather addresses 
  871:                  that aren't for a section even if I have a section
  872:                  (used for reccursion internally, first we look for
  873:                  addresses for our specific section then we recurse
  874:                  and look for non section addresses)
  875: 
  876: Returns
  877:   $typestyle - string of html text, describing what addresses were found
  878:   %to - a hash, which keys are addresses of users to send messages to
  879:         the keys will look like   name:domain
  880: 
  881: =cut
  882: 
  883: sub decide_receiver {
  884:     my ($feedurl,$author,$question,$course,$policy,$defaultflag) = @_;
  885:     &Apache::lonenc::check_decrypt(\$feedurl);
  886:     my $typestyle='';
  887:     my %to=();
  888:     if ($env{'form.discuss'} eq 'author' ||$author) {
  889: 	$typestyle.='Submitting as Author Feedback<br />';
  890: 	$feedurl=~ m{^/res/($LONCAPA::domain_re)/($LONCAPA::username_re)/};
  891: 	$to{$2.':'.$1}=1;
  892:     }
  893:     my $cid = $env{'request.course.id'};
  894:     if ($env{'form.discuss'} eq 'question' ||$question) {
  895: 	$typestyle.=&mt('Submitting as Question').'<br />';
  896: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.question.email'})) {
  897: 	    my $rec=&secapply($item,$defaultflag);
  898: 	    if ($rec) { $to{$rec}=1; }
  899: 	} 
  900:     }
  901:     if ($env{'form.discuss'} eq 'course' ||$course) {
  902: 	$typestyle.=&mt('Submitting as Comment').'<br />';
  903: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.comment.email'})) {
  904: 	    my $rec=&secapply($item,$defaultflag);
  905: 	    if ($rec) { $to{$rec}=1; }
  906: 	} 
  907:     }
  908:     if ($env{'form.discuss'} eq 'policy' ||$policy) {
  909: 	$typestyle.=&mt('Submitting as Policy Feedback').'<br />';
  910: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.policy.email'})) {
  911: 	    my $rec=&secapply($item,$defaultflag);
  912: 	    if ($rec) { $to{$rec}=1; }
  913: 	} 
  914:     }
  915:     if ((scalar(%to) eq '0') && (!$defaultflag)) {
  916: 	($typestyle,%to)=
  917: 	    &decide_receiver($feedurl,$author,$question,$course,$policy,1);
  918:     }
  919:     return ($typestyle,%to);
  920: }
  921: 
  922: =pod
  923: 
  924: =back
  925: 
  926: =cut
  927: 
  928: 1;
  929: __END__
  930: 

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