File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.204: download - view: text, annotated - select for diffs
Sat May 5 03:14:21 2007 UTC (17 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
bug 5168.
- users with srm priv can designate a reply-to address (which may not be the same as the sender's) for messages
- users with srm priv can specify that a specific message should be eligible fo replies.
- some modification of button display for critical messages for consistency with this.
- Reply link elininated in essage display functions if message is not allowed relies
- Critical message receipts go to reply to address (if different from original sender).

    1: # The LearningOnline Network with CAPA
    2: # Routines for messaging
    3: #
    4: # $Id: lonmsg.pm,v 1.204 2007/05/05 03:14:21 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::lonmsg;
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: Apache::lonmsg: supports internal messaging
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: lonmsg provides routines for sending messages.
   40: 
   41: Right now, this document will cover just how to send a message, since
   42: it is likely you will not need to programmatically read messages,
   43: since lonmsg already implements that functionality.
   44: 
   45: The routines used to package messages and unpackage messages are not
   46: only used by lonmsg when creating/extracting messages for LON-CAPA's
   47: internal messaging system, but also by lonnotify.pm which is available
   48: for use by Domain Coordinators to broadcast standard e-mail to specified
   49: users in their domain.  The XML packaging used in the two cases is very
   50: similar.  The differences are the use of <recuser>$uname</recuser> and
   51: <recdomain>$udom</recdomain> in stored internal messages, compared
   52: with <recipient username="$uname:$udom">$email</recipient> in stored
   53: Domain Coordinator e-mail for the storage of information about
   54: recipients of the message/e-mail.
   55: 
   56: =head1 FUNCTIONS
   57: 
   58: =over 4
   59: 
   60: =cut
   61: 
   62: use strict;
   63: use Apache::lonnet;
   64: use HTML::TokeParser();
   65: use Apache::lonlocal;
   66: use Mail::Send;
   67: use LONCAPA qw(:DEFAULT :match);
   68: 
   69: {
   70:     my $uniq;
   71:     sub get_uniq {
   72: 	$uniq++;
   73: 	return $uniq;
   74:     }
   75: }
   76: 
   77: # ===================================================================== Package
   78: 
   79: sub packagemsg {
   80:     my ($subject,$message,$citation,$baseurl,$attachmenturl,
   81: 	$recuser,$recdomain,$msgid,$type,$crsmsgid,$symb,$error,$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:     $text=~s/\&lt\;/\</gs;
  306:     $text=~s/\&gt\;/\>/gs;
  307:     $text=~s/\<\/*[^\>]+\>//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;
  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 $body = $coursetext. 
  327:                &mt('You received a'.$critical.' message from [_1] in LON-CAPA.',$sender).' '.&mt('The subject is 
  328: 
  329:  [_1]
  330: 
  331: ',$subj)."\n".
  332: '=== '.&mt('Excerpt')." ============================================================
  333: $text
  334: ========================================================================
  335: 
  336: ".&mt('Use 
  337: 
  338:  [_1]
  339: 
  340: to access the full message.',$url);
  341:     &sendemail($to,'New'.$critical.' message from '.$sender,$body);
  342: }
  343: # ============================================================= Check for email
  344: 
  345: sub newmail {
  346:     if ((time-$env{'user.mailcheck.time'})>300) {
  347:         my %what=&Apache::lonnet::get('email_status',['recnewemail']);
  348:         &Apache::lonnet::appenv('user.mailcheck.time'=>time);
  349:         if ($what{'recnewemail'}>0) { return 1; }
  350:     }
  351:     return 0;
  352: }
  353: 
  354: # =============================== Automated message to the author of a resource
  355: 
  356: =pod
  357: 
  358: =item * B<author_res_msg($filename, $message)>: Sends message $message to the owner
  359:     of the resource with the URI $filename.
  360: 
  361: =cut
  362: 
  363: sub author_res_msg {
  364:     my ($filename,$message)=@_;
  365:     unless ($message) { return 'empty'; }
  366:     $filename=&Apache::lonnet::declutter($filename);
  367:     my ($domain,$author,@dummy)=split(/\//,$filename);
  368:     my $homeserver=&Apache::lonnet::homeserver($author,$domain);
  369:     if ($homeserver ne 'no_host') {
  370:        my $id=unpack("%32C*",$message);
  371:        $message .= " <p>This error occurred on machine ".
  372: 	   $Apache::lonnet::perlvar{'lonHostID'}."</p>";
  373:        my $msgid;
  374:        ($msgid,$message)=&packagemsg($filename,$message);
  375:        return &Apache::lonnet::reply('put:'.$domain.':'.$author.
  376:          ':nohist_res_msgs:'.
  377:           &escape($filename.'_'.$id).'='.
  378:           &escape($message),$homeserver);
  379:     }
  380:     return 'no_host';
  381: }
  382: 
  383: # =========================================== Retrieve author resource messages
  384: 
  385: sub retrieve_author_res_msg {
  386:     my $url=shift;
  387:     $url=&Apache::lonnet::declutter($url);
  388:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
  389:     my %errormsgs=&Apache::lonnet::dump('nohist_res_msgs',$domain,$author);
  390:     my $msgs='';
  391:     foreach (keys %errormsgs) {
  392: 	if ($_=~/^\Q$url\E\_\d+$/) {
  393: 	    my %content=&unpackagemsg($errormsgs{$_});
  394: 	    $msgs.='<p><img src="/adm/lonMisc/bomb.gif" /><b>'.
  395: 		$content{'time'}.'</b>: '.$content{'message'}.
  396: 		'<br /></p>';
  397: 	}
  398:     } 
  399:     return $msgs;     
  400: }
  401: 
  402: 
  403: # =============================== Delete all author messages related to one URL
  404: 
  405: sub del_url_author_res_msg {
  406:     my $url=shift;
  407:     $url=&Apache::lonnet::declutter($url);
  408:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
  409:     my @delmsgs=();
  410:     foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
  411: 	if ($_=~/^\Q$url\E\_\d+$/) {
  412: 	    push (@delmsgs,$_);
  413: 	}
  414:     }
  415:     return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
  416: }
  417: # =================================== Clear out all author messages in URL path
  418: 
  419: sub clear_author_res_msg {
  420:     my $url=shift;
  421:     $url=&Apache::lonnet::declutter($url);
  422:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
  423:     my @delmsgs=();
  424:     foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
  425: 	if ($_=~/^\Q$url\E/) {
  426: 	    push (@delmsgs,$_);
  427: 	}
  428:     }
  429:     return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
  430: }
  431: # ================= Return hash with URLs for which there is a resource message
  432: 
  433: sub all_url_author_res_msg {
  434:     my ($author,$domain)=@_;
  435:     my %returnhash=();
  436:     foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
  437: 	$_=~/^(.+)\_\d+/;
  438: 	$returnhash{$1}=1;
  439:     }
  440:     return %returnhash;
  441: }
  442: 
  443: # ====================================== Add a comment to the User Notes screen
  444: 
  445: sub store_instructor_comment {
  446:     my ($msg,$uname,$udom) = @_;
  447:     my $cid  = $env{'request.course.id'};
  448:     my $cnum = $env{'course.'.$cid.'.num'};
  449:     my $cdom = $env{'course.'.$cid.'.domain'};
  450:     my $subject= &mt('Record').' ['.$uname.':'.$udom.']';
  451:     my $result = &user_normal_msg_raw($cnum,$cdom,$subject,$msg);
  452:     if ($result eq 'ok' || $result eq 'con_delayed') {
  453:         
  454:     }
  455:     return $result;
  456: }
  457: 
  458: # ================================================== Critical message to a user
  459: 
  460: sub user_crit_msg_raw {
  461:     my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage,
  462:         $nosentstore,$recipid)=@_;
  463: # Check if allowed missing
  464:     my ($status,$packed_message);
  465:     my $msgid='undefined';
  466:     unless (($message)&&($user)&&($domain)) { $status='empty'; };
  467:     my $text=$message;
  468:     my $homeserver=&Apache::lonnet::homeserver($user,$domain);
  469:     if ($homeserver ne 'no_host') {
  470:        ($msgid,$packed_message)=&packagemsg($subject,$message,undef,undef,
  471:                                   undef,undef,undef,undef,undef,undef,undef,
  472:                                   undef,$recipid);
  473:        if ($sendback) { $packed_message.='<sendback>true</sendback>'; }
  474:        $status=&Apache::lonnet::critical(
  475:            'put:'.$domain.':'.$user.':critical:'.
  476:            &escape($msgid).'='.
  477:            &escape($packed_message),$homeserver);
  478:         if (defined($sentmessage)) {
  479:             $$sentmessage = $packed_message;
  480:         }
  481:         if (!$nosentstore) {
  482:             (undef,my $packed_message_no_citation) =
  483:             &packagemsg($subject,$message,undef,undef,undef,$user,$domain,
  484:                         $msgid);
  485:             if ($status eq 'ok' || $status eq 'con_delayed') {
  486:                 &store_sent_mail($msgid,$packed_message_no_citation);
  487:             }
  488:         }
  489:     } else {
  490:        $status='no_host';
  491:     }
  492: 
  493: # Notifications
  494:     my %userenv = &Apache::loncommon::getemails($user,$domain);
  495:     if ($userenv{'critnotification'}) {
  496:       &sendnotification($userenv{'critnotification'},$user,$domain,$subject,1,
  497: 			$text,$msgid);
  498:     }
  499:     if ($toperm && $userenv{'permanentemail'}) {
  500:       &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,1,
  501: 			$text,$msgid);
  502:     }
  503: # Log this
  504:     &Apache::lonnet::logthis(
  505:       'Sending critical email '.$msgid.
  506:       ', log status: '.
  507:       &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  508:                          $env{'user.home'},
  509:       'Sending critical '.$msgid.' to '.$user.' at '.$domain.' with status: '
  510:       .$status));
  511:     return $status;
  512: }
  513: 
  514: # New routine that respects "forward" and calls old routine
  515: 
  516: =pod
  517: 
  518: =item * B<user_crit_msg($user, $domain, $subject, $message, $sendback, $nosentstore,$recipid)>: 
  519:     Sends a critical message $message to the $user at $domain.  If $sendback
  520:     is true,  a receipt will be sent to the current user when $user receives 
  521:     the message.
  522: 
  523:     Additionally it will check if the user has a Forwarding address
  524:     set, and send the message to that address instead
  525: 
  526:     returns 
  527:       - in array context a list of results for each message that was sent
  528:       - in scalar context a space seperated list of results for each 
  529:            message sent
  530: 
  531: =cut
  532: 
  533: sub user_crit_msg {
  534:     my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage,
  535:         $nosentstore,$recipid)=@_;
  536:     my @status;
  537:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
  538:                                        $domain,$user);
  539:     my $msgforward=$userenv{'msgforward'};
  540:     if ($msgforward) {
  541:        foreach my $addr (split(/\,/,$msgforward)) {
  542: 	 my ($forwuser,$forwdomain)=split(/\:/,$addr);
  543:          push(@status,
  544: 	      &user_crit_msg_raw($forwuser,$forwdomain,$subject,$message,
  545: 				 $sendback,$toperm,$sentmessage,$nosentstore,
  546:                                  $recipid));
  547:        }
  548:     } else { 
  549: 	push(@status,
  550: 	     &user_crit_msg_raw($user,$domain,$subject,$message,$sendback,
  551: 				$toperm,$sentmessage,$nosentstore,$recipid));
  552:     }
  553:     if (wantarray) {
  554: 	return @status;
  555:     }
  556:     return join(' ',@status);
  557: }
  558: 
  559: # =================================================== Critical message received
  560: 
  561: sub user_crit_received {
  562:     my $msgid=shift;
  563:     my %message=&Apache::lonnet::get('critical',[$msgid]);
  564:     my %contents=&unpackagemsg($message{$msgid},1);
  565:     my $destname = $contents{'sendername'};
  566:     my $destdom = $contents{'senderdomain'};
  567:     if ($contents{'replytoaddr'}) {
  568:         my ($repname,$repdom) = split(/:/,$contents{'replytoaddr'});
  569:         if (&Apache::lonnet::homeserver($repname,$repdom) ne 'no_host') {
  570:             $destname = $repname;
  571:             $destdom = $repdom;    
  572:         }
  573:     }
  574:     my $status='rec: '.($contents{'sendback'}?
  575:      &user_normal_msg($destname,$destdom,&mt('Receipt').': '.$env{'user.name'}.
  576:                       ' '.&mt('at').' '.$env{'user.domain'}.', '.
  577:                       $contents{'subject'},&mt('User').' '.$env{'user.name'}.
  578:                       ' '.&mt('at').' '.$env{'user.domain'}.
  579:                       ' acknowledged receipt of message'."\n".'   "'.
  580:                       $contents{'subject'}.'"'."\n".&mt('dated').' '.
  581:                       $contents{'time'}.".\n"
  582:                       ):'no msg req');
  583:     $status.=' trans: '.
  584:      &Apache::lonnet::put(
  585:      'nohist_email',{$contents{'msgid'} => $message{$msgid}});
  586:     $status.=' del: '.
  587:      &Apache::lonnet::del('critical',[$contents{'msgid'}]);
  588:     &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  589:                          $env{'user.home'},'Received critical message '.
  590:                          $contents{'msgid'}.
  591:                          ', '.$status);
  592:     return $status;
  593: }
  594: 
  595: # ======================================================== Normal communication
  596: 
  597: sub user_normal_msg_raw {
  598:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
  599:         $toperm,$currid,$newid,$sentmessage,$crsmsgid,$symb,$restitle,
  600:         $error,$nosentstore,$recipid)=@_;
  601: # Check if allowed missing
  602:     my ($status,$packed_message);
  603:     my $msgid='undefined';
  604:     my $text=$message;
  605:     unless (($message)&&($user)&&($domain)) { $status='empty'; };
  606:     my $homeserver=&Apache::lonnet::homeserver($user,$domain);
  607:     if ($homeserver ne 'no_host') {
  608:        ($msgid,$packed_message)=
  609: 	                 &packagemsg($subject,$message,$citation,$baseurl,
  610:                                      $attachmenturl,$user,$domain,$currid,
  611:                                      undef,$crsmsgid,$symb,$error,$recipid);
  612: 
  613: # Store in user folder
  614:        $status=&Apache::lonnet::critical(
  615:            'put:'.$domain.':'.$user.':nohist_email:'.
  616:            &escape($msgid).'='.
  617:            &escape($packed_message),$homeserver);
  618: # Save new message received time
  619:        &Apache::lonnet::put
  620:                          ('email_status',{'recnewemail'=>time},$domain,$user);
  621: # Into sent-mail folder if sent mail storage required
  622:        if (!$nosentstore) {
  623:            (undef,my $packed_message_no_citation) =
  624:                &packagemsg($subject,$message,undef,$baseurl,$attachmenturl,
  625:                            $user,$domain,$currid,undef,$crsmsgid,$symb,$error);
  626:            if ($status eq 'ok' || $status eq 'con_delayed') {
  627:                &store_sent_mail($msgid,$packed_message_no_citation);
  628:            }
  629:        }
  630:        if (ref($newid) eq 'SCALAR') {
  631: 	   $$newid = $msgid;
  632:        }
  633:        if (ref($sentmessage) eq 'SCALAR') {
  634: 	   $$sentmessage = $packed_message;
  635:        }
  636: # Notifications
  637:        my %userenv = &Apache::lonnet::get('environment',['notification',
  638: 							 'permanentemail'],
  639: 					  $domain,$user);
  640:        if ($userenv{'notification'}) {
  641: 	   &sendnotification($userenv{'notification'},$user,$domain,$subject,0,
  642: 			     $text,$msgid);
  643:        }
  644:        if ($toperm && $userenv{'permanentemail'}) {
  645: 	   &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,0,
  646: 			     $text,$msgid);
  647:        }
  648:        &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
  649: 			    $env{'user.home'},
  650: 			    'Sending '.$msgid.' to '.$user.' at '.$domain.' with status: '.$status);
  651:    } else {
  652:        $status='no_host';
  653:    }
  654:     return $status;
  655: }
  656: 
  657: # New routine that respects "forward" and calls old routine
  658: 
  659: =pod
  660: 
  661: =item * B<user_normal_msg($user, $domain, $subject, $message, $citation,
  662:        $baseurl, $attachmenturl, $toperm, $sentmessage, $symb, $restitle,
  663:        $error,$nosentstore,$recipid)>:
  664:  Sends a message to the  $user at $domain, with subject $subject and message $message.
  665: 
  666:     Additionally it will check if the user has a Forwarding address
  667:     set, and send the message to that address instead
  668: 
  669:     returns
  670:       - in array context a list of results for each message that was sent
  671:       - in scalar context a space seperated list of results for each
  672:            message sent
  673: 
  674: =cut
  675: 
  676: sub user_normal_msg {
  677:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
  678: 	$toperm,$sentmessage,$symb,$restitle,$error,$nosentstore,$recipid)=@_;
  679:     my @status;
  680:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
  681:                                        $domain,$user);
  682:     my $msgforward=$userenv{'msgforward'};
  683:     if ($msgforward) {
  684:         foreach (split(/\,/,$msgforward)) {
  685: 	    my ($forwuser,$forwdomain)=split(/\:/,$_);
  686: 	    push(@status,
  687: 	        &user_normal_msg_raw($forwuser,$forwdomain,$subject,$message,
  688: 				     $citation,$baseurl,$attachmenturl,$toperm,
  689: 				     undef,undef,$sentmessage,undef,$symb,
  690:                                      $restitle,$error,$nosentstore,$recipid));
  691:         }
  692:     } else {
  693: 	push(@status,&user_normal_msg_raw($user,$domain,$subject,$message,
  694: 				     $citation,$baseurl,$attachmenturl,$toperm,
  695: 				     undef,undef,$sentmessage,undef,$symb,
  696:                                      $restitle,$error,$nosentstore,$recipid));
  697:     }
  698:     if (wantarray) {
  699:         return @status;
  700:     }
  701:     return join(' ',@status);
  702: }
  703: 
  704: sub process_sent_mail {
  705:     my ($msgsubj,$subj_prefix,$numsent,$stamp,$msgname,$msgdom,$msgcount,$context,$pid,$savemsg,$recusers,$recudoms,$baseurl,$attachmenturl,$symb,$error,$senderuname,$senderdom,$senderhome) = @_;
  706:     my $sentsubj;
  707:     if ($numsent > 1) {
  708:         $sentsubj = $subj_prefix.' ('.$numsent.' sent) '.$msgsubj;
  709:     }
  710:     $sentsubj = &HTML::Entities::encode($sentsubj,'<>&"');
  711:     my $sentmsgid = 
  712:         &buildmsgid($stamp,$sentsubj,$msgname,$msgdom,$msgcount,$context,$pid);
  713:     (undef,my $sentmessage) =
  714:         &packagemsg($msgsubj,$savemsg,undef,$baseurl,$attachmenturl,$recusers,
  715:                     $recudoms,$sentmsgid,undef,undef,$symb,$error);
  716:     my $status = &store_sent_mail($sentmsgid,$sentmessage,$senderuname,
  717:                                   $senderdom,$senderhome);
  718:     return $status;
  719: }
  720: 
  721: sub store_sent_mail {
  722:     my ($msgid,$message,$senderuname,$senderdom,$senderhome) = @_;
  723:     if ($senderuname eq '') {
  724:         $senderuname = $env{'user.name'};
  725:     }
  726:     if ($senderdom eq '') {
  727:         $senderdom = $env{'user.domain'};
  728:     }
  729:     if ($senderhome eq '') {
  730:         $senderhome = $env{'user.home'};
  731:     }
  732:     my $status =' '.&Apache::lonnet::critical(
  733:                'put:'.$senderdom.':'.$senderuname.':nohist_email_sent:'.
  734:                &escape($msgid).'='.&escape($message),$senderhome);
  735:     return $status;
  736: }
  737: 
  738: sub store_recipients {
  739:     my ($subject,$sendername,$senderdom,$reciphash) = @_;
  740:     my $context = &get_course_context();
  741:     my $now = time();
  742:     my $msgcount = &get_uniq();
  743:     my $recipid =
  744:         &buildmsgid($now,$subject,$sendername,$senderdom,$msgcount,$context,$$);
  745:     my %recipinfo = (
  746:                          $recipid => $reciphash,
  747:                     );
  748:     my $status = &Apache::lonnet::put('nohist_emailrecip',\%recipinfo,
  749:                                       $senderdom,$sendername); 
  750:     if ($status eq 'ok') {
  751:         return ($recipid,$status);
  752:     } else {
  753:         return (undef,$status);
  754:     }
  755: }
  756: 
  757: # =============================================================== Folder suffix
  758: 
  759: sub foldersuffix {
  760:     my $folder=shift;
  761:     unless ($folder) { return ''; }
  762:     my $suffix;
  763:     my %folderhash = &get_user_folders($folder);
  764:     if (ref($folderhash{$folder}) eq 'HASH') {
  765:         $suffix = '_'.&escape($folderhash{$folder}{'id'});
  766:     } else {
  767:         $suffix = '_'.&escape($folder);
  768:     }
  769:     return $suffix;
  770: }
  771: 
  772: # ========================================================= User-defined folders 
  773: 
  774: sub get_user_folders {
  775:     my ($folder) = @_;
  776:     my %userfolders = 
  777:           &Apache::lonnet::dump('email_folders',undef,undef,$folder);
  778:     my $lock = "\0".'lock_counter'; # locks db while counter incremented
  779:     my $counter = "\0".'idcount';   # used in suffix for email db files
  780:     if (defined($userfolders{$lock})) {
  781:         delete($userfolders{$lock});
  782:     }
  783:     if (defined($userfolders{$counter})) {
  784:         delete($userfolders{$counter});
  785:     }
  786:     return %userfolders;
  787: }
  788: 
  789: sub secapply {
  790:     my $rec=shift;
  791:     my $defaultflag=shift;
  792:     $rec=~s/\s+//g;
  793:     $rec=~s/\@/\:/g;
  794:     my ($adr,$sections_or_groups)=($rec=~/^([^\(]+)\(([^\)]+)\)/);
  795:     if ($sections_or_groups) {
  796: 	foreach my $item (split(/\;/,$sections_or_groups)) {
  797:             if (($item eq $env{'request.course.sec'}) ||
  798:                 ($defaultflag && ($item eq '*'))) {
  799:                 return $adr; 
  800:             } elsif ($env{'request.course.groups'}) {
  801:                 my @usersgroups = split(/:/,$env{'request.course.groups'});
  802:                 if (grep(/^\Q$item\E$/,@usersgroups)) {
  803:                     return $adr;
  804:                 }
  805:             } 
  806:         }
  807:     } else {
  808:        return $rec;
  809:     }
  810:     return '';
  811: }
  812: 
  813: =pod 
  814: 
  815: =item * B<decide_receiver($feedurl,$author,$question,$course,$policy,$defaultflag)>:
  816: 
  817: Arguments
  818:   $feedurl - /res/ url of resource (only need if $author is true)
  819:   $author,$question,$course,$policy - all true/false parameters
  820:     if true will attempt to find the addresses of user that should receive
  821:     this type of feedback (author - feedback to author of resource $feedurl,
  822:     $question 'Resource Content Questions', $course 'Course Content Question',
  823:     $policy 'Course Policy')
  824:     (Additionally it also checks $env for whether the corresponding form.<name>
  825:     element exists, for ease of use in a html response context)
  826:    
  827:   $defaultflag - (internal should be left blank) if true gather addresses 
  828:                  that aren't for a section even if I have a section
  829:                  (used for reccursion internally, first we look for
  830:                  addresses for our specific section then we recurse
  831:                  and look for non section addresses)
  832: 
  833: Returns
  834:   $typestyle - string of html text, describing what addresses were found
  835:   %to - a hash, which keys are addresses of users to send messages to
  836:         the keys will look like   name:domain
  837: 
  838: =cut
  839: 
  840: sub decide_receiver {
  841:     my ($feedurl,$author,$question,$course,$policy,$defaultflag) = @_;
  842:     &Apache::lonenc::check_decrypt(\$feedurl);
  843:     my $typestyle='';
  844:     my %to=();
  845:     if ($env{'form.discuss'} eq 'author' ||$author) {
  846: 	$typestyle.='Submitting as Author Feedback<br />';
  847: 	$feedurl=~ m{^/res/($LONCAPA::domain_re)/($LONCAPA::username_re)/};
  848: 	$to{$2.':'.$1}=1;
  849:     }
  850:     my $cid = $env{'request.course.id'};
  851:     if ($env{'form.discuss'} eq 'question' ||$question) {
  852: 	$typestyle.=&mt('Submitting as Question').'<br />';
  853: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.question.email'})) {
  854: 	    my $rec=&secapply($item,$defaultflag);
  855: 	    if ($rec) { $to{$rec}=1; }
  856: 	} 
  857:     }
  858:     if ($env{'form.discuss'} eq 'course' ||$course) {
  859: 	$typestyle.=&mt('Submitting as Comment').'<br />';
  860: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.comment.email'})) {
  861: 	    my $rec=&secapply($item,$defaultflag);
  862: 	    if ($rec) { $to{$rec}=1; }
  863: 	} 
  864:     }
  865:     if ($env{'form.discuss'} eq 'policy' ||$policy) {
  866: 	$typestyle.=&mt('Submitting as Policy Feedback').'<br />';
  867: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.policy.email'})) {
  868: 	    my $rec=&secapply($item,$defaultflag);
  869: 	    if ($rec) { $to{$rec}=1; }
  870: 	} 
  871:     }
  872:     if ((scalar(%to) eq '0') && (!$defaultflag)) {
  873: 	($typestyle,%to)=
  874: 	    &decide_receiver($feedurl,$author,$question,$course,$policy,1);
  875:     }
  876:     return ($typestyle,%to);
  877: }
  878: 
  879: =pod
  880: 
  881: =back
  882: 
  883: =cut
  884: 
  885: 1;
  886: __END__
  887: 

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