File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.214.2.3: download - view: text, annotated - select for diffs
Tue Dec 23 19:27:33 2008 UTC (15 years, 6 months ago) by raeburn
Branches: version_2_8_X
CVS tags: version_2_7_99_0
- Backport 1.219.

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

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