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

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

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