File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.213: download - view: text, annotated - select for diffs
Sat Sep 13 02:37:26 2008 UTC (15 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 5786. Language used for text wrapped around body of message in notification e-mail should correspond to language preference of recipient determined in order: user pref, domain default), unless message is sent in course content, and a language is defined for course (use course langage in this case).
lonmsg.pm - &user_lang() used to get a language hadler for recipient.
          - Translation of text uses &mt_user() instead of &mt().

lonlocal.pm - &mt_user() added (exported). Calls maketext, but takes language handler as firrst arg.

loncommon.pm - &get_genlanguages() added - functionality to turn en-ca into en-ca,en and also to remove duplicates from @preferred_languages - moved from &preferred_languages() to a separate subroutine so it is more widely available.

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

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