File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.193: download - view: text, annotated - select for diffs
Wed Dec 27 20:42:12 2006 UTC (17 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_3_0, HEAD
Bug 5116.  Also check for return status of 'ok' or 'con_delayed' to store sent mail or send a message to user's User Notes.

    1: # The LearningOnline Network with CAPA
    2: # Routines for messaging
    3: #
    4: # $Id: lonmsg.pm,v 1.193 2006/12/27 20:42:12 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: use strict;
   32: use Apache::lonnet;
   33: use HTML::TokeParser();
   34: use Apache::lonlocal;
   35: use Mail::Send;
   36: use LONCAPA qw(:DEFAULT :match);
   37: 
   38: {
   39:     my $uniq;
   40:     sub get_uniq {
   41: 	$uniq++;
   42: 	return $uniq;
   43:     }
   44: }
   45: 
   46: # ===================================================================== Package
   47: 
   48: sub packagemsg {
   49:     my ($subject,$message,$citation,$baseurl,$attachmenturl,
   50: 	$recuser,$recdomain,$msgid,$type,$crsmsgid,$symb,$error)=@_;
   51:     $message =&HTML::Entities::encode($message,'<>&"');
   52:     $citation=&HTML::Entities::encode($citation,'<>&"');
   53:     $subject =&HTML::Entities::encode($subject,'<>&"');
   54:     #remove machine specification
   55:     $baseurl =~ s|^http://[^/]+/|/|;
   56:     $baseurl =&HTML::Entities::encode($baseurl,'<>&"');
   57:     #remove machine specification
   58:     $attachmenturl =~ s|^http://[^/]+/|/|;
   59:     $attachmenturl =&HTML::Entities::encode($attachmenturl,'<>&"');
   60:     my $course_context;
   61:     if (defined($env{'form.replyid'})) {
   62:         my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$origcid)=
   63:                    split(/\:/,&unescape($env{'form.replyid'}));
   64:         $course_context = $origcid;
   65:     }
   66:     foreach my $key (keys(%env)) {
   67:         if ($key=~/^form\.(rep)?rec\_(.*)$/) {
   68:             my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$origcid) =
   69:                                     split(/\:/,&unescape($2));
   70:             $course_context = $origcid;
   71:             last;
   72:         }
   73:     }
   74:     unless(defined($course_context)) {
   75:         $course_context = $env{'request.course.id'};
   76:     }
   77:     my $now=time;
   78:     my $msgcount = &get_uniq();
   79:     unless(defined($msgid)) {
   80:         $msgid = &buildmsgid($now,$subject,$env{'user.name'},$env{'user.domain'},
   81:                            $msgcount,$course_context,$symb,$error,$$);
   82:     }
   83:     my $result = '<sendername>'.$env{'user.name'}.'</sendername>'.
   84:            '<senderdomain>'.$env{'user.domain'}.'</senderdomain>'.
   85:            '<subject>'.$subject.'</subject>'.
   86:            '<time>'.&Apache::lonlocal::locallocaltime($now).'</time>';
   87:     if (defined($crsmsgid)) {
   88:         $result.= '<courseid>'.$course_context.'</courseid>'.
   89:                   '<coursesec>'.$env{'request.course.sec'}.'</coursesec>'.
   90:                   '<msgid>'.$msgid.'</msgid>'.
   91:                   '<coursemsgid>'.$crsmsgid.'</coursemsgid>'.
   92:                   '<message>'.$message.'</message>';
   93:         return ($msgid,$result);
   94:     }
   95:     $result .= '<servername>'.$ENV{'SERVER_NAME'}.'</servername>'.
   96:            '<host>'.$ENV{'HTTP_HOST'}.'</host>'.
   97: 	   '<client>'.$ENV{'REMOTE_ADDR'}.'</client>'.
   98: 	   '<browsertype>'.$env{'browser.type'}.'</browsertype>'.
   99: 	   '<browseros>'.$env{'browser.os'}.'</browseros>'.
  100: 	   '<browserversion>'.$env{'browser.version'}.'</browserversion>'.
  101:            '<browsermathml>'.$env{'browser.mathml'}.'</browsermathml>'.
  102: 	   '<browserraw>'.$ENV{'HTTP_USER_AGENT'}.'</browserraw>'.
  103: 	   '<courseid>'.$course_context.'</courseid>'.
  104: 	   '<coursesec>'.$env{'request.course.sec'}.'</coursesec>'.
  105: 	   '<role>'.$env{'request.role'}.'</role>'.
  106: 	   '<resource>'.$env{'request.filename'}.'</resource>'.
  107:            '<msgid>'.$msgid.'</msgid>';
  108:     if (ref($recuser) eq 'ARRAY') {
  109:         for (my $i=0; $i<@{$recuser}; $i++) {
  110:             if ($type eq 'dcmail') {
  111:                 my ($username,$email) = split(/:/,$$recuser[$i]);
  112:                 $username = &unescape($username);
  113:                 $email = &unescape($email);
  114:                 $username = &HTML::Entities::encode($username,'<>&"');
  115:                 $email = &HTML::Entities::encode($email,'<>&"');
  116:                 $result .= '<recipient username="'.$username.'">'.
  117:                                             $email.'</recipient>';
  118:             } else {
  119:                 $result .= '<recuser>'.$$recuser[$i].'</recuser>'.
  120:                            '<recdomain>'.$$recdomain[$i].'</recdomain>';
  121:             }
  122:         }
  123:     } else {
  124:         $result .= '<recuser>'.$recuser.'</recuser>'.
  125:                    '<recdomain>'.$recdomain.'</recdomain>';
  126:     }
  127:     $result .= '<message>'.$message.'</message>';
  128:     if (defined($citation)) {
  129: 	$result.='<citation>'.$citation.'</citation>';
  130:     }
  131:     if (defined($baseurl)) {
  132: 	$result.= '<baseurl>'.$baseurl.'</baseurl>';
  133:     }
  134:     if (defined($attachmenturl)) {
  135: 	$result.= '<attachmenturl>'.$attachmenturl.'</attachmenturl>';
  136:     }
  137:     if (defined($symb)) {
  138:         $result.= '<symb>'.$symb.'</symb>';
  139:         if (defined($course_context)) {
  140:             if ($course_context eq $env{'request.course.id'}) {
  141:                 my $resource_title = &Apache::lonnet::gettitle($symb);
  142:                 if (defined($resource_title)) {
  143:                     $result .= '<resource_title>'.$resource_title.'</resource_title>';
  144:                 }
  145:             }
  146:         }
  147:     }
  148:     return ($msgid,$result);
  149: }
  150: 
  151: # ================================================== Unpack message into a hash
  152: 
  153: sub unpackagemsg {
  154:     my ($message,$notoken)=@_;
  155:     my %content=();
  156:     my $parser=HTML::TokeParser->new(\$message);
  157:     my $token;
  158:     while ($token=$parser->get_token) {
  159:        if ($token->[0] eq 'S') {
  160: 	   my $entry=$token->[1];
  161:            my $value=$parser->get_text('/'.$entry);
  162:            if (($entry eq 'recuser') || ($entry eq 'recdomain')) {
  163:                push(@{$content{$entry}},$value);
  164:            } elsif ($entry eq 'recipient') {
  165:                my $username = $token->[2]{'username'};
  166:                $username = &HTML::Entities::decode($username,'<>&"');
  167:                $content{$entry}{$username} = $value;
  168:            } else {
  169:                $content{$entry}=$value;
  170:            }
  171:        }
  172:     }
  173:     if (!exists($content{'recuser'})) { $content{'recuser'} = []; }
  174:     if ($content{'attachmenturl'}) {
  175:        my ($fname)=($content{'attachmenturl'}=~m|/([^/]+)$|);
  176:        if ($notoken) {
  177: 	   $content{'message'}.='<p>'.&mt('Attachment').': <tt>'.$fname.'</tt>';
  178:        } else {
  179: 	   &Apache::lonnet::allowuploaded('/adm/msg',
  180: 					  $content{'attachmenturl'});
  181: 	   $content{'message'}.='<p>'.&mt('Attachment').
  182: 	       ': <a href="'.$content{'attachmenturl'}.'"><tt>'.
  183: 	       $fname.'</tt></a>';
  184:        }
  185:     }
  186:     return %content;
  187: }
  188: 
  189: # ======================================================= Get info out of msgid
  190: 
  191: sub buildmsgid {
  192:     my ($now,$subject,$uname,$udom,$msgcount,$course_context,$symb,$error,$pid) = @_;
  193:     $subject=&escape($subject);
  194:     $symb = &escape($symb);
  195:     return(&escape($now.':'.$subject.':'.$uname.':'.
  196:            $udom.':'.$msgcount.':'.$course_context.':'.$pid.':'.$symb.':'.$error));
  197: }
  198: 
  199: sub unpackmsgid {
  200:     my ($msgid,$folder,$skipstatus,$status_cache)=@_;
  201:     $msgid=&unescape($msgid);
  202:     my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$fromcid,
  203:         $processid,$symb,$error) = split(/\:/,&unescape($msgid));
  204:     $shortsubj = &unescape($shortsubj);
  205:     $shortsubj = &HTML::Entities::decode($shortsubj);
  206:     $symb = &unescape($symb);
  207:     if (!defined($processid)) { $fromcid = ''; }
  208:     my %status=();
  209:     unless ($skipstatus) {
  210: 	if (ref($status_cache)) {
  211: 	    $status{$msgid} = $status_cache->{$msgid};
  212: 	} else {
  213: 	    my $suffix=&foldersuffix($folder);
  214: 	    %status=&Apache::lonnet::get('email_status'.$suffix,[$msgid]);
  215: 	}
  216: 	if ($status{$msgid}=~/^error\:/) { $status{$msgid}=''; }
  217:         unless ($status{$msgid}) { $status{$msgid}='new'; }
  218:     }
  219:     return ($sendtime,$shortsubj,$fromname,$fromdomain,$status{$msgid},$fromcid,$symb,$error);
  220: }
  221: 
  222: 
  223: sub sendemail {
  224:     my ($to,$subject,$body)=@_;
  225:     my %senderemails=&Apache::loncommon::getemails();
  226:     my $senderaddress='';
  227:     foreach my $type ('notification','permanentemail','critnotification') {
  228: 	if ($senderemails{$type}) {
  229: 	    $senderaddress=$senderemails{$type};
  230: 	}
  231:     }
  232:     $body=
  233:     "*** ".&mt('This is an automatic message generated by the LON-CAPA system.')."\n".
  234:     "*** ".($senderaddress?&mt('You can reply to this message'):&mt('Please do not reply to this address.')."\n*** ".
  235: 	    &mt('A reply will not be received by the recipient!'))."\n\n".$body;
  236:     my $msg = new Mail::Send;
  237:     $msg->to($to);
  238:     $msg->subject('[LON-CAPA] '.$subject);
  239:     if ($senderaddress) { $msg->add('Reply-to',$senderaddress); $msg->add('From',$senderaddress); }
  240:     if (my $fh = $msg->open()) {
  241: 	print $fh $body;
  242: 	$fh->close;
  243:     }
  244: }
  245: 
  246: # ==================================================== Send notification emails
  247: 
  248: sub sendnotification {
  249:     my ($to,$touname,$toudom,$subj,$crit,$text)=@_;
  250:     my $sender=$env{'environment.firstname'}.' '.$env{'environment.lastname'};
  251:     unless ($sender=~/\w/) { 
  252: 	$sender=$env{'user.name'}.'@'.$env{'user.domain'};
  253:     }
  254:     my $critical=($crit?' critical':'');
  255:     $text=~s/\&lt\;/\</gs;
  256:     $text=~s/\&gt\;/\>/gs;
  257:     $text=~s/\<\/*[^\>]+\>//gs;
  258:     my $url='http://'.
  259:       $Apache::lonnet::hostname{&Apache::lonnet::homeserver($touname,$toudom)}.
  260:       '/adm/email?username='.$touname.'&domain='.$toudom;
  261:     my $body=(<<ENDMSG);
  262: You received a$critical message from $sender in LON-CAPA. The subject is
  263: 
  264:  $subj
  265: 
  266: === Excerpt ============================================================
  267: $text
  268: ========================================================================
  269: 
  270: Use
  271: 
  272:  $url
  273: 
  274: to access the full message.
  275: ENDMSG
  276:     &sendemail($to,'New'.$critical.' message from '.$sender,$body);
  277: }
  278: # ============================================================= Check for email
  279: 
  280: sub newmail {
  281:     if ((time-$env{'user.mailcheck.time'})>300) {
  282:         my %what=&Apache::lonnet::get('email_status',['recnewemail']);
  283:         &Apache::lonnet::appenv('user.mailcheck.time'=>time);
  284:         if ($what{'recnewemail'}>0) { return 1; }
  285:     }
  286:     return 0;
  287: }
  288: 
  289: # =============================== Automated message to the author of a resource
  290: 
  291: =pod
  292: 
  293: =item * B<author_res_msg($filename, $message)>: Sends message $message to the owner
  294:     of the resource with the URI $filename.
  295: 
  296: =cut
  297: 
  298: sub author_res_msg {
  299:     my ($filename,$message)=@_;
  300:     unless ($message) { return 'empty'; }
  301:     $filename=&Apache::lonnet::declutter($filename);
  302:     my ($domain,$author,@dummy)=split(/\//,$filename);
  303:     my $homeserver=&Apache::lonnet::homeserver($author,$domain);
  304:     if ($homeserver ne 'no_host') {
  305:        my $id=unpack("%32C*",$message);
  306:        $message .= " <p>This error occurred on machine ".
  307: 	   $Apache::lonnet::perlvar{'lonHostID'}."</p>";
  308:        my $msgid;
  309:        ($msgid,$message)=&packagemsg($filename,$message);
  310:        return &Apache::lonnet::reply('put:'.$domain.':'.$author.
  311:          ':nohist_res_msgs:'.
  312:           &escape($filename.'_'.$id).'='.
  313:           &escape($message),$homeserver);
  314:     }
  315:     return 'no_host';
  316: }
  317: 
  318: # =========================================== Retrieve author resource messages
  319: 
  320: sub retrieve_author_res_msg {
  321:     my $url=shift;
  322:     $url=&Apache::lonnet::declutter($url);
  323:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
  324:     my %errormsgs=&Apache::lonnet::dump('nohist_res_msgs',$domain,$author);
  325:     my $msgs='';
  326:     foreach (keys %errormsgs) {
  327: 	if ($_=~/^\Q$url\E\_\d+$/) {
  328: 	    my %content=&unpackagemsg($errormsgs{$_});
  329: 	    $msgs.='<p><img src="/adm/lonMisc/bomb.gif" /><b>'.
  330: 		$content{'time'}.'</b>: '.$content{'message'}.
  331: 		'<br /></p>';
  332: 	}
  333:     } 
  334:     return $msgs;     
  335: }
  336: 
  337: 
  338: # =============================== Delete all author messages related to one URL
  339: 
  340: sub del_url_author_res_msg {
  341:     my $url=shift;
  342:     $url=&Apache::lonnet::declutter($url);
  343:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
  344:     my @delmsgs=();
  345:     foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
  346: 	if ($_=~/^\Q$url\E\_\d+$/) {
  347: 	    push (@delmsgs,$_);
  348: 	}
  349:     }
  350:     return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
  351: }
  352: # =================================== Clear out all author messages in URL path
  353: 
  354: sub clear_author_res_msg {
  355:     my $url=shift;
  356:     $url=&Apache::lonnet::declutter($url);
  357:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
  358:     my @delmsgs=();
  359:     foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
  360: 	if ($_=~/^\Q$url\E/) {
  361: 	    push (@delmsgs,$_);
  362: 	}
  363:     }
  364:     return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
  365: }
  366: # ================= Return hash with URLs for which there is a resource message
  367: 
  368: sub all_url_author_res_msg {
  369:     my ($author,$domain)=@_;
  370:     my %returnhash=();
  371:     foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
  372: 	$_=~/^(.+)\_\d+/;
  373: 	$returnhash{$1}=1;
  374:     }
  375:     return %returnhash;
  376: }
  377: 
  378: # ====================================== Add a comment to the User Notes screen
  379: 
  380: sub store_instructor_comment {
  381:     my ($msg,$uname,$udom) = @_;
  382:     my $cid  = $env{'request.course.id'};
  383:     my $cnum = $env{'course.'.$cid.'.num'};
  384:     my $cdom = $env{'course.'.$cid.'.domain'};
  385:     my $subject= &mt('Record').' ['.$uname.':'.$udom.']';
  386:     my $result = &user_normal_msg_raw($cnum,$cdom,$subject,$msg);
  387:     return $result;
  388: }
  389: 
  390: # ================================================== Critical message to a user
  391: 
  392: sub user_crit_msg_raw {
  393:     my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage)=@_;
  394: # Check if allowed missing
  395:     my ($status,$packed_message);
  396:     my $msgid='undefined';
  397:     unless (($message)&&($user)&&($domain)) { $status='empty'; };
  398:     my $text=$message;
  399:     my $homeserver=&Apache::lonnet::homeserver($user,$domain);
  400:     if ($homeserver ne 'no_host') {
  401:        ($msgid,$packed_message)=&packagemsg($subject,$message);
  402:        if ($sendback) { $packed_message.='<sendback>true</sendback>'; }
  403:        $status=&Apache::lonnet::critical(
  404:            'put:'.$domain.':'.$user.':critical:'.
  405:            &escape($msgid).'='.
  406:            &escape($packed_message),$homeserver);
  407:         if (defined($sentmessage)) {
  408:             $$sentmessage = $packed_message;
  409:         }
  410:         if ($env{'request.course.id'} eq '') {
  411:             (undef,my $packed_message_no_citation) =
  412:             &packagemsg($subject,$message,undef,undef,undef,$user,$domain,
  413:                         $msgid);
  414:             if ($status eq 'ok' || $status eq 'con_delayed') {
  415:                 &store_sent_mail($msgid,$packed_message_no_citation);
  416:             }
  417:         }
  418:     } else {
  419:        $status='no_host';
  420:     }
  421: 
  422: # Notifications
  423:     my %userenv = &Apache::loncommon::getemails($user,$domain);
  424:     if ($userenv{'critnotification'}) {
  425:       &sendnotification($userenv{'critnotification'},$user,$domain,$subject,1,
  426: 			$text);
  427:     }
  428:     if ($toperm && $userenv{'permanentemail'}) {
  429:       &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,1,
  430: 			$text);
  431:     }
  432: # Log this
  433:     &Apache::lonnet::logthis(
  434:       'Sending critical email '.$msgid.
  435:       ', log status: '.
  436:       &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  437:                          $env{'user.home'},
  438:       'Sending critical '.$msgid.' to '.$user.' at '.$domain.' with status: '
  439:       .$status));
  440:     return $status;
  441: }
  442: 
  443: # New routine that respects "forward" and calls old routine
  444: 
  445: =pod
  446: 
  447: =item * B<user_crit_msg($user, $domain, $subject, $message, $sendback)>: Sends
  448:     a critical message $message to the $user at $domain. If $sendback is true,
  449:     a reciept will be sent to the current user when $user recieves the message.
  450: 
  451:     Additionally it will check if the user has a Forwarding address
  452:     set, and send the message to that address instead
  453: 
  454:     returns 
  455:       - in array context a list of results for each message that was sent
  456:       - in scalar context a space seperated list of results for each 
  457:            message sent
  458: 
  459: =cut
  460: 
  461: sub user_crit_msg {
  462:     my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage)=@_;
  463:     my @status;
  464:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
  465:                                        $domain,$user);
  466:     my $msgforward=$userenv{'msgforward'};
  467:     if ($msgforward) {
  468:        foreach my $addr (split(/\,/,$msgforward)) {
  469: 	 my ($forwuser,$forwdomain)=split(/\:/,$addr);
  470:          push(@status,
  471: 	      &user_crit_msg_raw($forwuser,$forwdomain,$subject,$message,
  472: 				 $sendback,$toperm,$sentmessage));
  473:        }
  474:     } else { 
  475: 	push(@status,
  476: 	     &user_crit_msg_raw($user,$domain,$subject,$message,$sendback,
  477: 				$toperm,$sentmessage));
  478:     }
  479:     if (wantarray) {
  480: 	return @status;
  481:     }
  482:     return join(' ',@status);
  483: }
  484: 
  485: # =================================================== Critical message received
  486: 
  487: sub user_crit_received {
  488:     my $msgid=shift;
  489:     my %message=&Apache::lonnet::get('critical',[$msgid]);
  490:     my %contents=&unpackagemsg($message{$msgid},1);
  491:     my $status='rec: '.($contents{'sendback'}?
  492:      &user_normal_msg($contents{'sendername'},$contents{'senderdomain'},
  493:                      &mt('Receipt').': '.$env{'user.name'}.' '.&mt('at').' '.$env{'user.domain'}.', '.$contents{'subject'},
  494:                      &mt('User').' '.$env{'user.name'}.' '.&mt('at').' '.$env{'user.domain'}.
  495:                      ' acknowledged receipt of message'."\n".'   "'.
  496:                      $contents{'subject'}.'"'."\n".&mt('dated').' '.
  497:                      $contents{'time'}.".\n"
  498:                      ):'no msg req');
  499:     $status.=' trans: '.
  500:      &Apache::lonnet::put(
  501:      'nohist_email',{$contents{'msgid'} => $message{$msgid}});
  502:     $status.=' del: '.
  503:      &Apache::lonnet::del('critical',[$contents{'msgid'}]);
  504:     &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  505:                          $env{'user.home'},'Received critical message '.
  506:                          $contents{'msgid'}.
  507:                          ', '.$status);
  508:     return $status;
  509: }
  510: 
  511: # ======================================================== Normal communication
  512: 
  513: sub user_normal_msg_raw {
  514:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
  515:         $toperm,$currid,$newid,$sentmessage,$crsmsgid,$symb,$restitle,
  516:         $error)=@_;
  517: # Check if allowed missing
  518:     my ($status,$packed_message);
  519:     my $msgid='undefined';
  520:     my $text=$message;
  521:     unless (($message)&&($user)&&($domain)) { $status='empty'; };
  522:     my $homeserver=&Apache::lonnet::homeserver($user,$domain);
  523:     if ($homeserver ne 'no_host') {
  524:        ($msgid,$packed_message)=
  525: 	                 &packagemsg($subject,$message,$citation,$baseurl,
  526:                                      $attachmenturl,$user,$domain,$currid,
  527:                                      undef,$crsmsgid,$symb,$error);
  528: 
  529: # Store in user folder
  530:        $status=&Apache::lonnet::critical(
  531:            'put:'.$domain.':'.$user.':nohist_email:'.
  532:            &escape($msgid).'='.
  533:            &escape($packed_message),$homeserver);
  534: # Save new message received time
  535:        &Apache::lonnet::put
  536:                          ('email_status',{'recnewemail'=>time},$domain,$user);
  537: # Into sent-mail folder unless a broadcast message or critical message
  538:        unless (($env{'request.course.id'}) && 
  539:                (($env{'form.sendmode'} eq 'group')  || 
  540:                (($env{'form.critmsg'}) || ($env{'form.sendbck'})) &&
  541:                (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  542: 		|| &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  543: 					    '/'.$env{'request.course.sec'})))) {
  544:            (undef,my $packed_message_no_citation) =
  545:                &packagemsg($subject,$message,undef,$baseurl,$attachmenturl,
  546:                            $user,$domain,$currid,undef,$crsmsgid,$symb,$error);
  547:            if ($status eq 'ok' || $status eq 'con_delayed') {
  548:                &store_sent_mail($msgid,$packed_message_no_citation);
  549:            }
  550:        }
  551:     } else {
  552:        $status='no_host';
  553:     }
  554:     if (defined($newid)) {
  555:         $$newid = $msgid;
  556:     }
  557:     if (defined($sentmessage)) {
  558:         $$sentmessage = $packed_message;
  559:     }
  560: 
  561: # Notifications
  562:     my %userenv = &Apache::lonnet::get('environment',['notification',
  563:                                                       'permanentemail'],
  564:                                        $domain,$user);
  565:     if ($userenv{'notification'}) {
  566: 	&sendnotification($userenv{'notification'},$user,$domain,$subject,0,
  567: 			  $text);
  568:     }
  569:     if ($toperm && $userenv{'permanentemail'}) {
  570: 	&sendnotification($userenv{'permanentemail'},$user,$domain,$subject,0,
  571: 			  $text);
  572:     }
  573:     &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  574:                          $env{'user.home'},
  575:       'Sending '.$msgid.' to '.$user.' at '.$domain.' with status: '.$status);
  576:     return $status;
  577: }
  578: 
  579: # New routine that respects "forward" and calls old routine
  580: 
  581: =pod
  582: 
  583: =item * B<user_normal_msg($user, $domain, $subject, $message, $citation,
  584:        $baseurl, $attachmenturl, $toperm, $sentmessage, $symb, $restitle, $error)>:
  585:  Sends a message to the  $user at $domain, with subject $subject and message $message.
  586: 
  587: =cut
  588: 
  589: sub user_normal_msg {
  590:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
  591: 	$toperm,$sentmessage,$symb,$restitle,$error)=@_;
  592:     my $status='';
  593:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
  594:                                        $domain,$user);
  595:     my $msgforward=$userenv{'msgforward'};
  596:     if ($msgforward) {
  597:         foreach (split(/\,/,$msgforward)) {
  598: 	    my ($forwuser,$forwdomain)=split(/\:/,$_);
  599: 	    $status.=
  600: 	        &user_normal_msg_raw($forwuser,$forwdomain,$subject,$message,
  601: 				     $citation,$baseurl,$attachmenturl,$toperm,
  602: 				     undef,undef,$sentmessage,undef,$symb,$restitle,$error).' ';
  603:         }
  604:     } else {
  605: 	$status=&user_normal_msg_raw($user,$domain,$subject,$message,
  606: 				     $citation,$baseurl,$attachmenturl,$toperm,
  607: 				     undef,undef,$sentmessage,undef,$symb,$restitle,$error);
  608:     }
  609:     return $status;
  610: }
  611: 
  612: sub store_sent_mail {
  613:     my ($msgid,$message) = @_;
  614:     my $status =' '.&Apache::lonnet::critical(
  615:                'put:'.$env{'user.domain'}.':'.$env{'user.name'}.
  616:                                           ':nohist_email_sent:'.
  617:                &escape($msgid).'='.
  618:                &escape($message),$env{'user.home'});
  619:     return $status;
  620: }
  621: 
  622: # =============================================================== Folder suffix
  623: 
  624: sub foldersuffix {
  625:     my $folder=shift;
  626:     unless ($folder) { return ''; }
  627:     my $suffix;
  628:     my %folderhash = &get_user_folders($folder);
  629:     if (ref($folderhash{$folder}) eq 'HASH') {
  630:         $suffix = '_'.&escape($folderhash{$folder}{'id'});
  631:     } else {
  632:         $suffix = '_'.&escape($folder);
  633:     }
  634:     return $suffix;
  635: }
  636: 
  637: # ========================================================= User-defined folders 
  638: 
  639: sub get_user_folders {
  640:     my ($folder) = @_;
  641:     my %userfolders = 
  642:           &Apache::lonnet::dump('email_folders',undef,undef,$folder);
  643:     my $lock = "\0".'lock_counter'; # locks db while counter incremented
  644:     my $counter = "\0".'idcount';   # used in suffix for email db files
  645:     if (defined($userfolders{$lock})) {
  646:         delete($userfolders{$lock});
  647:     }
  648:     if (defined($userfolders{$counter})) {
  649:         delete($userfolders{$counter});
  650:     }
  651:     return %userfolders;
  652: }
  653: 
  654: 1;
  655: __END__
  656: 

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