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