File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.214.2.4: download - view: text, annotated - select for diffs
Sun Jan 4 16:21:10 2009 UTC (15 years, 4 months ago) by raeburn
Branches: version_2_8_X
- Backport 1.220.

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

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