File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.224: download - view: text, annotated - select for diffs
Tue Mar 31 21:04:12 2009 UTC (15 years, 2 months ago) by kaisler
Branches: MAIN
CVS tags: version_2_9_99_0, version_2_8_99_0, bz6209-base, bz6209, bz5969, bz2851, HEAD, GCI_3, GCI_2, BZ5971-printing-apage, BZ5434-fox
Update the display for new Messages in the toplevelmenu, if you go on the message site the display in the toplevelmenu now is cleard

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

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