File:  [LON-CAPA] / loncom / interface / lonmsg.pm
Revision 1.212: download - view: text, annotated - select for diffs
Fri Jun 6 05:24:28 2008 UTC (15 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_7_X, version_2_7_1, version_2_7_0, version_2_6_99_1, version_2_6_99_0, HEAD
Bugs: 3706 5677 5678.
- Single attachment allowed in messages (whether sent via COM or FDBK).
- Warning displayed if uploaded file exceeded maximum size allowed for attachments (and was therefors discarded).
- Attachments included in forwarded messages (from both single message display, or from forward of multiple messages from folder display).
- Max size definition moved to a single location in lonmsgdisplay.pm and lonfeedback.pm
- Some appearance changes in modify_attachments display (for attachements associated with discussion posts).
- Subdirectory for storage of attachment file in sender's userfiles directory changed from feedback to feedback/$now (i.e., current UNIX time) to lessen likelihood of file being overwritten by a sequent message with an attachment of the same name.

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

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