1: # The LearningOnline Network with CAPA
2: # Routines for messaging
3: #
4: # $Id: lonmsg.pm,v 1.227 2010/09/13 23:35:44 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 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: =back
198:
199: =cut
200:
201: use strict;
202: use Apache::lonnet;
203: use HTML::TokeParser();
204: use Apache::lonlocal;
205: use Mail::Send;
206: use HTML::Entities;
207: use Encode;
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|^https?://[^/]+/|/|;
228: $baseurl =&HTML::Entities::encode($baseurl,'<>&"');
229: #remove machine specification
230: $attachmenturl =~ s|^https?://[^/]+/|/|;
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 $senderaddress='';
426: my $replytoaddress='';
427: if ($env{'form.can_reply'} eq 'N') {
428: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
429: my $hostname = &Apache::lonnet::hostname($lonhost);
430: $replytoaddress = 'do-not-reply@'.$hostname;
431: } else {
432: my %senderemails;
433: my $have_sender;
434: if ($env{'form.reply_to_addr'}) {
435: my ($replytoname,$replytodom) = split(/:/,$env{'form.reply_to_addr'});
436: if (!($replytoname eq $env{'user.name'} && $replytodom eq $env{'user.domain'})) {
437: if (&Apache::lonnet::homeserver($replytoname,$replytodom) ne 'no_host') {
438: %senderemails =
439: &Apache::loncommon::getemails($replytoname,$replytodom);
440: $have_sender = 1;
441: }
442: }
443: }
444: if (!$have_sender) {
445: %senderemails=&Apache::loncommon::getemails();
446: }
447: foreach my $type ('permanentemail','critnotification','notification') {
448: if ($senderemails{$type}) {
449: ($senderaddress) = split(/,/,$senderemails{$type});
450: last if ($senderaddress);
451: }
452: }
453: }
454: $body=
455: "*** ".&mt_user($user_lh,'This is an automatic e-mail generated by the LON-CAPA system.')."\n".
456: "*** ".($senderaddress?&mt_user($user_lh,'You can reply to this e-mail'):&mt_user($user_lh,'Please do not reply to this address.')."\n*** ".
457: &mt_user($user_lh,'A reply will not be received by the recipient!'))."\n\n".$body;
458:
459: my $msg = new Mail::Send;
460: $msg->to($to);
461: $msg->subject('[LON-CAPA] '.$subject);
462: if ($replytoaddress) {
463: $msg->add('Reply-to',$replytoaddress);
464: }
465: if ($senderaddress) {
466: $msg->add('From',$senderaddress);
467: }
468: if (my $fh = $msg->open()) {
469: print $fh $body;
470: $fh->close;
471: }
472: }
473:
474: # ==================================================== Send notification emails
475:
476: sub sendnotification {
477: my ($to,$touname,$toudom,$subj,$crit,$text,$msgid)=@_;
478: my $sender=$env{'environment.firstname'}.' '.$env{'environment.lastname'};
479: unless ($sender=~/\w/) {
480: $sender=$env{'user.name'}.':'.$env{'user.domain'};
481: }
482: my $critical=($crit?' critical':'');
483:
484: $text=~s/\<\;/\</gs;
485: $text=~s/\>\;/\>/gs;
486: my $homeserver = &Apache::lonnet::homeserver($touname,$toudom);
487: my $protocol = $Apache::lonnet::protocol{$homeserver};
488: $protocol = 'http' if ($protocol ne 'https');
489: my $url = $protocol.'://'.&Apache::lonnet::hostname($homeserver).
490: '/adm/email?username='.$touname.'&domain='.$toudom.
491: '&display='.&escape($msgid);
492: my ($sendtime,$shortsubj,$fromname,$fromdomain,$status,$fromcid,
493: $symb,$error) = &Apache::lonmsg::unpackmsgid($msgid);
494: my ($coursetext,$body,$bodybegin,$bodysubj,$bodyend);
495: my $user_lh = &Apache::loncommon::user_lang($touname,$toudom,$fromcid);
496: if ($fromcid ne '') {
497: $coursetext = "\n".&mt_user($user_lh,'Course').': ';
498: if ($env{'course.'.$fromcid.'.description'} ne '') {
499: $coursetext .= $env{'course.'.$fromcid.'.description'};
500: } else {
501: my %coursehash = &Apache::lonnet::coursedescription($fromcid,);
502: if ($coursehash{'description'} ne '') {
503: $coursetext .= $coursehash{'description'};
504: }
505: }
506: $coursetext .= "\n\n";
507: }
508: my @recipients = split(/,/,$to);
509: $bodybegin = $coursetext.
510: &mt_user($user_lh,
511: 'You received a'.$critical.' message from [_1] in LON-CAPA.',$sender).' ';
512: $bodysubj = &mt_user($user_lh,'The subject is
513:
514: [_1]
515:
516: ',$subj)."\n".
517: '=== '.&mt_user($user_lh,'Excerpt')." ============================================================
518: ";
519: $bodyend = "
520: ========================================================================
521:
522: ".&mt_user($user_lh,'Use
523:
524: [_1]
525:
526: to access the full message.',$url);
527: my %userenv = &Apache::lonnet::get('environment',['notifywithhtml'],$toudom,$touname);
528: my $subject = &mt_user($user_lh,"'New' $critical message from ").$sender;
529:
530: my ($blocked,$blocktext);
531: if (!$crit) {
532: my %setters;
533: my ($startblock,$endblock) =
534: &Apache::loncommon::blockcheck(\%setters,'com',$touname,$toudom);
535: if ($startblock && $endblock) {
536: $blocked = 1;
537: my $showstart = &Apache::lonlocal::locallocaltime($startblock);
538: my $showend = &Apache::lonlocal::locallocaltime($endblock);
539: $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);
540: }
541: }
542: if ($userenv{'notifywithhtml'} ne '') {
543: my @htmlexcerpt = split(/,/,$userenv{'notifywithhtml'});
544: my $htmlfree = &make_htmlfree($text);
545: foreach my $addr (@recipients) {
546: if ($blocked) {
547: $body = $bodybegin."\n".$blocktext."\n".$bodyend;
548: } else {
549: my $sendtext;
550: if (!grep/^\Q$addr\E/,@htmlexcerpt) {
551: $sendtext = $htmlfree;
552: } else {
553: $sendtext = $text;
554: }
555: $body = $bodybegin.$bodysubj.$sendtext.$bodyend;
556: }
557: &sendemail($addr,$subject,$body,$touname,$toudom,$user_lh);
558: }
559: } else {
560: if ($blocked) {
561: $body = $bodybegin."\n".$blocktext."\n".$bodyend;
562: } else {
563: my $htmlfree = &make_htmlfree($text);
564: $body = $bodybegin.$bodysubj.$htmlfree.$bodyend;
565: }
566: &sendemail($to,$subject,$body,$touname,$toudom,$user_lh);
567: }
568: }
569:
570: sub make_htmlfree {
571: my ($text) = @_;
572: $text =~ s/\<\/*[^\>]+\>//gs;
573: $text = &HTML::Entities::decode($text);
574: $text = &Encode::encode('utf8',$text);
575: return $text;
576: }
577:
578: sub mynewmail{
579: &newmail();
580: return $env{'user.mailcheck.lastnewmassagetime'} > $env{'user.mailcheck.lastvisit'};
581: }
582:
583:
584: sub newmail {
585: if ((time-$env{'user.mailcheck.time'})>300) {
586: my %what=&Apache::lonnet::get('email_status',['recnewemail']);
587: &Apache::lonnet::appenv({'user.mailcheck.time'=>time});
588: &Apache::lonnet::appenv({'user.mailcheck.lastnewmassagetime'=> $what{'recnewemail'}});
589: if ($what{'recnewemail'}>0) { return 1; }
590: }
591: return 0;
592: }
593:
594:
595:
596: sub author_res_msg {
597: my ($filename,$message)=@_;
598: unless ($message) { return 'empty'; }
599: $filename=&Apache::lonnet::declutter($filename);
600: my ($domain,$author,@dummy)=split(/\//,$filename);
601: my $homeserver=&Apache::lonnet::homeserver($author,$domain);
602: if ($homeserver ne 'no_host') {
603: my $id=unpack("%32C*",$message);
604: $message .= " <p>This error occurred on machine ".
605: $Apache::lonnet::perlvar{'lonHostID'}."</p>";
606: my $msgid;
607: ($msgid,$message)=&packagemsg($filename,$message);
608: return &Apache::lonnet::reply('put:'.$domain.':'.$author.
609: ':nohist_res_msgs:'.
610: &escape($filename.'_'.$id).'='.
611: &escape($message),$homeserver);
612: }
613: return 'no_host';
614: }
615:
616:
617:
618: sub retrieve_author_res_msg {
619: my $url=shift;
620: $url=&Apache::lonnet::declutter($url);
621: my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
622: my %errormsgs=&Apache::lonnet::dump('nohist_res_msgs',$domain,$author);
623: my $msgs='';
624: foreach (keys %errormsgs) {
625: if ($_=~/^\Q$url\E\_\d+$/) {
626: my %content=&unpackagemsg($errormsgs{$_});
627: $msgs.='<p><img src="/adm/lonMisc/bomb.gif" /><b>'.
628: $content{'time'}.'</b>: '.$content{'message'}.
629: '<br /></p>';
630: }
631: }
632: return $msgs;
633: }
634:
635:
636:
637:
638:
639: sub del_url_author_res_msg {
640: my $url=shift;
641: $url=&Apache::lonnet::declutter($url);
642: my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
643: my @delmsgs=();
644: foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
645: if ($_=~/^\Q$url\E\_\d+$/) {
646: push (@delmsgs,$_);
647: }
648: }
649: return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
650: }
651:
652:
653: sub clear_author_res_msg {
654: my $url=shift;
655: $url=&Apache::lonnet::declutter($url);
656: my ($domain,$author)=($url=~/^($match_domain)\/($match_username)\//);
657: my @delmsgs=();
658: foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
659: if ($_=~/^\Q$url\E/) {
660: push (@delmsgs,$_);
661: }
662: }
663: return &Apache::lonnet::del('nohist_res_msgs',\@delmsgs,$domain,$author);
664: }
665:
666:
667:
668: sub all_url_author_res_msg {
669: my ($author,$domain)=@_;
670: my %returnhash=();
671: foreach (&Apache::lonnet::getkeys('nohist_res_msgs',$domain,$author)) {
672: $_=~/^(.+)\_\d+/;
673: $returnhash{$1}=1;
674: }
675: return %returnhash;
676: }
677:
678:
679: sub store_instructor_comment {
680: my ($msg,$uname,$udom) = @_;
681: my $cid = $env{'request.course.id'};
682: my $cnum = $env{'course.'.$cid.'.num'};
683: my $cdom = $env{'course.'.$cid.'.domain'};
684: my $subject= &mt('Record').' ['.$uname.':'.$udom.']';
685: my $result = &user_normal_msg_raw($cnum,$cdom,$subject,$msg);
686: if ($result eq 'ok' || $result eq 'con_delayed') {
687:
688: }
689: return $result;
690: }
691:
692:
693: sub user_crit_msg_raw {
694: my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage,
695: $nosentstore,$recipid,$attachmenturl)=@_;
696: # Check if allowed missing
697: my ($status,$packed_message);
698: my $msgid='undefined';
699: unless (($message)&&($user)&&($domain)) { $status='empty'; };
700: my $text=$message;
701: my $homeserver=&Apache::lonnet::homeserver($user,$domain);
702: if ($homeserver ne 'no_host') {
703: ($msgid,$packed_message)=&packagemsg($subject,$message,undef,undef,
704: $attachmenturl,undef,undef,undef,undef,undef,
705: undef,undef,$recipid);
706: if ($sendback) { $packed_message.='<sendback>true</sendback>'; }
707: $status=&Apache::lonnet::cput('critical', {$msgid => $packed_message},
708: $domain,$user);
709: if (defined($sentmessage)) {
710: $$sentmessage = $packed_message;
711: }
712: if (!$nosentstore) {
713: (undef,my $packed_message_no_citation) =
714: &packagemsg($subject,$message,undef,undef,$attachmenturl,$user,
715: $domain,$msgid);
716: if ($status eq 'ok' || $status eq 'con_delayed') {
717: &store_sent_mail($msgid,$packed_message_no_citation);
718: }
719: }
720: } else {
721: $status='no_host';
722: }
723:
724: # Notifications
725: my %userenv = &Apache::loncommon::getemails($user,$domain);
726: if ($userenv{'critnotification'}) {
727: &sendnotification($userenv{'critnotification'},$user,$domain,$subject,1,
728: $text,$msgid);
729: }
730: if ($toperm && $userenv{'permanentemail'}) {
731: &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,1,
732: $text,$msgid);
733: }
734: # Log this
735: &Apache::lonnet::logthis(
736: 'Sending critical email '.$msgid.
737: ', log status: '.
738: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
739: $env{'user.home'},
740: 'Sending critical '.$msgid.' to '.$user.' at '.$domain.' with status: '
741: .$status));
742: return $status;
743: }
744:
745:
746:
747: sub user_crit_msg {
748: my ($user,$domain,$subject,$message,$sendback,$toperm,$sentmessage,
749: $nosentstore,$recipid,$attachmenturl)=@_;
750: my @status;
751: my %userenv = &Apache::lonnet::get('environment',['msgforward'],
752: $domain,$user);
753: my $msgforward=$userenv{'msgforward'};
754: if ($msgforward) {
755: foreach my $addr (split(/\,/,$msgforward)) {
756: my ($forwuser,$forwdomain)=split(/\:/,$addr);
757: push(@status,
758: &user_crit_msg_raw($forwuser,$forwdomain,$subject,$message,
759: $sendback,$toperm,$sentmessage,$nosentstore,
760: $recipid,$attachmenturl));
761: }
762: } else {
763: push(@status,
764: &user_crit_msg_raw($user,$domain,$subject,$message,$sendback,
765: $toperm,$sentmessage,$nosentstore,$recipid,
766: $attachmenturl));
767: }
768: if (wantarray) {
769: return @status;
770: }
771: return join(' ',@status);
772: }
773:
774:
775: sub user_crit_received {
776: my $msgid=shift;
777: my %message=&Apache::lonnet::get('critical',[$msgid]);
778: my %contents=&unpackagemsg($message{$msgid},1);
779: my $destname = $contents{'sendername'};
780: my $destdom = $contents{'senderdomain'};
781: if ($contents{'replytoaddr'}) {
782: my ($repname,$repdom) = split(/:/,$contents{'replytoaddr'});
783: if (&Apache::lonnet::homeserver($repname,$repdom) ne 'no_host') {
784: $destname = $repname;
785: $destdom = $repdom;
786: }
787: }
788: my $status='rec: '.($contents{'sendback'}?
789: &user_normal_msg($destname,$destdom,&mt('Receipt').': '.$env{'user.name'}.
790: ' '.&mt('at').' '.$env{'user.domain'}.', '.
791: $contents{'subject'},&mt('User').' '.$env{'user.name'}.
792: ' '.&mt('at').' '.$env{'user.domain'}.
793: ' acknowledged receipt of message'."\n".' "'.
794: $contents{'subject'}.'"'."\n".&mt('dated').' '.
795: $contents{'time'}.".\n"
796: ):'no msg req');
797: $status.=' trans: '.
798: &Apache::lonnet::put(
799: 'nohist_email',{$contents{'msgid'} => $message{$msgid}});
800: $status.=' del: '.
801: &Apache::lonnet::del('critical',[$contents{'msgid'}]);
802: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
803: $env{'user.home'},'Received critical message '.
804: $contents{'msgid'}.
805: ', '.$status);
806: return $status;
807: }
808:
809:
810:
811:
812: sub user_normal_msg_raw {
813: my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
814: $toperm,$currid,$newid,$sentmessage,$crsmsgid,$symb,$restitle,
815: $error,$nosentstore,$recipid)=@_;
816: # Check if allowed missing
817: my ($status,$packed_message);
818: my $msgid='undefined';
819: my $text=$message;
820: unless (($message)&&($user)&&($domain)) { $status='empty'; };
821: my $homeserver=&Apache::lonnet::homeserver($user,$domain);
822: if ($homeserver ne 'no_host') {
823: ($msgid,$packed_message)=
824: &packagemsg($subject,$message,$citation,$baseurl,
825: $attachmenturl,$user,$domain,$currid,
826: undef,$crsmsgid,$symb,$error,$recipid);
827:
828: # Store in user folder
829: $status=
830: &Apache::lonnet::cput('nohist_email',{$msgid => $packed_message},
831: $domain,$user);
832: # Save new message received time
833: &Apache::lonnet::put
834: ('email_status',{'recnewemail'=>time},$domain,$user);
835: # Into sent-mail folder if sent mail storage required
836: if (!$nosentstore) {
837: (undef,my $packed_message_no_citation) =
838: &packagemsg($subject,$message,undef,$baseurl,$attachmenturl,
839: $user,$domain,$currid,undef,$crsmsgid,$symb,$error);
840: if ($status eq 'ok' || $status eq 'con_delayed') {
841: &store_sent_mail($msgid,$packed_message_no_citation);
842: }
843: }
844: if (ref($newid) eq 'SCALAR') {
845: $$newid = $msgid;
846: }
847: if (ref($sentmessage) eq 'SCALAR') {
848: $$sentmessage = $packed_message;
849: }
850: # Notifications
851: my %userenv = &Apache::loncommon::getemails($user,$domain);
852: if ($userenv{'notification'}) {
853: &sendnotification($userenv{'notification'},$user,$domain,$subject,0,
854: $text,$msgid);
855: }
856: if ($toperm && $userenv{'permanentemail'}) {
857: if ((!$userenv{'notification'}) || ($userenv{'notification'} ne $userenv{'permanentemail'})) {
858: &sendnotification($userenv{'permanentemail'},$user,$domain,$subject,0,
859: $text,$msgid);
860: }
861: }
862: &Apache::lonnet::log($env{'user.domain'},$env{'user.name'},
863: $env{'user.home'},
864: 'Sending '.$msgid.' to '.$user.' at '.$domain.' with status: '.$status);
865: } else {
866: $status='no_host';
867: }
868: return $status;
869: }
870:
871: sub user_normal_msg {
872: my ($user,$domain,$subject,$message,$citation,$baseurl,$attachmenturl,
873: $toperm,$sentmessage,$symb,$restitle,$error,$nosentstore,$recipid)=@_;
874: my @status;
875: my %userenv = &Apache::lonnet::get('environment',['msgforward'],
876: $domain,$user);
877: my $msgforward=$userenv{'msgforward'};
878: if ($msgforward) {
879: foreach (split(/\,/,$msgforward)) {
880: my ($forwuser,$forwdomain)=split(/\:/,$_);
881: push(@status,
882: &user_normal_msg_raw($forwuser,$forwdomain,$subject,$message,
883: $citation,$baseurl,$attachmenturl,$toperm,
884: undef,undef,$sentmessage,undef,$symb,
885: $restitle,$error,$nosentstore,$recipid));
886: }
887: } else {
888: push(@status,&user_normal_msg_raw($user,$domain,$subject,$message,
889: $citation,$baseurl,$attachmenturl,$toperm,
890: undef,undef,$sentmessage,undef,$symb,
891: $restitle,$error,$nosentstore,$recipid));
892: }
893: if (wantarray) {
894: return @status;
895: }
896: return join(' ',@status);
897: }
898:
899: sub process_sent_mail {
900: my ($msgsubj,$subj_prefix,$numsent,$stamp,$msgname,$msgdom,$msgcount,$context,$pid,$savemsg,$recusers,$recudoms,$baseurl,$attachmenturl,$symb,$error,$senderuname,$senderdom,$recipid) = @_;
901: my $sentsubj;
902: if ($numsent > 1) {
903: $sentsubj = $subj_prefix.' ('.$numsent.' sent) '.$msgsubj;
904: } else {
905: if ($subj_prefix) {
906: $sentsubj = $subj_prefix.' ';
907: }
908: $sentsubj .= $msgsubj;
909: }
910: $sentsubj = &HTML::Entities::encode($sentsubj,'<>&"');
911: my $sentmsgid =
912: &buildmsgid($stamp,$sentsubj,$msgname,$msgdom,$msgcount,$context,$pid);
913: (undef,my $sentmessage) =
914: &packagemsg($msgsubj,$savemsg,undef,$baseurl,$attachmenturl,$recusers,
915: $recudoms,$sentmsgid,undef,undef,$symb,$error,$recipid);
916: my $status = &store_sent_mail($sentmsgid,$sentmessage,$senderuname,
917: $senderdom);
918: return $status;
919: }
920:
921: sub store_sent_mail {
922: my ($msgid,$message,$senderuname,$senderdom) = @_;
923: if ($senderuname eq '') {
924: $senderuname = $env{'user.name'};
925: }
926: if ($senderdom eq '') {
927: $senderdom = $env{'user.domain'};
928: }
929: my $status =' '.&Apache::lonnet::cput('nohist_email_sent',
930: {$msgid => $message},
931: $senderdom,$senderuname);
932: return $status;
933: }
934:
935: sub store_recipients {
936: my ($subject,$sendername,$senderdom,$reciphash) = @_;
937: my $context = &get_course_context();
938: my $now = time();
939: my $msgcount = &get_uniq();
940: my $recipid =
941: &buildmsgid($now,$subject,$sendername,$senderdom,$msgcount,$context,$$);
942: my %recipinfo = (
943: $recipid => $reciphash,
944: );
945: my $status = &Apache::lonnet::put('nohist_emailrecip',\%recipinfo,
946: $senderdom,$sendername);
947: if ($status eq 'ok') {
948: return ($recipid,$status);
949: } else {
950: return (undef,$status);
951: }
952: }
953:
954:
955: sub foldersuffix {
956: my $folder=shift;
957: unless ($folder) { return ''; }
958: my $suffix;
959: my %folderhash = &get_user_folders($folder);
960: if (ref($folderhash{$folder}) eq 'HASH') {
961: $suffix = '_'.&escape($folderhash{$folder}{'id'});
962: } else {
963: $suffix = '_'.&escape($folder);
964: }
965: return $suffix;
966: }
967:
968:
969: sub get_user_folders {
970: my ($folder) = @_;
971: my %userfolders =
972: &Apache::lonnet::dump('email_folders',undef,undef,$folder);
973: my $lock = "\0".'lock_counter'; # locks db while counter incremented
974: my $counter = "\0".'idcount'; # used in suffix for email db files
975: if (defined($userfolders{$lock})) {
976: delete($userfolders{$lock});
977: }
978: if (defined($userfolders{$counter})) {
979: delete($userfolders{$counter});
980: }
981: return %userfolders;
982: }
983:
984: sub secapply {
985: my $rec=shift;
986: my $defaultflag=shift;
987: $rec=~s/\s+//g;
988: $rec=~s/\@/\:/g;
989: my ($adr,$sections_or_groups)=($rec=~/^([^\(]+)\(([^\)]+)\)/);
990: if ($sections_or_groups) {
991: foreach my $item (split(/\;/,$sections_or_groups)) {
992: if (($item eq $env{'request.course.sec'}) ||
993: ($defaultflag && ($item eq '*'))) {
994: return $adr;
995: } elsif ($env{'request.course.groups'}) {
996: my @usersgroups = split(/:/,$env{'request.course.groups'});
997: if (grep(/^\Q$item\E$/,@usersgroups)) {
998: return $adr;
999: }
1000: }
1001: }
1002: } else {
1003: return $rec;
1004: }
1005: return '';
1006: }
1007:
1008: sub decide_receiver {
1009: my ($feedurl,$author,$question,$course,$policy,$defaultflag) = @_;
1010: &Apache::lonenc::check_decrypt(\$feedurl);
1011: my $typestyle='';
1012: my %to=();
1013: if ($env{'form.discuss'} eq 'author' ||$author) {
1014: $typestyle.='Submitting as Author Feedback<br />';
1015: $feedurl=~ m{^/res/($LONCAPA::domain_re)/($LONCAPA::username_re)/};
1016: $to{$2.':'.$1}=1;
1017: }
1018: my $cid = $env{'request.course.id'};
1019: if ($env{'form.discuss'} eq 'question' ||$question) {
1020: $typestyle.=&mt('Submitting as Question').'<br />';
1021: foreach my $item (split(/\,/,$env{'course.'.$cid.'.question.email'})) {
1022: my $rec=&secapply($item,$defaultflag);
1023: if ($rec) { $to{$rec}=1; }
1024: }
1025: }
1026: if ($env{'form.discuss'} eq 'course' ||$course) {
1027: $typestyle.=&mt('Submitting as Comment').'<br />';
1028: foreach my $item (split(/\,/,$env{'course.'.$cid.'.comment.email'})) {
1029: my $rec=&secapply($item,$defaultflag);
1030: if ($rec) { $to{$rec}=1; }
1031: }
1032: }
1033: if ($env{'form.discuss'} eq 'policy' ||$policy) {
1034: $typestyle.=&mt('Submitting as Policy Feedback').'<br />';
1035: foreach my $item (split(/\,/,$env{'course.'.$cid.'.policy.email'})) {
1036: my $rec=&secapply($item,$defaultflag);
1037: if ($rec) { $to{$rec}=1; }
1038: }
1039: }
1040: if ((scalar(%to) eq '0') && (!$defaultflag)) {
1041: ($typestyle,%to)=
1042: &decide_receiver($feedurl,$author,$question,$course,$policy,1);
1043: }
1044: return ($typestyle,%to);
1045: }
1046:
1047: 1;
1048: __END__
1049:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>