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

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

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