Annotation of loncom/interface/lonmsg.pm, revision 1.249

1.1       www         1: # The LearningOnline Network with CAPA
1.26      albertel    2: # Routines for messaging
                      3: #
1.249   ! raeburn     4: # $Id: lonmsg.pm,v 1.248 2022/01/18 17:33:13 raeburn Exp $
1.26      albertel    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/
1.1       www        27: #
1.75      www        28: 
1.1       www        29: package Apache::lonmsg;
                     30: 
1.199     raeburn    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: 
1.215     jms        56: =head1 SUBROUTINES
1.199     raeburn    57: 
1.215     jms        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: 
1.248     raeburn   123: =item * B<user_crit_msg($user, $domain, $subject, $message, $sendback, $toperm, $sentmessage, $nosentstore, $recipid, $attachmenturl, $permresults, $senthide)>: 
1.215     jms       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,
1.248     raeburn   151:        $error,$nosentstore,$recipid,$permresults,$senthide)>:
1.215     jms       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
1.199     raeburn   198: 
                    199: =cut
                    200: 
1.1       www       201: use strict;
1.140     albertel  202: use Apache::lonnet;
1.242     musolffc  203: use Apache::loncommon;
1.47      albertel  204: use HTML::TokeParser();
1.180     albertel  205: use Apache::lonlocal;
1.226     raeburn   206: use HTML::Entities;
                    207: use Encode;
1.187     albertel  208: use LONCAPA qw(:DEFAULT :match);
1.180     albertel  209: 
                    210: {
                    211:     my $uniq;
                    212:     sub get_uniq {
                    213: 	$uniq++;
                    214: 	return $uniq;
                    215:     }
                    216: }
1.65      www       217: 
1.215     jms       218: 
1.1       www       219: 
1.3       www       220: sub packagemsg {
1.248     raeburn   221:     my ($subject,$message,$citation,$baseurl,$attachmenturl,$recuser,$recdomain,
                    222: 	$msgid,$type,$crsmsgid,$symb,$error,$recipid,$senthide,$origmsgid)=@_;
1.96      albertel  223:     $message =&HTML::Entities::encode($message,'<>&"');
                    224:     $citation=&HTML::Entities::encode($citation,'<>&"');
                    225:     $subject =&HTML::Entities::encode($subject,'<>&"');
1.49      albertel  226:     #remove machine specification
1.218     raeburn   227:     $baseurl =~ s|^https?://[^/]+/|/|;
1.96      albertel  228:     $baseurl =&HTML::Entities::encode($baseurl,'<>&"');
1.51      www       229:     #remove machine specification
1.218     raeburn   230:     $attachmenturl =~ s|^https?://[^/]+/|/|;
1.96      albertel  231:     $attachmenturl =&HTML::Entities::encode($attachmenturl,'<>&"');
1.248     raeburn   232:     if ($senthide) {
                    233:         foreach my $item ($subject,$message) {
                    234:             if ($item ne '') {
                    235:                 $item = 'Not shown due to IP block';
                    236:             }
                    237:         }
                    238:         if ($attachmenturl ne '') {
                    239:             $attachmenturl = '';
                    240:         }
                    241:         if ($citation ne '') {
                    242:             $citation = '';
                    243:         }
                    244:         if ($msgid ne '') {
                    245:             $msgid = '';
                    246:         }
                    247:     }
1.201     raeburn   248:     my $course_context = &get_course_context();
1.2       www       249:     my $now=time;
1.246     raeburn   250:     my $ip = &Apache::lonnet::get_requestor_ip();
1.180     albertel  251:     my $msgcount = &get_uniq();
1.156     raeburn   252:     unless(defined($msgid)) {
1.159     raeburn   253:         $msgid = &buildmsgid($now,$subject,$env{'user.name'},$env{'user.domain'},
1.191     raeburn   254:                            $msgcount,$course_context,$symb,$error,$$);
1.156     raeburn   255:     }
1.174     raeburn   256:     my $result = '<sendername>'.$env{'user.name'}.'</sendername>'.
1.140     albertel  257:            '<senderdomain>'.$env{'user.domain'}.'</senderdomain>'.
1.1       www       258:            '<subject>'.$subject.'</subject>'.
1.174     raeburn   259:            '<time>'.&Apache::lonlocal::locallocaltime($now).'</time>';
                    260:     if (defined($crsmsgid)) {
                    261:         $result.= '<courseid>'.$course_context.'</courseid>'.
                    262:                   '<coursesec>'.$env{'request.course.sec'}.'</coursesec>'.
                    263:                   '<msgid>'.$msgid.'</msgid>'.
                    264:                   '<coursemsgid>'.$crsmsgid.'</coursemsgid>'.
                    265:                   '<message>'.$message.'</message>';
                    266:         return ($msgid,$result);
                    267:     }
                    268:     $result .= '<servername>'.$ENV{'SERVER_NAME'}.'</servername>'.
1.1       www       269:            '<host>'.$ENV{'HTTP_HOST'}.'</host>'.
1.246     raeburn   270: 	   '<client>'.$ip.'</client>'.
1.140     albertel  271: 	   '<browsertype>'.$env{'browser.type'}.'</browsertype>'.
                    272: 	   '<browseros>'.$env{'browser.os'}.'</browseros>'.
                    273: 	   '<browserversion>'.$env{'browser.version'}.'</browserversion>'.
                    274:            '<browsermathml>'.$env{'browser.mathml'}.'</browsermathml>'.
1.1       www       275: 	   '<browserraw>'.$ENV{'HTTP_USER_AGENT'}.'</browserraw>'.
1.158     raeburn   276: 	   '<courseid>'.$course_context.'</courseid>'.
1.140     albertel  277: 	   '<coursesec>'.$env{'request.course.sec'}.'</coursesec>'.
                    278: 	   '<role>'.$env{'request.role'}.'</role>'.
                    279: 	   '<resource>'.$env{'request.filename'}.'</resource>'.
1.156     raeburn   280:            '<msgid>'.$msgid.'</msgid>';
1.214     raeburn   281:     if (defined($env{'form.group'})) {
                    282:         $result .= '<group>'.$env{'form.group'}.'</group>';
                    283:     }
1.156     raeburn   284:     if (ref($recuser) eq 'ARRAY') {
                    285:         for (my $i=0; $i<@{$recuser}; $i++) {
1.162     raeburn   286:             if ($type eq 'dcmail') {
                    287:                 my ($username,$email) = split(/:/,$$recuser[$i]);
1.184     www       288:                 $username = &unescape($username);
                    289:                 $email = &unescape($email);
1.162     raeburn   290:                 $username = &HTML::Entities::encode($username,'<>&"');
                    291:                 $email = &HTML::Entities::encode($email,'<>&"');
                    292:                 $result .= '<recipient username="'.$username.'">'.
                    293:                                             $email.'</recipient>';
                    294:             } else {
                    295:                 $result .= '<recuser>'.$$recuser[$i].'</recuser>'.
                    296:                            '<recdomain>'.$$recdomain[$i].'</recdomain>';
                    297:             }
1.156     raeburn   298:         }
                    299:     } else {
                    300:         $result .= '<recuser>'.$recuser.'</recuser>'.
                    301:                    '<recdomain>'.$recdomain.'</recdomain>';
                    302:     }
                    303:     $result .= '<message>'.$message.'</message>';
1.49      albertel  304:     if (defined($citation)) {
                    305: 	$result.='<citation>'.$citation.'</citation>';
                    306:     }
                    307:     if (defined($baseurl)) {
                    308: 	$result.= '<baseurl>'.$baseurl.'</baseurl>';
                    309:     }
1.51      www       310:     if (defined($attachmenturl)) {
1.52      www       311: 	$result.= '<attachmenturl>'.$attachmenturl.'</attachmenturl>';
1.51      www       312:     }
1.191     raeburn   313:     if (defined($symb)) {
                    314:         $result.= '<symb>'.$symb.'</symb>';
1.201     raeburn   315:         if ($course_context ne '') {
1.191     raeburn   316:             if ($course_context eq $env{'request.course.id'}) {
                    317:                 my $resource_title = &Apache::lonnet::gettitle($symb);
                    318:                 if (defined($resource_title)) {
                    319:                     $result .= '<resource_title>'.$resource_title.'</resource_title>';
                    320:                 }
                    321:             }
                    322:         }
                    323:     }
1.202     raeburn   324:     if (defined($recipid)) {
                    325:         $result.= '<recipid>'.$recipid.'</recipid>';
                    326:     }
1.204     raeburn   327:     if ($env{'form.can_reply'} eq 'N') {
                    328:         $result .= '<noreplies>1</noreplies>';
                    329:     }
                    330:     if ($env{'form.reply_to_addr'}) {
                    331:         my ($replytoname,$replytodom) = split(/:/,$env{'form.reply_to_addr'});
                    332:         if (!($replytoname eq $env{'user.name'} && $replytodom eq $env{'user.domain'})) {
                    333:             if (&Apache::lonnet::homeserver($replytoname,$replytodom) ne 'no_host') {
                    334:                 $result .= '<replytoaddr>'.$env{'form.reply_to_addr'}.'</replytoaddr>';
                    335:             }
                    336:         }
                    337:     }
1.248     raeburn   338:     if ($senthide) {
                    339:         $result .= '<senthide>$origmsgid</senthide>';
                    340:     }
1.191     raeburn   341:     return ($msgid,$result);
1.1       www       342: }
                    343: 
1.201     raeburn   344: sub get_course_context {
                    345:     my $course_context;
1.212     raeburn   346:     my $msgkey;
1.201     raeburn   347:     if (defined($env{'form.replyid'})) {
1.212     raeburn   348:         $msgkey = $env{'form.replyid'};
                    349:     } elsif (defined($env{'form.forwid'})) {
                    350:         $msgkey = $env{'form.forwid'}
                    351:     } elsif (defined($env{'form.multiforwid'})) {
                    352:         $msgkey = $env{'form.multiforwid'};
                    353:     }
                    354:     if ($msgkey ne '') {
1.201     raeburn   355:         my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$origcid)=
1.212     raeburn   356:                    split(/\:/,&unescape($msgkey));
1.201     raeburn   357:         $course_context = $origcid;
                    358:     }
                    359:     foreach my $key (keys(%env)) {
                    360:         if ($key=~/^form\.(rep)?rec\_(.*)$/) {
                    361:             my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$origcid) =
                    362:                                     split(/\:/,&unescape($2));
                    363:             $course_context = $origcid;
                    364:             last;
                    365:         }
                    366:     }
                    367:     if ($course_context eq '') {
                    368:         $course_context = $env{'request.course.id'};
                    369:     }
                    370:     return $course_context;
                    371: }
                    372: 
1.2       www       373: 
1.3       www       374: sub unpackagemsg {
1.212     raeburn   375:     my ($message,$notoken,$noattachmentlink)=@_;
1.2       www       376:     my %content=();
                    377:     my $parser=HTML::TokeParser->new(\$message);
                    378:     my $token;
                    379:     while ($token=$parser->get_token) {
                    380:        if ($token->[0] eq 'S') {
                    381: 	   my $entry=$token->[1];
                    382:            my $value=$parser->get_text('/'.$entry);
1.156     raeburn   383:            if (($entry eq 'recuser') || ($entry eq 'recdomain')) {
                    384:                push(@{$content{$entry}},$value);
1.162     raeburn   385:            } elsif ($entry eq 'recipient') {
                    386:                my $username = $token->[2]{'username'};
                    387:                $username = &HTML::Entities::decode($username,'<>&"');
                    388:                $content{$entry}{$username} = $value;
1.156     raeburn   389:            } else {
                    390:                $content{$entry}=$value;
                    391:            }
1.2       www       392:        }
                    393:     }
1.168     albertel  394:     if (!exists($content{'recuser'})) { $content{'recuser'} = []; }
1.212     raeburn   395:     if (($content{'attachmenturl'}) && (!$noattachmentlink)) {
1.100     albertel  396:        my ($fname)=($content{'attachmenturl'}=~m|/([^/]+)$|);
1.52      www       397:        if ($notoken) {
1.100     albertel  398: 	   $content{'message'}.='<p>'.&mt('Attachment').': <tt>'.$fname.'</tt>';
1.52      www       399:        } else {
1.99      albertel  400: 	   &Apache::lonnet::allowuploaded('/adm/msg',
                    401: 					  $content{'attachmenturl'});
                    402: 	   $content{'message'}.='<p>'.&mt('Attachment').
                    403: 	       ': <a href="'.$content{'attachmenturl'}.'"><tt>'.
1.100     albertel  404: 	       $fname.'</tt></a>';
1.52      www       405:        }
                    406:     }
1.2       www       407:     return %content;
                    408: }
                    409: 
1.6       www       410: 
1.159     raeburn   411: sub buildmsgid {
1.191     raeburn   412:     my ($now,$subject,$uname,$udom,$msgcount,$course_context,$symb,$error,$pid) = @_;
1.184     www       413:     $subject=&escape($subject);
1.192     raeburn   414:     $symb = &escape($symb);
1.184     www       415:     return(&escape($now.':'.$subject.':'.$uname.':'.
1.191     raeburn   416:            $udom.':'.$msgcount.':'.$course_context.':'.$pid.':'.$symb.':'.$error));
1.159     raeburn   417: }
                    418: 
1.6       www       419: sub unpackmsgid {
1.243     raeburn   420:     my ($msgid,$folder,$skipstatus,$status_cache,$onlycid)=@_;
1.184     www       421:     $msgid=&unescape($msgid);
1.167     raeburn   422:     my ($sendtime,$shortsubj,$fromname,$fromdomain,$count,$fromcid,
1.191     raeburn   423:         $processid,$symb,$error) = split(/\:/,&unescape($msgid));
1.243     raeburn   424:     if (!defined($processid)) { $fromcid = ''; }
                    425:     if (($onlycid) && ($onlycid ne $fromcid)) {
                    426:         return ($sendtime,'',$fromname,$fromdomain,'',$fromcid,'',$error);
                    427:     }
1.184     www       428:     $shortsubj = &unescape($shortsubj);
1.182     albertel  429:     $shortsubj = &HTML::Entities::decode($shortsubj);
1.192     raeburn   430:     $symb = &unescape($symb);
1.164     raeburn   431:     my %status=();
                    432:     unless ($skipstatus) {
1.169     albertel  433: 	if (ref($status_cache)) {
                    434: 	    $status{$msgid} = $status_cache->{$msgid};
                    435: 	} else {
                    436: 	    my $suffix=&foldersuffix($folder);
                    437: 	    %status=&Apache::lonnet::get('email_status'.$suffix,[$msgid]);
                    438: 	}
                    439: 	if ($status{$msgid}=~/^error\:/) { $status{$msgid}=''; }
1.164     raeburn   440:         unless ($status{$msgid}) { $status{$msgid}='new'; }
                    441:     }
1.191     raeburn   442:     return ($sendtime,$shortsubj,$fromname,$fromdomain,$status{$msgid},$fromcid,$symb,$error);
1.141     raeburn   443: }
1.6       www       444: 
1.53      www       445: 
                    446: sub sendemail {
1.242     musolffc  447:     my ($to,$subject,$body,$to_uname,$to_udom,$user_lh,$attachmenturl)=@_;
1.186     www       448:     my $senderaddress='';
1.220     raeburn   449:     my $replytoaddress='';
1.238     raeburn   450:     my $msgsent;
1.220     raeburn   451:     if ($env{'form.can_reply'} eq 'N') {
                    452:         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                    453:         my $hostname = &Apache::lonnet::hostname($lonhost);
                    454:         $replytoaddress = 'do-not-reply@'.$hostname;
                    455:     } else {
                    456:         my %senderemails;
                    457:         my $have_sender;
                    458:         if ($env{'form.reply_to_addr'}) {
                    459:             my ($replytoname,$replytodom) = split(/:/,$env{'form.reply_to_addr'});
                    460:             if (!($replytoname eq $env{'user.name'} && $replytodom eq $env{'user.domain'})) {
                    461:                 if (&Apache::lonnet::homeserver($replytoname,$replytodom) ne 'no_host') {
                    462:                     %senderemails = 
                    463:                         &Apache::loncommon::getemails($replytoname,$replytodom);
                    464:                     $have_sender = 1;
                    465:                 }
                    466:             }
                    467:         }
                    468:         if (!$have_sender) {
                    469:             %senderemails=&Apache::loncommon::getemails();
                    470:         }
                    471:         foreach my $type ('permanentemail','critnotification','notification') {
                    472:             if ($senderemails{$type}) {
                    473:                 ($senderaddress) = split(/,/,$senderemails{$type});
                    474:                 last if ($senderaddress);
                    475:             }
                    476:         }
1.186     www       477:     }
1.53      www       478:     $body=
1.217     schafran  479:     "*** ".&mt_user($user_lh,'This is an automatic e-mail generated by the LON-CAPA system.')."\n".
                    480:     "*** ".($senderaddress?&mt_user($user_lh,'You can reply to this e-mail'):&mt_user($user_lh,'Please do not reply to this address.')."\n*** ".
1.220     raeburn   481:     &mt_user($user_lh,'A reply will not be received by the recipient!'))."\n\n".$body;
1.225     jms       482:     
1.242     musolffc  483:     $attachmenturl = &Apache::lonnet::filelocation("",$attachmenturl);
                    484:     my $filesize = (stat($attachmenturl))[7];
                    485:     if ($filesize > 1048576) {
                    486:         # Don't send if it exceeds 1 MB.
                    487:         print '<p><span class="LC_error">' 
                    488:             .&mt('Email not sent.  Attachment exceeds permitted length.')
                    489:             .'</span><br /></p>';
                    490:     } else {
                    491:         # Otherwise build and send the email
                    492:         $subject = '[LON-CAPA] '.$subject;
1.245     raeburn   493:         &Apache::loncommon::mime_email($senderaddress,$replytoaddress,$to,
                    494:                                        $subject,$body,'','',$attachmenturl,'','');
1.238     raeburn   495:         $msgsent = 1;
1.68      www       496:     }
1.238     raeburn   497:     return $msgsent;
1.53      www       498: }
                    499: 
                    500: # ==================================================== Send notification emails
                    501: 
                    502: sub sendnotification {
1.242     musolffc  503:     my ($to,$touname,$toudom,$subj,$crit,$text,$msgid,$attachmenturl)=@_;
1.140     albertel  504:     my $sender=$env{'environment.firstname'}.' '.$env{'environment.lastname'};
1.131     www       505:     unless ($sender=~/\w/) { 
1.208     raeburn   506: 	$sender=$env{'user.name'}.':'.$env{'user.domain'};
1.131     www       507:     }
1.53      www       508:     my $critical=($crit?' critical':'');
1.238     raeburn   509:     my $numsent = 0;
1.208     raeburn   510: 
1.131     www       511:     $text=~s/\&lt\;/\</gs;
                    512:     $text=~s/\&gt\;/\>/gs;
1.249   ! raeburn   513:     my $touhome = &Apache::lonnet::homeserver($touname,$toudom);
        !           514:     my $url = &Apache::lonnet::url_prefix('',$toudom,$touhome,'email').
1.226     raeburn   515:               '/adm/email?username='.$touname.'&domain='.$toudom.
                    516:               '&display='.&escape($msgid);
1.194     raeburn   517:     my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$fromcid,
                    518:         $symb,$error) = &Apache::lonmsg::unpackmsgid($msgid);
1.208     raeburn   519:     my ($coursetext,$body,$bodybegin,$bodysubj,$bodyend);
1.222     raeburn   520:     my $user_lh = &Apache::loncommon::user_lang($touname,$toudom,$fromcid);
1.194     raeburn   521:     if ($fromcid ne '') {
1.213     raeburn   522:         $coursetext = "\n".&mt_user($user_lh,'Course').': ';
1.194     raeburn   523:         if ($env{'course.'.$fromcid.'.description'} ne '') {
                    524:             $coursetext .= $env{'course.'.$fromcid.'.description'};
                    525:         } else {
                    526:             my %coursehash = &Apache::lonnet::coursedescription($fromcid,);
                    527:             if ($coursehash{'description'} ne '') {
                    528:                 $coursetext .= $coursehash{'description'};
                    529:             }
                    530:         }
                    531:         $coursetext .= "\n\n";
                    532:     }
1.206     raeburn   533:     my @recipients = split(/,/,$to);
1.208     raeburn   534:     $bodybegin = $coursetext. 
1.213     raeburn   535:                &mt_user($user_lh,
                    536:                          'You received a'.$critical.' message from [_1] in LON-CAPA.',$sender).' ';
                    537:     $bodysubj = &mt_user($user_lh,'The subject is 
1.53      www       538: 
1.195     raeburn   539:  [_1]
1.53      www       540: 
1.195     raeburn   541: ',$subj)."\n".
1.213     raeburn   542: '=== '.&mt_user($user_lh,'Excerpt')." ============================================================
1.206     raeburn   543: ";
                    544:     $bodyend = "
1.131     www       545: ========================================================================
                    546: 
1.213     raeburn   547: ".&mt_user($user_lh,'Use 
1.53      www       548: 
1.195     raeburn   549:  [_1]
1.53      www       550: 
1.195     raeburn   551: to access the full message.',$url);
1.206     raeburn   552:     my %userenv = &Apache::lonnet::get('environment',['notifywithhtml'],$toudom,$touname);
1.235     bisitz    553:     my $subject = &mt_user($user_lh,"'New'$critical message from [_1]",$sender);
1.232     raeburn   554:     unless ($subj eq '') {
                    555:         $subject = $subj;
                    556:     }
1.208     raeburn   557:  
1.247     raeburn   558:     my ($blocked,$blocktext,$clientip);
                    559:     $clientip = &Apache::lonnet::get_requestor_ip();
1.208     raeburn   560:     if (!$crit) {
                    561:         my %setters;
1.247     raeburn   562:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                    563:             &Apache::loncommon::blockcheck(\%setters,'com',$clientip,$touname,$toudom);
1.208     raeburn   564:         if ($startblock && $endblock) {
                    565:             $blocked = 1;
1.209     albertel  566:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
                    567:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
1.213     raeburn   568:             $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);
1.247     raeburn   569:         } elsif ($by_ip) {
                    570:             $blocked = 1;
                    571:             $blocktext = &mt_user($user_lh,'LON-CAPA messages sent to you will be inaccessible from your IP address [_1], because communication is being blocked for certain IP address(es).',$clientip);
1.208     raeburn   572:         }
                    573:     }
1.206     raeburn   574:     if ($userenv{'notifywithhtml'} ne '') {
                    575:         my @htmlexcerpt = split(/,/,$userenv{'notifywithhtml'});
1.226     raeburn   576:         my $htmlfree = &make_htmlfree($text);
1.206     raeburn   577:         foreach my $addr (@recipients) {
1.208     raeburn   578:             if ($blocked) {
                    579:                 $body = $bodybegin."\n".$blocktext."\n".$bodyend;
                    580:             } else {
1.226     raeburn   581:                 my $sendtext;
1.208     raeburn   582:                 if (!grep/^\Q$addr\E/,@htmlexcerpt) {
1.227     raeburn   583:                     $sendtext = $htmlfree;
1.226     raeburn   584:                 } else {
                    585:                     $sendtext = $text;
1.208     raeburn   586:                 }
                    587:                 $body = $bodybegin.$bodysubj.$sendtext.$bodyend;
1.206     raeburn   588:             }
1.242     musolffc  589:             if (&sendemail($addr,$subject,$body,$touname,$toudom,$user_lh,$attachmenturl)) {
1.238     raeburn   590:                 $numsent ++;
                    591:             }
1.206     raeburn   592:         }
                    593:     } else {
1.208     raeburn   594:         if ($blocked) {
                    595:             $body = $bodybegin."\n".$blocktext."\n".$bodyend;
                    596:         } else {
1.226     raeburn   597:             my $htmlfree = &make_htmlfree($text);
                    598:             $body = $bodybegin.$bodysubj.$htmlfree.$bodyend;
1.208     raeburn   599:         }
1.242     musolffc  600:         if (&sendemail($to,$subject,$body,$touname,$toudom,$user_lh,$attachmenturl)) {
1.238     raeburn   601:             $numsent ++;
                    602:         }
1.206     raeburn   603:     }
1.238     raeburn   604:     return $numsent;
1.53      www       605: }
1.215     jms       606: 
1.226     raeburn   607: sub make_htmlfree {
                    608:     my ($text) = @_;
                    609:     $text =~ s/\<\/*[^\>]+\>//gs;
                    610:     $text = &HTML::Entities::decode($text);
                    611:     $text = &Encode::encode('utf8',$text);
                    612:     return $text;
                    613: }
                    614: 
1.223     kaisler   615: sub mynewmail{
                    616: 	&newmail();
1.231     raeburn   617: 	return $env{'user.mailcheck.lastnewmessagetime'} > $env{'user.mailcheck.lastvisit'};
1.223     kaisler   618: }
                    619: 
1.40      www       620: 
                    621: sub newmail {
1.140     albertel  622:     if ((time-$env{'user.mailcheck.time'})>300) {
1.40      www       623:         my %what=&Apache::lonnet::get('email_status',['recnewemail']);
1.211     raeburn   624:         &Apache::lonnet::appenv({'user.mailcheck.time'=>time});
1.231     raeburn   625: 		&Apache::lonnet::appenv({'user.mailcheck.lastnewmessagetime'=> $what{'recnewemail'}});
1.40      www       626:         if ($what{'recnewemail'}>0) { return 1; }
                    627:     }
                    628:     return 0;
                    629: }
                    630: 
1.1       www       631: 
1.58      bowersj2  632: 
1.1       www       633: sub author_res_msg {
                    634:     my ($filename,$message)=@_;
1.2       www       635:     unless ($message) { return 'empty'; }
1.1       www       636:     $filename=&Apache::lonnet::declutter($filename);
1.72      www       637:     my ($domain,$author,@dummy)=split(/\//,$filename);
1.1       www       638:     my $homeserver=&Apache::lonnet::homeserver($author,$domain);
                    639:     if ($homeserver ne 'no_host') {
                    640:        my $id=unpack("%32C*",$message);
1.181     albertel  641:        $message .= " <p>This error occurred on machine ".
                    642: 	   $Apache::lonnet::perlvar{'lonHostID'}."</p>";
1.2       www       643:        my $msgid;
1.72      www       644:        ($msgid,$message)=&packagemsg($filename,$message);
1.3       www       645:        return &Apache::lonnet::reply('put:'.$domain.':'.$author.
1.72      www       646:          ':nohist_res_msgs:'.
1.184     www       647:           &escape($filename.'_'.$id).'='.
                    648:           &escape($message),$homeserver);
1.1       www       649:     }
1.2       www       650:     return 'no_host';
1.73      www       651: }
                    652: 
1.215     jms       653: 
1.73      www       654: 
                    655: sub retrieve_author_res_msg {
1.75      www       656:     my $url=shift;
1.73      www       657:     $url=&Apache::lonnet::declutter($url);
1.187     albertel  658:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
1.76      www       659:     my %errormsgs=&Apache::lonnet::dump('nohist_res_msgs',$domain,$author);
1.73      www       660:     my $msgs='';
1.239     raeburn   661:     foreach my $msg (keys(%errormsgs)) {
                    662: 	if ($msg =~ /^\Q$url\E\_\d+$/) {
                    663: 	    my %content=&unpackagemsg($errormsgs{$msg});
1.74      www       664: 	    $msgs.='<p><img src="/adm/lonMisc/bomb.gif" /><b>'.
                    665: 		$content{'time'}.'</b>: '.$content{'message'}.
                    666: 		'<br /></p>';
1.73      www       667: 	}
                    668:     } 
                    669:     return $msgs;     
                    670: }
                    671: 
                    672: 
1.215     jms       673: 
                    674: 
1.73      www       675: 
                    676: sub del_url_author_res_msg {
1.75      www       677:     my $url=shift;
1.73      www       678:     $url=&Apache::lonnet::declutter($url);
1.187     albertel  679:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
1.77      www       680:     my @delmsgs=();
1.239     raeburn   681:     foreach my $msg (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
                    682: 	if ($msg =~ /^\Q$url\E\_\d+$/) {
                    683: 	    push (@delmsgs,$msg);
1.77      www       684: 	}
                    685:     }
                    686:     return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
1.73      www       687: }
1.215     jms       688: 
1.73      www       689: 
1.152     www       690: sub clear_author_res_msg {
                    691:     my $url=shift;
                    692:     $url=&Apache::lonnet::declutter($url);
1.187     albertel  693:     my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
1.152     www       694:     my @delmsgs=();
1.239     raeburn   695:     foreach my $msg (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
                    696: 	if ($msg =~ /^\Q$url\E/) {
                    697: 	    push (@delmsgs,$msg);
1.152     www       698: 	}
                    699:     }
                    700:     return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
                    701: }
1.215     jms       702: 
                    703: 
1.73      www       704: 
                    705: sub all_url_author_res_msg {
                    706:     my ($author,$domain)=@_;
1.75      www       707:     my %returnhash=();
1.239     raeburn   708:     foreach my $msg (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
                    709: 	$msg =~ /^(.+)\_\d+/;
1.75      www       710: 	$returnhash{$1}=1;
                    711:     }
                    712:     return %returnhash;
1.1       www       713: }
                    714: 
1.185     albertel  715: 
                    716: sub store_instructor_comment {
                    717:     my ($msg,$uname,$udom) = @_;
                    718:     my $cid  = $env{'request.course.id'};
                    719:     my $cnum = $env{'course.'.$cid.'.num'};
                    720:     my $cdom = $env{'course.'.$cid.'.domain'};
                    721:     my $subject= &mt('Record').' ['.$uname.':'.$udom.']';
                    722:     my $result = &user_normal_msg_raw($cnum,$cdom,$subject,$msg);
1.201     raeburn   723:     if ($result eq 'ok' || $result eq 'con_delayed') {
                    724:         
                    725:     }
1.185     albertel  726:     return $result;
                    727: }
                    728: 
1.1       www       729: 
1.38      www       730: sub user_crit_msg_raw {
1.201     raeburn   731:     my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage,
1.248     raeburn   732:         $nosentstore,$recipid,$attachmenturl,$permresults,$senthide)=@_;
1.2       www       733: # Check if allowed missing
1.190     raeburn   734:     my ($status,$packed_message);
1.2       www       735:     my $msgid='undefined';
                    736:     unless (($message)&&($user)&&($domain)) { $status='empty'; };
1.131     www       737:     my $text=$message;
1.2       www       738:     my $homeserver=&Apache::lonnet::homeserver($user,$domain);
                    739:     if ($homeserver ne 'no_host') {
1.202     raeburn   740:        ($msgid,$packed_message)=&packagemsg($subject,$message,undef,undef,
1.212     raeburn   741:                                   $attachmenturl,undef,undef,undef,undef,undef,
                    742:                                   undef,undef,$recipid);
1.190     raeburn   743:        if ($sendback) { $packed_message.='<sendback>true</sendback>'; }
1.210     albertel  744:        $status=&Apache::lonnet::cput('critical', {$msgid => $packed_message},
                    745: 				     $domain,$user);
1.159     raeburn   746:         if (defined($sentmessage)) {
1.190     raeburn   747:             $$sentmessage = $packed_message;
1.159     raeburn   748:         }
1.201     raeburn   749:         if (!$nosentstore) {
1.248     raeburn   750:             my ($sentmsgid,$packed_message_no_citation) =
1.212     raeburn   751:             &packagemsg($subject,$message,undef,undef,$attachmenturl,$user,
1.248     raeburn   752:                         $domain,$msgid,undef,undef,undef,undef,undef,$senthide,$msgid);
1.193     raeburn   753:             if ($status eq 'ok' || $status eq 'con_delayed') {
1.248     raeburn   754:                 if ($senthide && $sentmsgid) {
                    755:                     &store_sent_mail($sentmsgid,$packed_message_no_citation);
                    756:                 } else {
                    757:                     &store_sent_mail($msgid,$packed_message_no_citation);
                    758:                 }
1.193     raeburn   759:             }
                    760:         }
1.2       www       761:     } else {
                    762:        $status='no_host';
                    763:     }
1.190     raeburn   764: 
1.53      www       765: # Notifications
1.186     www       766:     my %userenv = &Apache::loncommon::getemails($user,$domain);
1.238     raeburn   767:     my $critnotify = $userenv{'critnotification'};
                    768:     my $permemail = $userenv{'permanentemail'};
                    769:     my $numcrit = 0;
                    770:     my $numperm = 0;
                    771:     my $permlogmsgstatus;
                    772:     if ($critnotify) {
1.242     musolffc  773:         $numcrit = &sendnotification($critnotify,$user,$domain,$subject,1,$text,$msgid,$attachmenturl);
1.238     raeburn   774:     }
                    775:     if ($toperm && $permemail) {
                    776:         if ($critnotify && $numcrit) {
                    777:             if (grep(/^\Q$permemail\E/,split(/,/,$critnotify))) {
                    778:                 $numperm = 1;
                    779:             }
                    780:         }
                    781:         unless ($numperm) {
1.242     musolffc  782:             $numperm = &sendnotification($permemail,$user,$domain,$subject,1,$text,$msgid,$attachmenturl);
1.238     raeburn   783:         }
                    784:     }
                    785:     if ($toperm) {
                    786:         $permlogmsgstatus = '. Perm. email log status '.
                    787:                             &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
                    788:                                                  "Perm. e-mail count $numperm for $user at $domain");
                    789:         if (ref($permresults) eq 'HASH') {
                    790:             $permresults->{"$user:$domain"} = $numperm;
                    791:         }
1.132     www       792:     }
1.53      www       793: # Log this
1.2       www       794:     &Apache::lonnet::logthis(
1.238     raeburn   795:       'Sending critical '.$msgid.
1.2       www       796:       ', log status: '.
1.140     albertel  797:       &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
                    798:                          $env{'user.home'},
1.238     raeburn   799:       'Sending critical '.$msgid.' to '.$user.' at '.$domain.' with status '
                    800:       .$status).$permlogmsgstatus);
1.2       www       801:     return $status;
                    802: }
                    803: 
1.38      www       804: 
1.58      bowersj2  805: 
1.38      www       806: sub user_crit_msg {
1.201     raeburn   807:     my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage,
1.248     raeburn   808:         $nosentstore,$recipid,$attachmenturl,$permresults,$senthide)=@_;
1.183     albertel  809:     my @status;
1.38      www       810:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
                    811:                                        $domain,$user);
                    812:     my $msgforward=$userenv{'msgforward'};
                    813:     if ($msgforward) {
1.183     albertel  814:        foreach my $addr (split(/\,/,$msgforward)) {
                    815: 	 my ($forwuser,$forwdomain)=split(/\:/,$addr);
                    816:          push(@status,
                    817: 	      &user_crit_msg_raw($forwuser,$forwdomain,$subject,$message,
1.202     raeburn   818: 				 $sendback,$toperm,$sentmessage,$nosentstore,
1.248     raeburn   819:                                  $recipid,$attachmenturl,$permresults,$senthide));
1.38      www       820:        }
                    821:     } else { 
1.183     albertel  822: 	push(@status,
                    823: 	     &user_crit_msg_raw($user,$domain,$subject,$message,$sendback,
1.212     raeburn   824: 				$toperm,$sentmessage,$nosentstore,$recipid,
1.248     raeburn   825:                                 $attachmenturl,$permresults,$senthide));
1.38      www       826:     }
1.183     albertel  827:     if (wantarray) {
                    828: 	return @status;
                    829:     }
                    830:     return join(' ',@status);
1.38      www       831: }
                    832: 
1.2       www       833: 
                    834: sub user_crit_received {
1.12      www       835:     my $msgid=shift;
                    836:     my %message=&Apache::lonnet::get('critical',[$msgid]);
1.52      www       837:     my %contents=&unpackagemsg($message{$msgid},1);
1.204     raeburn   838:     my $destname = $contents{'sendername'};
                    839:     my $destdom = $contents{'senderdomain'};
                    840:     if ($contents{'replytoaddr'}) {
                    841:         my ($repname,$repdom) = split(/:/,$contents{'replytoaddr'});
                    842:         if (&Apache::lonnet::homeserver($repname,$repdom) ne 'no_host') {
                    843:             $destname = $repname;
                    844:             $destdom = $repdom;    
                    845:         }
                    846:     }
1.24      www       847:     my $status='rec: '.($contents{'sendback'}?
1.204     raeburn   848:      &user_normal_msg($destname,$destdom,&mt('Receipt').': '.$env{'user.name'}.
                    849:                       ' '.&mt('at').' '.$env{'user.domain'}.', '.
                    850:                       $contents{'subject'},&mt('User').' '.$env{'user.name'}.
                    851:                       ' '.&mt('at').' '.$env{'user.domain'}.
                    852:                       ' acknowledged receipt of message'."\n".'   "'.
                    853:                       $contents{'subject'}.'"'."\n".&mt('dated').' '.
                    854:                       $contents{'time'}.".\n"
                    855:                       ):'no msg req');
1.5       www       856:     $status.=' trans: '.
1.12      www       857:      &Apache::lonnet::put(
                    858:      'nohist_email',{$contents{'msgid'} => $message{$msgid}});
1.5       www       859:     $status.=' del: '.
1.9       albertel  860:      &Apache::lonnet::del('critical',[$contents{'msgid'}]);
1.140     albertel  861:     &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
                    862:                          $env{'user.home'},'Received critical message '.
1.5       www       863:                          $contents{'msgid'}.
                    864:                          ', '.$status);
1.12      www       865:     return $status;
1.2       www       866: }
                    867: 
1.215     jms       868: 
                    869: 
1.2       www       870: 
1.38      www       871: sub user_normal_msg_raw {
1.132     www       872:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
1.191     raeburn   873:         $toperm,$currid,$newid,$sentmessage,$crsmsgid,$symb,$restitle,
1.248     raeburn   874:         $error,$nosentstore,$recipid,$permresults,$senthide)=@_;
1.2       www       875: # Check if allowed missing
1.173     albertel  876:     my ($status,$packed_message);
1.2       www       877:     my $msgid='undefined';
1.131     www       878:     my $text=$message;
1.2       www       879:     unless (($message)&&($user)&&($domain)) { $status='empty'; };
                    880:     my $homeserver=&Apache::lonnet::homeserver($user,$domain);
                    881:     if ($homeserver ne 'no_host') {
1.173     albertel  882:        ($msgid,$packed_message)=
                    883: 	                 &packagemsg($subject,$message,$citation,$baseurl,
1.174     raeburn   884:                                      $attachmenturl,$user,$domain,$currid,
1.202     raeburn   885:                                      undef,$crsmsgid,$symb,$error,$recipid);
1.174     raeburn   886: 
1.108     www       887: # Store in user folder
1.210     albertel  888:        $status=
                    889: 	   &Apache::lonnet::cput('nohist_email',{$msgid => $packed_message},
                    890: 				 $domain,$user);
1.108     www       891: # Save new message received time
1.40      www       892:        &Apache::lonnet::put
                    893:                          ('email_status',{'recnewemail'=>time},$domain,$user);
1.201     raeburn   894: # Into sent-mail folder if sent mail storage required
                    895:        if (!$nosentstore) {
1.248     raeburn   896:            my ($sentmsgid,$packed_message_no_citation) =
1.190     raeburn   897:                &packagemsg($subject,$message,undef,$baseurl,$attachmenturl,
1.248     raeburn   898:                            $user,$domain,$currid,undef,$crsmsgid,$symb,$error,
                    899:                            undef,$senthide,$msgid);
1.193     raeburn   900:            if ($status eq 'ok' || $status eq 'con_delayed') {
1.248     raeburn   901:                if ($senthide && $sentmsgid) {
                    902:                    &store_sent_mail($sentmsgid,$packed_message_no_citation);
                    903:                } else {
                    904:                    &store_sent_mail($msgid,$packed_message_no_citation);
                    905:                }
1.193     raeburn   906:            }
1.156     raeburn   907:        }
1.201     raeburn   908:        if (ref($newid) eq 'SCALAR') {
1.196     www       909: 	   $$newid = $msgid;
                    910:        }
1.201     raeburn   911:        if (ref($sentmessage) eq 'SCALAR') {
1.196     www       912: 	   $$sentmessage = $packed_message;
                    913:        }
                    914: # Notifications
1.206     raeburn   915:        my %userenv = &Apache::loncommon::getemails($user,$domain);
1.238     raeburn   916:        my $notify = $userenv{'notification'};
                    917:        my $permemail = $userenv{'permanentemail'};
                    918:        my $numnotify = 0;
                    919:        my $numperm = 0;
                    920:        my $permlogmsgstatus;
                    921:        if ($notify) {
1.242     musolffc  922:            $numnotify = &sendnotification($notify,$user,$domain,$subject,0,$text,$msgid,$attachmenturl);
1.238     raeburn   923:        }
                    924:        if ($toperm && $permemail) {
                    925:            if ($notify && $numnotify) {
                    926:                if (grep(/^\Q$permemail\E/,split(/,/,$notify))) {
                    927:                    $numperm = 1;
                    928:                }
                    929:            }
                    930:            unless ($numperm) {
                    931:                $numperm = &sendnotification($permemail,$user,$domain,$subject,0,
1.242     musolffc  932:                                             $text,$msgid,$attachmenturl);
1.238     raeburn   933:            }
1.196     www       934:        }
1.238     raeburn   935:        if ($toperm) {
                    936:            $permlogmsgstatus = '. Perm. email log status '.
                    937:                          &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
                    938:                                               "Perm. e-mail count $numperm for $user at $domain");
                    939:            if (ref($permresults) eq 'HASH') {
                    940:                $permresults->{"$user:$domain"} = $numperm;
1.214     raeburn   941:            }
1.196     www       942:        }
                    943:        &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
                    944: 			    $env{'user.home'},
1.238     raeburn   945: 			    'Sending '.$msgid.' to '.$user.' at '.$domain.' with status '.$status.
                    946:                             $permlogmsgstatus);
1.196     www       947:    } else {
1.2       www       948:        $status='no_host';
1.196     www       949:    }
1.2       www       950:     return $status;
                    951: }
1.38      www       952: 
                    953: sub user_normal_msg {
1.132     www       954:     my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
1.238     raeburn   955: 	$toperm,$sentmessage,$symb,$restitle,$error,$nosentstore,$recipid,
1.248     raeburn   956:         $permresults,$senthide)=@_;
1.199     raeburn   957:     my @status;
1.38      www       958:     my %userenv = &Apache::lonnet::get('environment',['msgforward'],
                    959:                                        $domain,$user);
                    960:     my $msgforward=$userenv{'msgforward'};
                    961:     if ($msgforward) {
1.239     raeburn   962:         foreach my $fwd (split(/\,/,$msgforward)) {
                    963: 	    my ($forwuser,$forwdomain)=split(/\:/,$fwd);
1.199     raeburn   964: 	    push(@status,
1.171     banghart  965: 	        &user_normal_msg_raw($forwuser,$forwdomain,$subject,$message,
1.172     albertel  966: 				     $citation,$baseurl,$attachmenturl,$toperm,
1.201     raeburn   967: 				     undef,undef,$sentmessage,undef,$symb,
1.248     raeburn   968:                                      $restitle,$error,$nosentstore,$recipid,
                    969:                                      $permresults,$senthide));
1.171     banghart  970:         }
1.191     raeburn   971:     } else {
1.199     raeburn   972: 	push(@status,&user_normal_msg_raw($user,$domain,$subject,$message,
1.172     albertel  973: 				     $citation,$baseurl,$attachmenturl,$toperm,
1.201     raeburn   974: 				     undef,undef,$sentmessage,undef,$symb,
1.248     raeburn   975:                                      $restitle,$error,$nosentstore,$recipid,
                    976:                                      $permresults,$senthide));
1.199     raeburn   977:     }
                    978:     if (wantarray) {
                    979:         return @status;
1.38      www       980:     }
1.199     raeburn   981:     return join(' ',@status);
1.38      www       982: }
                    983: 
1.201     raeburn   984: sub process_sent_mail {
1.236     raeburn   985:     my ($msgsubj,$subj_prefix,$numsent,$stamp,$msgname,$msgdom,$msgcount,
                    986:         $context,$pid,$savemsg,$recusers,$recudoms,$baseurl,$attachmenturl,
                    987:         $symb,$error,$senderuname,$senderdom,$recipid) = @_;
1.201     raeburn   988:     my $sentsubj;
                    989:     if ($numsent > 1) {
                    990:         $sentsubj = $subj_prefix.' ('.$numsent.' sent) '.$msgsubj;
1.205     raeburn   991:     } else {
                    992:         if ($subj_prefix) {
                    993:             $sentsubj = $subj_prefix.' ';
                    994:         }
                    995:         $sentsubj .= $msgsubj;
1.201     raeburn   996:     }
                    997:     $sentsubj = &HTML::Entities::encode($sentsubj,'<>&"');
                    998:     my $sentmsgid = 
                    999:         &buildmsgid($stamp,$sentsubj,$msgname,$msgdom,$msgcount,$context,$pid);
                   1000:     (undef,my $sentmessage) =
                   1001:         &packagemsg($msgsubj,$savemsg,undef,$baseurl,$attachmenturl,$recusers,
1.214     raeburn  1002:                     $recudoms,$sentmsgid,undef,undef,$symb,$error,$recipid);
1.201     raeburn  1003:     my $status = &store_sent_mail($sentmsgid,$sentmessage,$senderuname,
1.210     albertel 1004:                                   $senderdom);
1.201     raeburn  1005:     return $status;
                   1006: }
                   1007: 
1.156     raeburn  1008: sub store_sent_mail {
1.210     albertel 1009:     my ($msgid,$message,$senderuname,$senderdom) = @_;
1.201     raeburn  1010:     if ($senderuname eq '') {
                   1011:         $senderuname = $env{'user.name'};
                   1012:     }
                   1013:     if ($senderdom eq '') {
                   1014:         $senderdom = $env{'user.domain'};
                   1015:     }
1.210     albertel 1016:     my $status =' '.&Apache::lonnet::cput('nohist_email_sent',
                   1017: 					  {$msgid => $message},
                   1018: 					  $senderdom,$senderuname);
1.156     raeburn  1019:     return $status;
                   1020: }
1.2       www      1021: 
1.202     raeburn  1022: sub store_recipients {
                   1023:     my ($subject,$sendername,$senderdom,$reciphash) = @_;
                   1024:     my $context = &get_course_context();
1.203     albertel 1025:     my $now = time();
1.202     raeburn  1026:     my $msgcount = &get_uniq();
                   1027:     my $recipid =
                   1028:         &buildmsgid($now,$subject,$sendername,$senderdom,$msgcount,$context,$$);
                   1029:     my %recipinfo = (
                   1030:                          $recipid => $reciphash,
                   1031:                     );
                   1032:     my $status = &Apache::lonnet::put('nohist_emailrecip',\%recipinfo,
                   1033:                                       $senderdom,$sendername); 
                   1034:     if ($status eq 'ok') {
                   1035:         return ($recipid,$status);
                   1036:     } else {
                   1037:         return (undef,$status);
                   1038:     }
                   1039: }
                   1040: 
1.106     www      1041: 
                   1042: sub foldersuffix {
                   1043:     my $folder=shift;
                   1044:     unless ($folder) { return ''; }
1.189     raeburn  1045:     my $suffix;
                   1046:     my %folderhash = &get_user_folders($folder);
                   1047:     if (ref($folderhash{$folder}) eq 'HASH') {
                   1048:         $suffix = '_'.&escape($folderhash{$folder}{'id'});
                   1049:     } else {
                   1050:         $suffix = '_'.&escape($folder);
                   1051:     }
                   1052:     return $suffix;
                   1053: }
                   1054: 
                   1055: 
                   1056: sub get_user_folders {
                   1057:     my ($folder) = @_;
                   1058:     my %userfolders = 
                   1059:           &Apache::lonnet::dump('email_folders',undef,undef,$folder);
                   1060:     my $lock = "\0".'lock_counter'; # locks db while counter incremented
                   1061:     my $counter = "\0".'idcount';   # used in suffix for email db files
                   1062:     if (defined($userfolders{$lock})) {
                   1063:         delete($userfolders{$lock});
                   1064:     }
                   1065:     if (defined($userfolders{$counter})) {
                   1066:         delete($userfolders{$counter});
                   1067:     }
                   1068:     return %userfolders;
1.106     www      1069: }
                   1070: 
1.197     albertel 1071: sub secapply {
                   1072:     my $rec=shift;
                   1073:     my $defaultflag=shift;
                   1074:     $rec=~s/\s+//g;
1.229     raeburn  1075:     unless ($rec =~ /\:/) {
                   1076:         $rec=~s/\@/\:/g;
                   1077:     }
1.197     albertel 1078:     my ($adr,$sections_or_groups)=($rec=~/^([^\(]+)\(([^\)]+)\)/);
                   1079:     if ($sections_or_groups) {
                   1080: 	foreach my $item (split(/\;/,$sections_or_groups)) {
                   1081:             if (($item eq $env{'request.course.sec'}) ||
                   1082:                 ($defaultflag && ($item eq '*'))) {
                   1083:                 return $adr; 
                   1084:             } elsif ($env{'request.course.groups'}) {
                   1085:                 my @usersgroups = split(/:/,$env{'request.course.groups'});
                   1086:                 if (grep(/^\Q$item\E$/,@usersgroups)) {
                   1087:                     return $adr;
                   1088:                 }
                   1089:             } 
                   1090:         }
                   1091:     } else {
                   1092:        return $rec;
                   1093:     }
                   1094:     return '';
                   1095: }
                   1096: 
                   1097: sub decide_receiver {
                   1098:     my ($feedurl,$author,$question,$course,$policy,$defaultflag) = @_;
                   1099:     &Apache::lonenc::check_decrypt(\$feedurl);
                   1100:     my $typestyle='';
                   1101:     my %to=();
                   1102:     if ($env{'form.discuss'} eq 'author' ||$author) {
                   1103: 	$typestyle.='Submitting as Author Feedback<br />';
                   1104: 	$feedurl=~ m{^/res/($LONCAPA::domain_re)/($LONCAPA::username_re)/};
                   1105: 	$to{$2.':'.$1}=1;
                   1106:     }
                   1107:     my $cid = $env{'request.course.id'};
                   1108:     if ($env{'form.discuss'} eq 'question' ||$question) {
                   1109: 	$typestyle.=&mt('Submitting as Question').'<br />';
                   1110: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.question.email'})) {
                   1111: 	    my $rec=&secapply($item,$defaultflag);
                   1112: 	    if ($rec) { $to{$rec}=1; }
                   1113: 	} 
                   1114:     }
                   1115:     if ($env{'form.discuss'} eq 'course' ||$course) {
                   1116: 	$typestyle.=&mt('Submitting as Comment').'<br />';
                   1117: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.comment.email'})) {
                   1118: 	    my $rec=&secapply($item,$defaultflag);
                   1119: 	    if ($rec) { $to{$rec}=1; }
                   1120: 	} 
                   1121:     }
                   1122:     if ($env{'form.discuss'} eq 'policy' ||$policy) {
                   1123: 	$typestyle.=&mt('Submitting as Policy Feedback').'<br />';
                   1124: 	foreach my $item (split(/\,/,$env{'course.'.$cid.'.policy.email'})) {
                   1125: 	    my $rec=&secapply($item,$defaultflag);
                   1126: 	    if ($rec) { $to{$rec}=1; }
                   1127: 	} 
                   1128:     }
                   1129:     if ((scalar(%to) eq '0') && (!$defaultflag)) {
                   1130: 	($typestyle,%to)=
                   1131: 	    &decide_receiver($feedurl,$author,$question,$course,$policy,1);
                   1132:     }
                   1133:     return ($typestyle,%to);
                   1134: }
                   1135: 
1.180     albertel 1136: 1;
1.1       www      1137: __END__
                   1138: 

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