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

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

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